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 "ARMBaseInstrInfo.h" 16 #include "ARMBaseRegisterInfo.h" 17 #include "ARMCallingConv.h" 18 #include "ARMConstantPoolValue.h" 19 #include "ARMISelLowering.h" 20 #include "ARMMachineFunctionInfo.h" 21 #include "ARMPerfectShuffle.h" 22 #include "ARMRegisterInfo.h" 23 #include "ARMSelectionDAGInfo.h" 24 #include "ARMSubtarget.h" 25 #include "MCTargetDesc/ARMAddressingModes.h" 26 #include "MCTargetDesc/ARMBaseInfo.h" 27 #include "llvm/ADT/APFloat.h" 28 #include "llvm/ADT/APInt.h" 29 #include "llvm/ADT/ArrayRef.h" 30 #include "llvm/ADT/BitVector.h" 31 #include "llvm/ADT/DenseMap.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/STLExtras.h" 36 #include "llvm/ADT/StringExtras.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/ADT/StringRef.h" 39 #include "llvm/ADT/Triple.h" 40 #include "llvm/ADT/Twine.h" 41 #include "llvm/Analysis/VectorUtils.h" 42 #include "llvm/CodeGen/CallingConvLower.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/IntrinsicLowering.h" 45 #include "llvm/CodeGen/MachineBasicBlock.h" 46 #include "llvm/CodeGen/MachineConstantPool.h" 47 #include "llvm/CodeGen/MachineFrameInfo.h" 48 #include "llvm/CodeGen/MachineFunction.h" 49 #include "llvm/CodeGen/MachineInstr.h" 50 #include "llvm/CodeGen/MachineInstrBuilder.h" 51 #include "llvm/CodeGen/MachineJumpTableInfo.h" 52 #include "llvm/CodeGen/MachineMemOperand.h" 53 #include "llvm/CodeGen/MachineOperand.h" 54 #include "llvm/CodeGen/MachineRegisterInfo.h" 55 #include "llvm/CodeGen/MachineValueType.h" 56 #include "llvm/CodeGen/RuntimeLibcalls.h" 57 #include "llvm/CodeGen/SelectionDAG.h" 58 #include "llvm/CodeGen/SelectionDAGNodes.h" 59 #include "llvm/CodeGen/ValueTypes.h" 60 #include "llvm/IR/Attributes.h" 61 #include "llvm/IR/CallingConv.h" 62 #include "llvm/IR/Constant.h" 63 #include "llvm/IR/Constants.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugLoc.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/Function.h" 69 #include "llvm/IR/GlobalAlias.h" 70 #include "llvm/IR/GlobalValue.h" 71 #include "llvm/IR/GlobalVariable.h" 72 #include "llvm/IR/IRBuilder.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/Instruction.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/Module.h" 79 #include "llvm/IR/Type.h" 80 #include "llvm/IR/User.h" 81 #include "llvm/IR/Value.h" 82 #include "llvm/MC/MCInstrDesc.h" 83 #include "llvm/MC/MCInstrItineraries.h" 84 #include "llvm/MC/MCRegisterInfo.h" 85 #include "llvm/MC/MCSchedule.h" 86 #include "llvm/Support/AtomicOrdering.h" 87 #include "llvm/Support/BranchProbability.h" 88 #include "llvm/Support/Casting.h" 89 #include "llvm/Support/CodeGen.h" 90 #include "llvm/Support/CommandLine.h" 91 #include "llvm/Support/Compiler.h" 92 #include "llvm/Support/Debug.h" 93 #include "llvm/Support/ErrorHandling.h" 94 #include "llvm/Support/MathExtras.h" 95 #include "llvm/Support/raw_ostream.h" 96 #include "llvm/Target/TargetInstrInfo.h" 97 #include "llvm/Target/TargetMachine.h" 98 #include "llvm/Target/TargetOptions.h" 99 #include <algorithm> 100 #include <cassert> 101 #include <cstdint> 102 #include <cstdlib> 103 #include <iterator> 104 #include <limits> 105 #include <tuple> 106 #include <string> 107 #include <utility> 108 #include <vector> 109 110 using namespace llvm; 111 112 #define DEBUG_TYPE "arm-isel" 113 114 STATISTIC(NumTailCalls, "Number of tail calls"); 115 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 116 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 117 STATISTIC(NumConstpoolPromoted, 118 "Number of constants with their storage promoted into constant pools"); 119 120 static cl::opt<bool> 121 ARMInterworking("arm-interworking", cl::Hidden, 122 cl::desc("Enable / disable ARM interworking (for debugging only)"), 123 cl::init(true)); 124 125 static cl::opt<bool> EnableConstpoolPromotion( 126 "arm-promote-constant", cl::Hidden, 127 cl::desc("Enable / disable promotion of unnamed_addr constants into " 128 "constant pools"), 129 cl::init(true)); 130 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 131 "arm-promote-constant-max-size", cl::Hidden, 132 cl::desc("Maximum size of constant to promote into a constant pool"), 133 cl::init(64)); 134 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 135 "arm-promote-constant-max-total", cl::Hidden, 136 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 137 cl::init(128)); 138 139 // The APCS parameter registers. 140 static const MCPhysReg GPRArgRegs[] = { 141 ARM::R0, ARM::R1, ARM::R2, ARM::R3 142 }; 143 144 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 145 MVT PromotedBitwiseVT) { 146 if (VT != PromotedLdStVT) { 147 setOperationAction(ISD::LOAD, VT, Promote); 148 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 149 150 setOperationAction(ISD::STORE, VT, Promote); 151 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 152 } 153 154 MVT ElemTy = VT.getVectorElementType(); 155 if (ElemTy != MVT::f64) 156 setOperationAction(ISD::SETCC, VT, Custom); 157 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 158 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 159 if (ElemTy == MVT::i32) { 160 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 161 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 162 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 163 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 164 } else { 165 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 166 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 167 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 168 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 169 } 170 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 171 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 172 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 173 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 174 setOperationAction(ISD::SELECT, VT, Expand); 175 setOperationAction(ISD::SELECT_CC, VT, Expand); 176 setOperationAction(ISD::VSELECT, VT, Expand); 177 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 178 if (VT.isInteger()) { 179 setOperationAction(ISD::SHL, VT, Custom); 180 setOperationAction(ISD::SRA, VT, Custom); 181 setOperationAction(ISD::SRL, VT, Custom); 182 } 183 184 // Promote all bit-wise operations. 185 if (VT.isInteger() && VT != PromotedBitwiseVT) { 186 setOperationAction(ISD::AND, VT, Promote); 187 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 188 setOperationAction(ISD::OR, VT, Promote); 189 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 190 setOperationAction(ISD::XOR, VT, Promote); 191 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 192 } 193 194 // Neon does not support vector divide/remainder operations. 195 setOperationAction(ISD::SDIV, VT, Expand); 196 setOperationAction(ISD::UDIV, VT, Expand); 197 setOperationAction(ISD::FDIV, VT, Expand); 198 setOperationAction(ISD::SREM, VT, Expand); 199 setOperationAction(ISD::UREM, VT, Expand); 200 setOperationAction(ISD::FREM, VT, Expand); 201 202 if (!VT.isFloatingPoint() && 203 VT != MVT::v2i64 && VT != MVT::v1i64) 204 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 205 setOperationAction(Opcode, VT, Legal); 206 } 207 208 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 209 addRegisterClass(VT, &ARM::DPRRegClass); 210 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 211 } 212 213 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 214 addRegisterClass(VT, &ARM::DPairRegClass); 215 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 216 } 217 218 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 219 const ARMSubtarget &STI) 220 : TargetLowering(TM), Subtarget(&STI) { 221 RegInfo = Subtarget->getRegisterInfo(); 222 Itins = Subtarget->getInstrItineraryData(); 223 224 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 225 226 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 227 !Subtarget->isTargetWatchOS()) { 228 const auto &E = Subtarget->getTargetTriple().getEnvironment(); 229 230 bool IsHFTarget = E == Triple::EABIHF || E == Triple::GNUEABIHF || 231 E == Triple::MuslEABIHF; 232 // Windows is a special case. Technically, we will replace all of the "GNU" 233 // calls with calls to MSVCRT if appropriate and adjust the calling 234 // convention then. 235 IsHFTarget = IsHFTarget || Subtarget->isTargetWindows(); 236 237 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 238 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 239 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 240 : CallingConv::ARM_AAPCS); 241 } 242 243 if (Subtarget->isTargetMachO()) { 244 // Uses VFP for Thumb libfuncs if available. 245 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 246 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 247 static const struct { 248 const RTLIB::Libcall Op; 249 const char * const Name; 250 const ISD::CondCode Cond; 251 } LibraryCalls[] = { 252 // Single-precision floating-point arithmetic. 253 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 254 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 255 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 256 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 257 258 // Double-precision floating-point arithmetic. 259 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 260 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 261 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 262 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 263 264 // Single-precision comparisons. 265 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 266 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 267 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 268 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 269 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 270 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 271 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 272 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 273 274 // Double-precision comparisons. 275 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 276 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 277 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 278 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 279 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 280 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 281 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 282 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 283 284 // Floating-point to integer conversions. 285 // i64 conversions are done via library routines even when generating VFP 286 // instructions, so use the same ones. 287 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 288 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 289 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 290 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 291 292 // Conversions between floating types. 293 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 294 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 295 296 // Integer to floating-point conversions. 297 // i64 conversions are done via library routines even when generating VFP 298 // instructions, so use the same ones. 299 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 300 // e.g., __floatunsidf vs. __floatunssidfvfp. 301 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 302 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 303 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 304 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 305 }; 306 307 for (const auto &LC : LibraryCalls) { 308 setLibcallName(LC.Op, LC.Name); 309 if (LC.Cond != ISD::SETCC_INVALID) 310 setCmpLibcallCC(LC.Op, LC.Cond); 311 } 312 } 313 314 // Set the correct calling convention for ARMv7k WatchOS. It's just 315 // AAPCS_VFP for functions as simple as libcalls. 316 if (Subtarget->isTargetWatchABI()) { 317 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 318 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 319 } 320 } 321 322 // These libcalls are not available in 32-bit. 323 setLibcallName(RTLIB::SHL_I128, nullptr); 324 setLibcallName(RTLIB::SRL_I128, nullptr); 325 setLibcallName(RTLIB::SRA_I128, nullptr); 326 327 // RTLIB 328 if (Subtarget->isAAPCS_ABI() && 329 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 330 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 331 static const struct { 332 const RTLIB::Libcall Op; 333 const char * const Name; 334 const CallingConv::ID CC; 335 const ISD::CondCode Cond; 336 } LibraryCalls[] = { 337 // Double-precision floating-point arithmetic helper functions 338 // RTABI chapter 4.1.2, Table 2 339 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 342 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 343 344 // Double-precision floating-point comparison helper functions 345 // RTABI chapter 4.1.2, Table 3 346 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 347 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 348 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 349 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 350 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 351 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 352 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 353 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 354 355 // Single-precision floating-point arithmetic helper functions 356 // RTABI chapter 4.1.2, Table 4 357 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 358 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 359 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 360 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 361 362 // Single-precision floating-point comparison helper functions 363 // RTABI chapter 4.1.2, Table 5 364 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 365 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 366 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 367 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 368 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 369 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 370 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 371 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 372 373 // Floating-point to integer conversions. 374 // RTABI chapter 4.1.2, Table 6 375 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 376 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 377 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 378 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 379 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 380 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 381 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 382 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 383 384 // Conversions between floating types. 385 // RTABI chapter 4.1.2, Table 7 386 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 387 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 388 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 389 390 // Integer to floating-point conversions. 391 // RTABI chapter 4.1.2, Table 8 392 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 393 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 394 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 395 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 396 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 397 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 398 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 399 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 400 401 // Long long helper functions 402 // RTABI chapter 4.2, Table 9 403 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 404 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 405 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 406 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 407 408 // Integer division functions 409 // RTABI chapter 4.3.1 410 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 411 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 412 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 413 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 414 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 415 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 416 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 417 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 418 }; 419 420 for (const auto &LC : LibraryCalls) { 421 setLibcallName(LC.Op, LC.Name); 422 setLibcallCallingConv(LC.Op, LC.CC); 423 if (LC.Cond != ISD::SETCC_INVALID) 424 setCmpLibcallCC(LC.Op, LC.Cond); 425 } 426 427 // EABI dependent RTLIB 428 if (TM.Options.EABIVersion == EABI::EABI4 || 429 TM.Options.EABIVersion == EABI::EABI5) { 430 static const struct { 431 const RTLIB::Libcall Op; 432 const char *const Name; 433 const CallingConv::ID CC; 434 const ISD::CondCode Cond; 435 } MemOpsLibraryCalls[] = { 436 // Memory operations 437 // RTABI chapter 4.3.4 438 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 439 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 440 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 441 }; 442 443 for (const auto &LC : MemOpsLibraryCalls) { 444 setLibcallName(LC.Op, LC.Name); 445 setLibcallCallingConv(LC.Op, LC.CC); 446 if (LC.Cond != ISD::SETCC_INVALID) 447 setCmpLibcallCC(LC.Op, LC.Cond); 448 } 449 } 450 } 451 452 if (Subtarget->isTargetWindows()) { 453 static const struct { 454 const RTLIB::Libcall Op; 455 const char * const Name; 456 const CallingConv::ID CC; 457 } LibraryCalls[] = { 458 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 459 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 460 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 461 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 462 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 463 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 464 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 465 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 466 }; 467 468 for (const auto &LC : LibraryCalls) { 469 setLibcallName(LC.Op, LC.Name); 470 setLibcallCallingConv(LC.Op, LC.CC); 471 } 472 } 473 474 // Use divmod compiler-rt calls for iOS 5.0 and later. 475 if (Subtarget->isTargetWatchOS() || 476 (Subtarget->isTargetIOS() && 477 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 478 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 479 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 480 } 481 482 // The half <-> float conversion functions are always soft-float on 483 // non-watchos platforms, but are needed for some targets which use a 484 // hard-float calling convention by default. 485 if (!Subtarget->isTargetWatchABI()) { 486 if (Subtarget->isAAPCS_ABI()) { 487 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 488 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 489 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 490 } else { 491 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 492 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 493 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 494 } 495 } 496 497 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 498 // a __gnu_ prefix (which is the default). 499 if (Subtarget->isTargetAEABI()) { 500 static const struct { 501 const RTLIB::Libcall Op; 502 const char * const Name; 503 const CallingConv::ID CC; 504 } LibraryCalls[] = { 505 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 506 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 507 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 508 }; 509 510 for (const auto &LC : LibraryCalls) { 511 setLibcallName(LC.Op, LC.Name); 512 setLibcallCallingConv(LC.Op, LC.CC); 513 } 514 } 515 516 if (Subtarget->isThumb1Only()) 517 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 518 else 519 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 520 521 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 522 !Subtarget->isThumb1Only()) { 523 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 524 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 525 } 526 527 for (MVT VT : MVT::vector_valuetypes()) { 528 for (MVT InnerVT : MVT::vector_valuetypes()) { 529 setTruncStoreAction(VT, InnerVT, Expand); 530 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 531 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 532 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 533 } 534 535 setOperationAction(ISD::MULHS, VT, Expand); 536 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 537 setOperationAction(ISD::MULHU, VT, Expand); 538 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 539 540 setOperationAction(ISD::BSWAP, VT, Expand); 541 } 542 543 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 544 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 545 546 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 547 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 548 549 if (Subtarget->hasNEON()) { 550 addDRTypeForNEON(MVT::v2f32); 551 addDRTypeForNEON(MVT::v8i8); 552 addDRTypeForNEON(MVT::v4i16); 553 addDRTypeForNEON(MVT::v2i32); 554 addDRTypeForNEON(MVT::v1i64); 555 556 addQRTypeForNEON(MVT::v4f32); 557 addQRTypeForNEON(MVT::v2f64); 558 addQRTypeForNEON(MVT::v16i8); 559 addQRTypeForNEON(MVT::v8i16); 560 addQRTypeForNEON(MVT::v4i32); 561 addQRTypeForNEON(MVT::v2i64); 562 563 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 564 // neither Neon nor VFP support any arithmetic operations on it. 565 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 566 // supported for v4f32. 567 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 568 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 569 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 570 // FIXME: Code duplication: FDIV and FREM are expanded always, see 571 // ARMTargetLowering::addTypeForNEON method for details. 572 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 573 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 574 // FIXME: Create unittest. 575 // In another words, find a way when "copysign" appears in DAG with vector 576 // operands. 577 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 578 // FIXME: Code duplication: SETCC has custom operation action, see 579 // ARMTargetLowering::addTypeForNEON method for details. 580 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 581 // FIXME: Create unittest for FNEG and for FABS. 582 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 583 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 584 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 585 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 586 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 587 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 588 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 589 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 590 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 591 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 592 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 593 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 594 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 595 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 596 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 597 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 598 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 599 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 600 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 601 602 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 603 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 604 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 605 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 606 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 607 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 608 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 609 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 610 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 611 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 612 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 613 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 614 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 615 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 616 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 617 618 // Mark v2f32 intrinsics. 619 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 620 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 621 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 622 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 623 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 624 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 625 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 626 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 627 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 628 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 629 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 630 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 631 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 632 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 633 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 634 635 // Neon does not support some operations on v1i64 and v2i64 types. 636 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 637 // Custom handling for some quad-vector types to detect VMULL. 638 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 639 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 640 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 641 // Custom handling for some vector types to avoid expensive expansions 642 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 643 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 644 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 645 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 646 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 647 // a destination type that is wider than the source, and nor does 648 // it have a FP_TO_[SU]INT instruction with a narrower destination than 649 // source. 650 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 651 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 652 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 653 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 654 655 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 656 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 657 658 // NEON does not have single instruction CTPOP for vectors with element 659 // types wider than 8-bits. However, custom lowering can leverage the 660 // v8i8/v16i8 vcnt instruction. 661 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 662 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 663 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 664 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 665 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 666 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 667 668 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 669 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 670 671 // NEON does not have single instruction CTTZ for vectors. 672 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 673 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 674 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 675 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 676 677 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 678 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 679 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 680 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 681 682 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 683 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 684 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 685 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 686 687 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 688 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 689 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 690 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 691 692 // NEON only has FMA instructions as of VFP4. 693 if (!Subtarget->hasVFP4()) { 694 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 695 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 696 } 697 698 setTargetDAGCombine(ISD::INTRINSIC_VOID); 699 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 700 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 701 setTargetDAGCombine(ISD::SHL); 702 setTargetDAGCombine(ISD::SRL); 703 setTargetDAGCombine(ISD::SRA); 704 setTargetDAGCombine(ISD::SIGN_EXTEND); 705 setTargetDAGCombine(ISD::ZERO_EXTEND); 706 setTargetDAGCombine(ISD::ANY_EXTEND); 707 setTargetDAGCombine(ISD::BUILD_VECTOR); 708 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 709 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 710 setTargetDAGCombine(ISD::STORE); 711 setTargetDAGCombine(ISD::FP_TO_SINT); 712 setTargetDAGCombine(ISD::FP_TO_UINT); 713 setTargetDAGCombine(ISD::FDIV); 714 setTargetDAGCombine(ISD::LOAD); 715 716 // It is legal to extload from v4i8 to v4i16 or v4i32. 717 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 718 MVT::v2i32}) { 719 for (MVT VT : MVT::integer_vector_valuetypes()) { 720 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 721 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 722 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 723 } 724 } 725 } 726 727 // ARM and Thumb2 support UMLAL/SMLAL. 728 if (!Subtarget->isThumb1Only()) 729 setTargetDAGCombine(ISD::ADDC); 730 731 if (Subtarget->isFPOnlySP()) { 732 // When targeting a floating-point unit with only single-precision 733 // operations, f64 is legal for the few double-precision instructions which 734 // are present However, no double-precision operations other than moves, 735 // loads and stores are provided by the hardware. 736 setOperationAction(ISD::FADD, MVT::f64, Expand); 737 setOperationAction(ISD::FSUB, MVT::f64, Expand); 738 setOperationAction(ISD::FMUL, MVT::f64, Expand); 739 setOperationAction(ISD::FMA, MVT::f64, Expand); 740 setOperationAction(ISD::FDIV, MVT::f64, Expand); 741 setOperationAction(ISD::FREM, MVT::f64, Expand); 742 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 743 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 744 setOperationAction(ISD::FNEG, MVT::f64, Expand); 745 setOperationAction(ISD::FABS, MVT::f64, Expand); 746 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 747 setOperationAction(ISD::FSIN, MVT::f64, Expand); 748 setOperationAction(ISD::FCOS, MVT::f64, Expand); 749 setOperationAction(ISD::FPOWI, MVT::f64, Expand); 750 setOperationAction(ISD::FPOW, MVT::f64, Expand); 751 setOperationAction(ISD::FLOG, MVT::f64, Expand); 752 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 753 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 754 setOperationAction(ISD::FEXP, MVT::f64, Expand); 755 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 756 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 757 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 758 setOperationAction(ISD::FRINT, MVT::f64, Expand); 759 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 760 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 761 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 762 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 763 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 764 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 765 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 766 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 767 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 768 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 769 } 770 771 computeRegisterProperties(Subtarget->getRegisterInfo()); 772 773 // ARM does not have floating-point extending loads. 774 for (MVT VT : MVT::fp_valuetypes()) { 775 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 776 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 777 } 778 779 // ... or truncating stores 780 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 781 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 782 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 783 784 // ARM does not have i1 sign extending load. 785 for (MVT VT : MVT::integer_valuetypes()) 786 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 787 788 // ARM supports all 4 flavors of integer indexed load / store. 789 if (!Subtarget->isThumb1Only()) { 790 for (unsigned im = (unsigned)ISD::PRE_INC; 791 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 792 setIndexedLoadAction(im, MVT::i1, Legal); 793 setIndexedLoadAction(im, MVT::i8, Legal); 794 setIndexedLoadAction(im, MVT::i16, Legal); 795 setIndexedLoadAction(im, MVT::i32, Legal); 796 setIndexedStoreAction(im, MVT::i1, Legal); 797 setIndexedStoreAction(im, MVT::i8, Legal); 798 setIndexedStoreAction(im, MVT::i16, Legal); 799 setIndexedStoreAction(im, MVT::i32, Legal); 800 } 801 } else { 802 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 803 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 804 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 805 } 806 807 setOperationAction(ISD::SADDO, MVT::i32, Custom); 808 setOperationAction(ISD::UADDO, MVT::i32, Custom); 809 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 810 setOperationAction(ISD::USUBO, MVT::i32, Custom); 811 812 // i64 operation support. 813 setOperationAction(ISD::MUL, MVT::i64, Expand); 814 setOperationAction(ISD::MULHU, MVT::i32, Expand); 815 if (Subtarget->isThumb1Only()) { 816 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 817 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 818 } 819 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 820 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 821 setOperationAction(ISD::MULHS, MVT::i32, Expand); 822 823 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 824 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 825 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 826 setOperationAction(ISD::SRL, MVT::i64, Custom); 827 setOperationAction(ISD::SRA, MVT::i64, Custom); 828 829 if (!Subtarget->isThumb1Only()) { 830 // FIXME: We should do this for Thumb1 as well. 831 setOperationAction(ISD::ADDC, MVT::i32, Custom); 832 setOperationAction(ISD::ADDE, MVT::i32, Custom); 833 setOperationAction(ISD::SUBC, MVT::i32, Custom); 834 setOperationAction(ISD::SUBE, MVT::i32, Custom); 835 } 836 837 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 838 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 839 840 // ARM does not have ROTL. 841 setOperationAction(ISD::ROTL, MVT::i32, Expand); 842 for (MVT VT : MVT::vector_valuetypes()) { 843 setOperationAction(ISD::ROTL, VT, Expand); 844 setOperationAction(ISD::ROTR, VT, Expand); 845 } 846 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 847 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 848 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 849 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 850 851 // @llvm.readcyclecounter requires the Performance Monitors extension. 852 // Default to the 0 expansion on unsupported platforms. 853 // FIXME: Technically there are older ARM CPUs that have 854 // implementation-specific ways of obtaining this information. 855 if (Subtarget->hasPerfMon()) 856 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 857 858 // Only ARMv6 has BSWAP. 859 if (!Subtarget->hasV6Ops()) 860 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 861 862 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide() 863 : Subtarget->hasDivideInARMMode(); 864 if (!hasDivide) { 865 // These are expanded into libcalls if the cpu doesn't have HW divider. 866 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 867 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 868 } 869 870 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) { 871 setOperationAction(ISD::SDIV, MVT::i32, Custom); 872 setOperationAction(ISD::UDIV, MVT::i32, Custom); 873 874 setOperationAction(ISD::SDIV, MVT::i64, Custom); 875 setOperationAction(ISD::UDIV, MVT::i64, Custom); 876 } 877 878 setOperationAction(ISD::SREM, MVT::i32, Expand); 879 setOperationAction(ISD::UREM, MVT::i32, Expand); 880 881 // Register based DivRem for AEABI (RTABI 4.2) 882 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 883 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 884 Subtarget->isTargetWindows()) { 885 setOperationAction(ISD::SREM, MVT::i64, Custom); 886 setOperationAction(ISD::UREM, MVT::i64, Custom); 887 HasStandaloneRem = false; 888 889 if (Subtarget->isTargetWindows()) { 890 const struct { 891 const RTLIB::Libcall Op; 892 const char * const Name; 893 const CallingConv::ID CC; 894 } LibraryCalls[] = { 895 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 896 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 897 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 898 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 899 900 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 901 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 902 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 903 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 904 }; 905 906 for (const auto &LC : LibraryCalls) { 907 setLibcallName(LC.Op, LC.Name); 908 setLibcallCallingConv(LC.Op, LC.CC); 909 } 910 } else { 911 const struct { 912 const RTLIB::Libcall Op; 913 const char * const Name; 914 const CallingConv::ID CC; 915 } LibraryCalls[] = { 916 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 917 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 918 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 919 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 920 921 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 922 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 923 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 924 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 925 }; 926 927 for (const auto &LC : LibraryCalls) { 928 setLibcallName(LC.Op, LC.Name); 929 setLibcallCallingConv(LC.Op, LC.CC); 930 } 931 } 932 933 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 934 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 935 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 936 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 937 } else { 938 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 939 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 940 } 941 942 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 943 for (auto &VT : {MVT::f32, MVT::f64}) 944 setOperationAction(ISD::FPOWI, VT, Custom); 945 946 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 947 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 948 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 949 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 950 951 setOperationAction(ISD::TRAP, MVT::Other, Legal); 952 953 // Use the default implementation. 954 setOperationAction(ISD::VASTART, MVT::Other, Custom); 955 setOperationAction(ISD::VAARG, MVT::Other, Expand); 956 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 957 setOperationAction(ISD::VAEND, MVT::Other, Expand); 958 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 959 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 960 961 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 962 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 963 else 964 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 965 966 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 967 // the default expansion. 968 InsertFencesForAtomic = false; 969 if (Subtarget->hasAnyDataBarrier() && 970 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 971 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 972 // to ldrex/strex loops already. 973 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 974 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 975 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 976 977 // On v8, we have particularly efficient implementations of atomic fences 978 // if they can be combined with nearby atomic loads and stores. 979 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 980 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 981 InsertFencesForAtomic = true; 982 } 983 } else { 984 // If there's anything we can use as a barrier, go through custom lowering 985 // for ATOMIC_FENCE. 986 // If target has DMB in thumb, Fences can be inserted. 987 if (Subtarget->hasDataBarrier()) 988 InsertFencesForAtomic = true; 989 990 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 991 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 992 993 // Set them all for expansion, which will force libcalls. 994 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 995 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 996 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 997 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 998 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 999 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1000 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1001 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1002 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1003 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1004 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1005 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1006 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1007 // Unordered/Monotonic case. 1008 if (!InsertFencesForAtomic) { 1009 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1010 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1011 } 1012 } 1013 1014 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1015 1016 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1017 if (!Subtarget->hasV6Ops()) { 1018 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1019 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1020 } 1021 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1022 1023 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1024 !Subtarget->isThumb1Only()) { 1025 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1026 // iff target supports vfp2. 1027 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1028 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1029 } 1030 1031 // We want to custom lower some of our intrinsics. 1032 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1033 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1034 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1035 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1036 if (Subtarget->useSjLjEH()) 1037 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1038 1039 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1040 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1041 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1042 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1043 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1044 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1045 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1046 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1047 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1048 1049 // Thumb-1 cannot currently select ARMISD::SUBE. 1050 if (!Subtarget->isThumb1Only()) 1051 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 1052 1053 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 1054 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1055 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1056 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1057 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1058 1059 // We don't support sin/cos/fmod/copysign/pow 1060 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1061 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1062 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1063 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1064 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1065 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1066 setOperationAction(ISD::FREM, MVT::f64, Expand); 1067 setOperationAction(ISD::FREM, MVT::f32, Expand); 1068 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1069 !Subtarget->isThumb1Only()) { 1070 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1071 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1072 } 1073 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1074 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1075 1076 if (!Subtarget->hasVFP4()) { 1077 setOperationAction(ISD::FMA, MVT::f64, Expand); 1078 setOperationAction(ISD::FMA, MVT::f32, Expand); 1079 } 1080 1081 // Various VFP goodness 1082 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1083 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1084 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1085 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1086 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1087 } 1088 1089 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1090 if (!Subtarget->hasFP16()) { 1091 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1092 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1093 } 1094 } 1095 1096 // Combine sin / cos into one node or libcall if possible. 1097 if (Subtarget->hasSinCos()) { 1098 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 1099 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 1100 if (Subtarget->isTargetWatchABI()) { 1101 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 1102 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 1103 } 1104 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 1105 // For iOS, we don't want to the normal expansion of a libcall to 1106 // sincos. We want to issue a libcall to __sincos_stret. 1107 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1108 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1109 } 1110 } 1111 1112 // FP-ARMv8 implements a lot of rounding-like FP operations. 1113 if (Subtarget->hasFPARMv8()) { 1114 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1115 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1116 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1117 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1118 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1119 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1120 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1121 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1122 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1123 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1124 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1125 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1126 1127 if (!Subtarget->isFPOnlySP()) { 1128 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1129 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1130 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1131 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1132 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1133 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1134 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1135 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1136 } 1137 } 1138 1139 if (Subtarget->hasNEON()) { 1140 // vmin and vmax aren't available in a scalar form, so we use 1141 // a NEON instruction with an undef lane instead. 1142 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1143 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1144 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1145 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1146 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1147 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1148 } 1149 1150 // We have target-specific dag combine patterns for the following nodes: 1151 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1152 setTargetDAGCombine(ISD::ADD); 1153 setTargetDAGCombine(ISD::SUB); 1154 setTargetDAGCombine(ISD::MUL); 1155 setTargetDAGCombine(ISD::AND); 1156 setTargetDAGCombine(ISD::OR); 1157 setTargetDAGCombine(ISD::XOR); 1158 1159 if (Subtarget->hasV6Ops()) 1160 setTargetDAGCombine(ISD::SRL); 1161 1162 setStackPointerRegisterToSaveRestore(ARM::SP); 1163 1164 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1165 !Subtarget->hasVFP2()) 1166 setSchedulingPreference(Sched::RegPressure); 1167 else 1168 setSchedulingPreference(Sched::Hybrid); 1169 1170 //// temporary - rewrite interface to use type 1171 MaxStoresPerMemset = 8; 1172 MaxStoresPerMemsetOptSize = 4; 1173 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1174 MaxStoresPerMemcpyOptSize = 2; 1175 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1176 MaxStoresPerMemmoveOptSize = 2; 1177 1178 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1179 // are at least 4 bytes aligned. 1180 setMinStackArgumentAlignment(4); 1181 1182 // Prefer likely predicted branches to selects on out-of-order cores. 1183 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1184 1185 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1186 } 1187 1188 bool ARMTargetLowering::useSoftFloat() const { 1189 return Subtarget->useSoftFloat(); 1190 } 1191 1192 // FIXME: It might make sense to define the representative register class as the 1193 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1194 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1195 // SPR's representative would be DPR_VFP2. This should work well if register 1196 // pressure tracking were modified such that a register use would increment the 1197 // pressure of the register class's representative and all of it's super 1198 // classes' representatives transitively. We have not implemented this because 1199 // of the difficulty prior to coalescing of modeling operand register classes 1200 // due to the common occurrence of cross class copies and subregister insertions 1201 // and extractions. 1202 std::pair<const TargetRegisterClass *, uint8_t> 1203 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1204 MVT VT) const { 1205 const TargetRegisterClass *RRC = nullptr; 1206 uint8_t Cost = 1; 1207 switch (VT.SimpleTy) { 1208 default: 1209 return TargetLowering::findRepresentativeClass(TRI, VT); 1210 // Use DPR as representative register class for all floating point 1211 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1212 // the cost is 1 for both f32 and f64. 1213 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1214 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1215 RRC = &ARM::DPRRegClass; 1216 // When NEON is used for SP, only half of the register file is available 1217 // because operations that define both SP and DP results will be constrained 1218 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1219 // coalescing by double-counting the SP regs. See the FIXME above. 1220 if (Subtarget->useNEONForSinglePrecisionFP()) 1221 Cost = 2; 1222 break; 1223 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1224 case MVT::v4f32: case MVT::v2f64: 1225 RRC = &ARM::DPRRegClass; 1226 Cost = 2; 1227 break; 1228 case MVT::v4i64: 1229 RRC = &ARM::DPRRegClass; 1230 Cost = 4; 1231 break; 1232 case MVT::v8i64: 1233 RRC = &ARM::DPRRegClass; 1234 Cost = 8; 1235 break; 1236 } 1237 return std::make_pair(RRC, Cost); 1238 } 1239 1240 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1241 switch ((ARMISD::NodeType)Opcode) { 1242 case ARMISD::FIRST_NUMBER: break; 1243 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1244 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1245 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1246 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1247 case ARMISD::CALL: return "ARMISD::CALL"; 1248 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1249 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1250 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1251 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1252 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1253 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1254 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1255 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1256 case ARMISD::CMP: return "ARMISD::CMP"; 1257 case ARMISD::CMN: return "ARMISD::CMN"; 1258 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1259 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1260 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1261 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1262 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1263 1264 case ARMISD::CMOV: return "ARMISD::CMOV"; 1265 1266 case ARMISD::SSAT: return "ARMISD::SSAT"; 1267 1268 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1269 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1270 case ARMISD::RRX: return "ARMISD::RRX"; 1271 1272 case ARMISD::ADDC: return "ARMISD::ADDC"; 1273 case ARMISD::ADDE: return "ARMISD::ADDE"; 1274 case ARMISD::SUBC: return "ARMISD::SUBC"; 1275 case ARMISD::SUBE: return "ARMISD::SUBE"; 1276 1277 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1278 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1279 1280 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1281 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1282 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1283 1284 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1285 1286 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1287 1288 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1289 1290 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1291 1292 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1293 1294 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1295 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1296 1297 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1298 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1299 case ARMISD::VCGE: return "ARMISD::VCGE"; 1300 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1301 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1302 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1303 case ARMISD::VCGT: return "ARMISD::VCGT"; 1304 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1305 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1306 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1307 case ARMISD::VTST: return "ARMISD::VTST"; 1308 1309 case ARMISD::VSHL: return "ARMISD::VSHL"; 1310 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1311 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1312 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1313 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1314 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1315 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1316 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1317 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1318 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1319 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1320 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1321 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1322 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1323 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1324 case ARMISD::VSLI: return "ARMISD::VSLI"; 1325 case ARMISD::VSRI: return "ARMISD::VSRI"; 1326 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1327 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1328 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1329 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1330 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1331 case ARMISD::VDUP: return "ARMISD::VDUP"; 1332 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1333 case ARMISD::VEXT: return "ARMISD::VEXT"; 1334 case ARMISD::VREV64: return "ARMISD::VREV64"; 1335 case ARMISD::VREV32: return "ARMISD::VREV32"; 1336 case ARMISD::VREV16: return "ARMISD::VREV16"; 1337 case ARMISD::VZIP: return "ARMISD::VZIP"; 1338 case ARMISD::VUZP: return "ARMISD::VUZP"; 1339 case ARMISD::VTRN: return "ARMISD::VTRN"; 1340 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1341 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1342 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1343 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1344 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1345 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1346 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1347 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1348 case ARMISD::BFI: return "ARMISD::BFI"; 1349 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1350 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1351 case ARMISD::VBSL: return "ARMISD::VBSL"; 1352 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1353 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1354 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1355 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1356 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1357 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1358 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1359 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1360 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1361 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1362 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1363 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1364 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1365 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1366 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1367 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1368 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1369 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1370 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1371 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1372 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1373 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1374 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1375 } 1376 return nullptr; 1377 } 1378 1379 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1380 EVT VT) const { 1381 if (!VT.isVector()) 1382 return getPointerTy(DL); 1383 return VT.changeVectorElementTypeToInteger(); 1384 } 1385 1386 /// getRegClassFor - Return the register class that should be used for the 1387 /// specified value type. 1388 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1389 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1390 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1391 // load / store 4 to 8 consecutive D registers. 1392 if (Subtarget->hasNEON()) { 1393 if (VT == MVT::v4i64) 1394 return &ARM::QQPRRegClass; 1395 if (VT == MVT::v8i64) 1396 return &ARM::QQQQPRRegClass; 1397 } 1398 return TargetLowering::getRegClassFor(VT); 1399 } 1400 1401 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1402 // source/dest is aligned and the copy size is large enough. We therefore want 1403 // to align such objects passed to memory intrinsics. 1404 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1405 unsigned &PrefAlign) const { 1406 if (!isa<MemIntrinsic>(CI)) 1407 return false; 1408 MinSize = 8; 1409 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1410 // cycle faster than 4-byte aligned LDM. 1411 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1412 return true; 1413 } 1414 1415 // Create a fast isel object. 1416 FastISel * 1417 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1418 const TargetLibraryInfo *libInfo) const { 1419 return ARM::createFastISel(funcInfo, libInfo); 1420 } 1421 1422 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1423 unsigned NumVals = N->getNumValues(); 1424 if (!NumVals) 1425 return Sched::RegPressure; 1426 1427 for (unsigned i = 0; i != NumVals; ++i) { 1428 EVT VT = N->getValueType(i); 1429 if (VT == MVT::Glue || VT == MVT::Other) 1430 continue; 1431 if (VT.isFloatingPoint() || VT.isVector()) 1432 return Sched::ILP; 1433 } 1434 1435 if (!N->isMachineOpcode()) 1436 return Sched::RegPressure; 1437 1438 // Load are scheduled for latency even if there instruction itinerary 1439 // is not available. 1440 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1441 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1442 1443 if (MCID.getNumDefs() == 0) 1444 return Sched::RegPressure; 1445 if (!Itins->isEmpty() && 1446 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1447 return Sched::ILP; 1448 1449 return Sched::RegPressure; 1450 } 1451 1452 //===----------------------------------------------------------------------===// 1453 // Lowering Code 1454 //===----------------------------------------------------------------------===// 1455 1456 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1457 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1458 switch (CC) { 1459 default: llvm_unreachable("Unknown condition code!"); 1460 case ISD::SETNE: return ARMCC::NE; 1461 case ISD::SETEQ: return ARMCC::EQ; 1462 case ISD::SETGT: return ARMCC::GT; 1463 case ISD::SETGE: return ARMCC::GE; 1464 case ISD::SETLT: return ARMCC::LT; 1465 case ISD::SETLE: return ARMCC::LE; 1466 case ISD::SETUGT: return ARMCC::HI; 1467 case ISD::SETUGE: return ARMCC::HS; 1468 case ISD::SETULT: return ARMCC::LO; 1469 case ISD::SETULE: return ARMCC::LS; 1470 } 1471 } 1472 1473 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1474 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1475 ARMCC::CondCodes &CondCode2) { 1476 CondCode2 = ARMCC::AL; 1477 switch (CC) { 1478 default: llvm_unreachable("Unknown FP condition!"); 1479 case ISD::SETEQ: 1480 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1481 case ISD::SETGT: 1482 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1483 case ISD::SETGE: 1484 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1485 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1486 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1487 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1488 case ISD::SETO: CondCode = ARMCC::VC; break; 1489 case ISD::SETUO: CondCode = ARMCC::VS; break; 1490 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1491 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1492 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1493 case ISD::SETLT: 1494 case ISD::SETULT: CondCode = ARMCC::LT; break; 1495 case ISD::SETLE: 1496 case ISD::SETULE: CondCode = ARMCC::LE; break; 1497 case ISD::SETNE: 1498 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1499 } 1500 } 1501 1502 //===----------------------------------------------------------------------===// 1503 // Calling Convention Implementation 1504 //===----------------------------------------------------------------------===// 1505 1506 #include "ARMGenCallingConv.inc" 1507 1508 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1509 /// account presence of floating point hardware and calling convention 1510 /// limitations, such as support for variadic functions. 1511 CallingConv::ID 1512 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1513 bool isVarArg) const { 1514 switch (CC) { 1515 default: 1516 llvm_unreachable("Unsupported calling convention"); 1517 case CallingConv::ARM_AAPCS: 1518 case CallingConv::ARM_APCS: 1519 case CallingConv::GHC: 1520 return CC; 1521 case CallingConv::PreserveMost: 1522 return CallingConv::PreserveMost; 1523 case CallingConv::ARM_AAPCS_VFP: 1524 case CallingConv::Swift: 1525 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1526 case CallingConv::C: 1527 if (!Subtarget->isAAPCS_ABI()) 1528 return CallingConv::ARM_APCS; 1529 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1530 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1531 !isVarArg) 1532 return CallingConv::ARM_AAPCS_VFP; 1533 else 1534 return CallingConv::ARM_AAPCS; 1535 case CallingConv::Fast: 1536 case CallingConv::CXX_FAST_TLS: 1537 if (!Subtarget->isAAPCS_ABI()) { 1538 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1539 return CallingConv::Fast; 1540 return CallingConv::ARM_APCS; 1541 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1542 return CallingConv::ARM_AAPCS_VFP; 1543 else 1544 return CallingConv::ARM_AAPCS; 1545 } 1546 } 1547 1548 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1549 bool isVarArg) const { 1550 return CCAssignFnForNode(CC, false, isVarArg); 1551 } 1552 1553 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1554 bool isVarArg) const { 1555 return CCAssignFnForNode(CC, true, isVarArg); 1556 } 1557 1558 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1559 /// CallingConvention. 1560 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1561 bool Return, 1562 bool isVarArg) const { 1563 switch (getEffectiveCallingConv(CC, isVarArg)) { 1564 default: 1565 llvm_unreachable("Unsupported calling convention"); 1566 case CallingConv::ARM_APCS: 1567 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1568 case CallingConv::ARM_AAPCS: 1569 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1570 case CallingConv::ARM_AAPCS_VFP: 1571 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1572 case CallingConv::Fast: 1573 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1574 case CallingConv::GHC: 1575 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1576 case CallingConv::PreserveMost: 1577 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1578 } 1579 } 1580 1581 /// LowerCallResult - Lower the result values of a call into the 1582 /// appropriate copies out of appropriate physical registers. 1583 SDValue ARMTargetLowering::LowerCallResult( 1584 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1585 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1586 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1587 SDValue ThisVal) const { 1588 1589 // Assign locations to each value returned by this call. 1590 SmallVector<CCValAssign, 16> RVLocs; 1591 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1592 *DAG.getContext()); 1593 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1594 1595 // Copy all of the result registers out of their specified physreg. 1596 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1597 CCValAssign VA = RVLocs[i]; 1598 1599 // Pass 'this' value directly from the argument to return value, to avoid 1600 // reg unit interference 1601 if (i == 0 && isThisReturn) { 1602 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1603 "unexpected return calling convention register assignment"); 1604 InVals.push_back(ThisVal); 1605 continue; 1606 } 1607 1608 SDValue Val; 1609 if (VA.needsCustom()) { 1610 // Handle f64 or half of a v2f64. 1611 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1612 InFlag); 1613 Chain = Lo.getValue(1); 1614 InFlag = Lo.getValue(2); 1615 VA = RVLocs[++i]; // skip ahead to next loc 1616 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1617 InFlag); 1618 Chain = Hi.getValue(1); 1619 InFlag = Hi.getValue(2); 1620 if (!Subtarget->isLittle()) 1621 std::swap (Lo, Hi); 1622 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1623 1624 if (VA.getLocVT() == MVT::v2f64) { 1625 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1626 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1627 DAG.getConstant(0, dl, MVT::i32)); 1628 1629 VA = RVLocs[++i]; // skip ahead to next loc 1630 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1631 Chain = Lo.getValue(1); 1632 InFlag = Lo.getValue(2); 1633 VA = RVLocs[++i]; // skip ahead to next loc 1634 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1635 Chain = Hi.getValue(1); 1636 InFlag = Hi.getValue(2); 1637 if (!Subtarget->isLittle()) 1638 std::swap (Lo, Hi); 1639 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1640 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1641 DAG.getConstant(1, dl, MVT::i32)); 1642 } 1643 } else { 1644 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1645 InFlag); 1646 Chain = Val.getValue(1); 1647 InFlag = Val.getValue(2); 1648 } 1649 1650 switch (VA.getLocInfo()) { 1651 default: llvm_unreachable("Unknown loc info!"); 1652 case CCValAssign::Full: break; 1653 case CCValAssign::BCvt: 1654 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1655 break; 1656 } 1657 1658 InVals.push_back(Val); 1659 } 1660 1661 return Chain; 1662 } 1663 1664 /// LowerMemOpCallTo - Store the argument to the stack. 1665 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1666 SDValue Arg, const SDLoc &dl, 1667 SelectionDAG &DAG, 1668 const CCValAssign &VA, 1669 ISD::ArgFlagsTy Flags) const { 1670 unsigned LocMemOffset = VA.getLocMemOffset(); 1671 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1672 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1673 StackPtr, PtrOff); 1674 return DAG.getStore( 1675 Chain, dl, Arg, PtrOff, 1676 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1677 } 1678 1679 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1680 SDValue Chain, SDValue &Arg, 1681 RegsToPassVector &RegsToPass, 1682 CCValAssign &VA, CCValAssign &NextVA, 1683 SDValue &StackPtr, 1684 SmallVectorImpl<SDValue> &MemOpChains, 1685 ISD::ArgFlagsTy Flags) const { 1686 1687 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1688 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1689 unsigned id = Subtarget->isLittle() ? 0 : 1; 1690 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1691 1692 if (NextVA.isRegLoc()) 1693 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1694 else { 1695 assert(NextVA.isMemLoc()); 1696 if (!StackPtr.getNode()) 1697 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1698 getPointerTy(DAG.getDataLayout())); 1699 1700 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1701 dl, DAG, NextVA, 1702 Flags)); 1703 } 1704 } 1705 1706 /// LowerCall - Lowering a call into a callseq_start <- 1707 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1708 /// nodes. 1709 SDValue 1710 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1711 SmallVectorImpl<SDValue> &InVals) const { 1712 SelectionDAG &DAG = CLI.DAG; 1713 SDLoc &dl = CLI.DL; 1714 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1715 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1716 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1717 SDValue Chain = CLI.Chain; 1718 SDValue Callee = CLI.Callee; 1719 bool &isTailCall = CLI.IsTailCall; 1720 CallingConv::ID CallConv = CLI.CallConv; 1721 bool doesNotRet = CLI.DoesNotReturn; 1722 bool isVarArg = CLI.IsVarArg; 1723 1724 MachineFunction &MF = DAG.getMachineFunction(); 1725 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1726 bool isThisReturn = false; 1727 bool isSibCall = false; 1728 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1729 1730 // Disable tail calls if they're not supported. 1731 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1732 isTailCall = false; 1733 1734 if (isTailCall) { 1735 // Check if it's really possible to do a tail call. 1736 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1737 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1738 Outs, OutVals, Ins, DAG); 1739 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1740 report_fatal_error("failed to perform tail call elimination on a call " 1741 "site marked musttail"); 1742 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1743 // detected sibcalls. 1744 if (isTailCall) { 1745 ++NumTailCalls; 1746 isSibCall = true; 1747 } 1748 } 1749 1750 // Analyze operands of the call, assigning locations to each operand. 1751 SmallVector<CCValAssign, 16> ArgLocs; 1752 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1753 *DAG.getContext()); 1754 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1755 1756 // Get a count of how many bytes are to be pushed on the stack. 1757 unsigned NumBytes = CCInfo.getNextStackOffset(); 1758 1759 // For tail calls, memory operands are available in our caller's stack. 1760 if (isSibCall) 1761 NumBytes = 0; 1762 1763 // Adjust the stack pointer for the new arguments... 1764 // These operations are automatically eliminated by the prolog/epilog pass 1765 if (!isSibCall) 1766 Chain = DAG.getCALLSEQ_START(Chain, 1767 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1768 1769 SDValue StackPtr = 1770 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1771 1772 RegsToPassVector RegsToPass; 1773 SmallVector<SDValue, 8> MemOpChains; 1774 1775 // Walk the register/memloc assignments, inserting copies/loads. In the case 1776 // of tail call optimization, arguments are handled later. 1777 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1778 i != e; 1779 ++i, ++realArgIdx) { 1780 CCValAssign &VA = ArgLocs[i]; 1781 SDValue Arg = OutVals[realArgIdx]; 1782 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1783 bool isByVal = Flags.isByVal(); 1784 1785 // Promote the value if needed. 1786 switch (VA.getLocInfo()) { 1787 default: llvm_unreachable("Unknown loc info!"); 1788 case CCValAssign::Full: break; 1789 case CCValAssign::SExt: 1790 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1791 break; 1792 case CCValAssign::ZExt: 1793 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1794 break; 1795 case CCValAssign::AExt: 1796 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1797 break; 1798 case CCValAssign::BCvt: 1799 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1800 break; 1801 } 1802 1803 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1804 if (VA.needsCustom()) { 1805 if (VA.getLocVT() == MVT::v2f64) { 1806 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1807 DAG.getConstant(0, dl, MVT::i32)); 1808 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1809 DAG.getConstant(1, dl, MVT::i32)); 1810 1811 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1812 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1813 1814 VA = ArgLocs[++i]; // skip ahead to next loc 1815 if (VA.isRegLoc()) { 1816 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1817 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1818 } else { 1819 assert(VA.isMemLoc()); 1820 1821 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1822 dl, DAG, VA, Flags)); 1823 } 1824 } else { 1825 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1826 StackPtr, MemOpChains, Flags); 1827 } 1828 } else if (VA.isRegLoc()) { 1829 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1830 assert(VA.getLocVT() == MVT::i32 && 1831 "unexpected calling convention register assignment"); 1832 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1833 "unexpected use of 'returned'"); 1834 isThisReturn = true; 1835 } 1836 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1837 } else if (isByVal) { 1838 assert(VA.isMemLoc()); 1839 unsigned offset = 0; 1840 1841 // True if this byval aggregate will be split between registers 1842 // and memory. 1843 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1844 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1845 1846 if (CurByValIdx < ByValArgsCount) { 1847 1848 unsigned RegBegin, RegEnd; 1849 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1850 1851 EVT PtrVT = 1852 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1853 unsigned int i, j; 1854 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1855 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1856 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1857 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1858 MachinePointerInfo(), 1859 DAG.InferPtrAlignment(AddArg)); 1860 MemOpChains.push_back(Load.getValue(1)); 1861 RegsToPass.push_back(std::make_pair(j, Load)); 1862 } 1863 1864 // If parameter size outsides register area, "offset" value 1865 // helps us to calculate stack slot for remained part properly. 1866 offset = RegEnd - RegBegin; 1867 1868 CCInfo.nextInRegsParam(); 1869 } 1870 1871 if (Flags.getByValSize() > 4*offset) { 1872 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1873 unsigned LocMemOffset = VA.getLocMemOffset(); 1874 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1875 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1876 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1877 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1878 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1879 MVT::i32); 1880 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1881 MVT::i32); 1882 1883 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1884 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1885 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1886 Ops)); 1887 } 1888 } else if (!isSibCall) { 1889 assert(VA.isMemLoc()); 1890 1891 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1892 dl, DAG, VA, Flags)); 1893 } 1894 } 1895 1896 if (!MemOpChains.empty()) 1897 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1898 1899 // Build a sequence of copy-to-reg nodes chained together with token chain 1900 // and flag operands which copy the outgoing args into the appropriate regs. 1901 SDValue InFlag; 1902 // Tail call byval lowering might overwrite argument registers so in case of 1903 // tail call optimization the copies to registers are lowered later. 1904 if (!isTailCall) 1905 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1906 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1907 RegsToPass[i].second, InFlag); 1908 InFlag = Chain.getValue(1); 1909 } 1910 1911 // For tail calls lower the arguments to the 'real' stack slot. 1912 if (isTailCall) { 1913 // Force all the incoming stack arguments to be loaded from the stack 1914 // before any new outgoing arguments are stored to the stack, because the 1915 // outgoing stack slots may alias the incoming argument stack slots, and 1916 // the alias isn't otherwise explicit. This is slightly more conservative 1917 // than necessary, because it means that each store effectively depends 1918 // on every argument instead of just those arguments it would clobber. 1919 1920 // Do not flag preceding copytoreg stuff together with the following stuff. 1921 InFlag = SDValue(); 1922 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1923 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1924 RegsToPass[i].second, InFlag); 1925 InFlag = Chain.getValue(1); 1926 } 1927 InFlag = SDValue(); 1928 } 1929 1930 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1931 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1932 // node so that legalize doesn't hack it. 1933 bool isDirect = false; 1934 1935 const TargetMachine &TM = getTargetMachine(); 1936 const Module *Mod = MF.getFunction()->getParent(); 1937 const GlobalValue *GV = nullptr; 1938 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1939 GV = G->getGlobal(); 1940 bool isStub = 1941 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 1942 1943 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1944 bool isLocalARMFunc = false; 1945 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1946 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1947 1948 if (Subtarget->genLongCalls()) { 1949 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 1950 "long-calls codegen is not position independent!"); 1951 // Handle a global address or an external symbol. If it's not one of 1952 // those, the target's already in a register, so we don't need to do 1953 // anything extra. 1954 if (isa<GlobalAddressSDNode>(Callee)) { 1955 // Create a constant pool entry for the callee address 1956 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1957 ARMConstantPoolValue *CPV = 1958 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1959 1960 // Get the address of the callee into a register 1961 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1962 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1963 Callee = DAG.getLoad( 1964 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1965 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 1966 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1967 const char *Sym = S->getSymbol(); 1968 1969 // Create a constant pool entry for the callee address 1970 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1971 ARMConstantPoolValue *CPV = 1972 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1973 ARMPCLabelIndex, 0); 1974 // Get the address of the callee into a register 1975 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1976 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1977 Callee = DAG.getLoad( 1978 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1979 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 1980 } 1981 } else if (isa<GlobalAddressSDNode>(Callee)) { 1982 // If we're optimizing for minimum size and the function is called three or 1983 // more times in this block, we can improve codesize by calling indirectly 1984 // as BLXr has a 16-bit encoding. 1985 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 1986 auto *BB = CLI.CS->getParent(); 1987 bool PreferIndirect = 1988 Subtarget->isThumb() && MF.getFunction()->optForMinSize() && 1989 count_if(GV->users(), [&BB](const User *U) { 1990 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 1991 }) > 2; 1992 1993 if (!PreferIndirect) { 1994 isDirect = true; 1995 bool isDef = GV->isStrongDefinitionForLinker(); 1996 1997 // ARM call to a local ARM function is predicable. 1998 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 1999 // tBX takes a register source operand. 2000 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2001 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2002 Callee = DAG.getNode( 2003 ARMISD::WrapperPIC, dl, PtrVt, 2004 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2005 Callee = DAG.getLoad( 2006 PtrVt, dl, DAG.getEntryNode(), Callee, 2007 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2008 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2009 MachineMemOperand::MOInvariant); 2010 } else if (Subtarget->isTargetCOFF()) { 2011 assert(Subtarget->isTargetWindows() && 2012 "Windows is the only supported COFF target"); 2013 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2014 ? ARMII::MO_DLLIMPORT 2015 : ARMII::MO_NO_FLAG; 2016 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2017 TargetFlags); 2018 if (GV->hasDLLImportStorageClass()) 2019 Callee = 2020 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2021 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2022 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2023 } else { 2024 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2025 } 2026 } 2027 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2028 isDirect = true; 2029 // tBX takes a register source operand. 2030 const char *Sym = S->getSymbol(); 2031 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2032 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2033 ARMConstantPoolValue *CPV = 2034 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2035 ARMPCLabelIndex, 4); 2036 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2037 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2038 Callee = DAG.getLoad( 2039 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2040 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2041 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2042 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2043 } else { 2044 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2045 } 2046 } 2047 2048 // FIXME: handle tail calls differently. 2049 unsigned CallOpc; 2050 if (Subtarget->isThumb()) { 2051 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2052 CallOpc = ARMISD::CALL_NOLINK; 2053 else 2054 CallOpc = ARMISD::CALL; 2055 } else { 2056 if (!isDirect && !Subtarget->hasV5TOps()) 2057 CallOpc = ARMISD::CALL_NOLINK; 2058 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2059 // Emit regular call when code size is the priority 2060 !MF.getFunction()->optForMinSize()) 2061 // "mov lr, pc; b _foo" to avoid confusing the RSP 2062 CallOpc = ARMISD::CALL_NOLINK; 2063 else 2064 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2065 } 2066 2067 std::vector<SDValue> Ops; 2068 Ops.push_back(Chain); 2069 Ops.push_back(Callee); 2070 2071 // Add argument registers to the end of the list so that they are known live 2072 // into the call. 2073 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2074 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2075 RegsToPass[i].second.getValueType())); 2076 2077 // Add a register mask operand representing the call-preserved registers. 2078 if (!isTailCall) { 2079 const uint32_t *Mask; 2080 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2081 if (isThisReturn) { 2082 // For 'this' returns, use the R0-preserving mask if applicable 2083 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2084 if (!Mask) { 2085 // Set isThisReturn to false if the calling convention is not one that 2086 // allows 'returned' to be modeled in this way, so LowerCallResult does 2087 // not try to pass 'this' straight through 2088 isThisReturn = false; 2089 Mask = ARI->getCallPreservedMask(MF, CallConv); 2090 } 2091 } else 2092 Mask = ARI->getCallPreservedMask(MF, CallConv); 2093 2094 assert(Mask && "Missing call preserved mask for calling convention"); 2095 Ops.push_back(DAG.getRegisterMask(Mask)); 2096 } 2097 2098 if (InFlag.getNode()) 2099 Ops.push_back(InFlag); 2100 2101 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2102 if (isTailCall) { 2103 MF.getFrameInfo().setHasTailCall(); 2104 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2105 } 2106 2107 // Returns a chain and a flag for retval copy to use. 2108 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2109 InFlag = Chain.getValue(1); 2110 2111 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2112 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2113 if (!Ins.empty()) 2114 InFlag = Chain.getValue(1); 2115 2116 // Handle result values, copying them out of physregs into vregs that we 2117 // return. 2118 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2119 InVals, isThisReturn, 2120 isThisReturn ? OutVals[0] : SDValue()); 2121 } 2122 2123 /// HandleByVal - Every parameter *after* a byval parameter is passed 2124 /// on the stack. Remember the next parameter register to allocate, 2125 /// and then confiscate the rest of the parameter registers to insure 2126 /// this. 2127 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2128 unsigned Align) const { 2129 // Byval (as with any stack) slots are always at least 4 byte aligned. 2130 Align = std::max(Align, 4U); 2131 2132 unsigned Reg = State->AllocateReg(GPRArgRegs); 2133 if (!Reg) 2134 return; 2135 2136 unsigned AlignInRegs = Align / 4; 2137 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2138 for (unsigned i = 0; i < Waste; ++i) 2139 Reg = State->AllocateReg(GPRArgRegs); 2140 2141 if (!Reg) 2142 return; 2143 2144 unsigned Excess = 4 * (ARM::R4 - Reg); 2145 2146 // Special case when NSAA != SP and parameter size greater than size of 2147 // all remained GPR regs. In that case we can't split parameter, we must 2148 // send it to stack. We also must set NCRN to R4, so waste all 2149 // remained registers. 2150 const unsigned NSAAOffset = State->getNextStackOffset(); 2151 if (NSAAOffset != 0 && Size > Excess) { 2152 while (State->AllocateReg(GPRArgRegs)) 2153 ; 2154 return; 2155 } 2156 2157 // First register for byval parameter is the first register that wasn't 2158 // allocated before this method call, so it would be "reg". 2159 // If parameter is small enough to be saved in range [reg, r4), then 2160 // the end (first after last) register would be reg + param-size-in-regs, 2161 // else parameter would be splitted between registers and stack, 2162 // end register would be r4 in this case. 2163 unsigned ByValRegBegin = Reg; 2164 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2165 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2166 // Note, first register is allocated in the beginning of function already, 2167 // allocate remained amount of registers we need. 2168 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2169 State->AllocateReg(GPRArgRegs); 2170 // A byval parameter that is split between registers and memory needs its 2171 // size truncated here. 2172 // In the case where the entire structure fits in registers, we set the 2173 // size in memory to zero. 2174 Size = std::max<int>(Size - Excess, 0); 2175 } 2176 2177 /// MatchingStackOffset - Return true if the given stack call argument is 2178 /// already available in the same position (relatively) of the caller's 2179 /// incoming argument stack. 2180 static 2181 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2182 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2183 const TargetInstrInfo *TII) { 2184 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2185 int FI = std::numeric_limits<int>::max(); 2186 if (Arg.getOpcode() == ISD::CopyFromReg) { 2187 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2188 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2189 return false; 2190 MachineInstr *Def = MRI->getVRegDef(VR); 2191 if (!Def) 2192 return false; 2193 if (!Flags.isByVal()) { 2194 if (!TII->isLoadFromStackSlot(*Def, FI)) 2195 return false; 2196 } else { 2197 return false; 2198 } 2199 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2200 if (Flags.isByVal()) 2201 // ByVal argument is passed in as a pointer but it's now being 2202 // dereferenced. e.g. 2203 // define @foo(%struct.X* %A) { 2204 // tail call @bar(%struct.X* byval %A) 2205 // } 2206 return false; 2207 SDValue Ptr = Ld->getBasePtr(); 2208 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2209 if (!FINode) 2210 return false; 2211 FI = FINode->getIndex(); 2212 } else 2213 return false; 2214 2215 assert(FI != std::numeric_limits<int>::max()); 2216 if (!MFI.isFixedObjectIndex(FI)) 2217 return false; 2218 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2219 } 2220 2221 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2222 /// for tail call optimization. Targets which want to do tail call 2223 /// optimization should implement this function. 2224 bool 2225 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2226 CallingConv::ID CalleeCC, 2227 bool isVarArg, 2228 bool isCalleeStructRet, 2229 bool isCallerStructRet, 2230 const SmallVectorImpl<ISD::OutputArg> &Outs, 2231 const SmallVectorImpl<SDValue> &OutVals, 2232 const SmallVectorImpl<ISD::InputArg> &Ins, 2233 SelectionDAG& DAG) const { 2234 MachineFunction &MF = DAG.getMachineFunction(); 2235 const Function *CallerF = MF.getFunction(); 2236 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2237 2238 assert(Subtarget->supportsTailCall()); 2239 2240 // Look for obvious safe cases to perform tail call optimization that do not 2241 // require ABI changes. This is what gcc calls sibcall. 2242 2243 // Exception-handling functions need a special set of instructions to indicate 2244 // a return to the hardware. Tail-calling another function would probably 2245 // break this. 2246 if (CallerF->hasFnAttribute("interrupt")) 2247 return false; 2248 2249 // Also avoid sibcall optimization if either caller or callee uses struct 2250 // return semantics. 2251 if (isCalleeStructRet || isCallerStructRet) 2252 return false; 2253 2254 // Externally-defined functions with weak linkage should not be 2255 // tail-called on ARM when the OS does not support dynamic 2256 // pre-emption of symbols, as the AAELF spec requires normal calls 2257 // to undefined weak functions to be replaced with a NOP or jump to the 2258 // next instruction. The behaviour of branch instructions in this 2259 // situation (as used for tail calls) is implementation-defined, so we 2260 // cannot rely on the linker replacing the tail call with a return. 2261 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2262 const GlobalValue *GV = G->getGlobal(); 2263 const Triple &TT = getTargetMachine().getTargetTriple(); 2264 if (GV->hasExternalWeakLinkage() && 2265 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2266 return false; 2267 } 2268 2269 // Check that the call results are passed in the same way. 2270 LLVMContext &C = *DAG.getContext(); 2271 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2272 CCAssignFnForReturn(CalleeCC, isVarArg), 2273 CCAssignFnForReturn(CallerCC, isVarArg))) 2274 return false; 2275 // The callee has to preserve all registers the caller needs to preserve. 2276 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2277 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2278 if (CalleeCC != CallerCC) { 2279 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2280 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2281 return false; 2282 } 2283 2284 // If Caller's vararg or byval argument has been split between registers and 2285 // stack, do not perform tail call, since part of the argument is in caller's 2286 // local frame. 2287 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2288 if (AFI_Caller->getArgRegsSaveSize()) 2289 return false; 2290 2291 // If the callee takes no arguments then go on to check the results of the 2292 // call. 2293 if (!Outs.empty()) { 2294 // Check if stack adjustment is needed. For now, do not do this if any 2295 // argument is passed on the stack. 2296 SmallVector<CCValAssign, 16> ArgLocs; 2297 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2298 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2299 if (CCInfo.getNextStackOffset()) { 2300 // Check if the arguments are already laid out in the right way as 2301 // the caller's fixed stack objects. 2302 MachineFrameInfo &MFI = MF.getFrameInfo(); 2303 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2304 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2305 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2306 i != e; 2307 ++i, ++realArgIdx) { 2308 CCValAssign &VA = ArgLocs[i]; 2309 EVT RegVT = VA.getLocVT(); 2310 SDValue Arg = OutVals[realArgIdx]; 2311 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2312 if (VA.getLocInfo() == CCValAssign::Indirect) 2313 return false; 2314 if (VA.needsCustom()) { 2315 // f64 and vector types are split into multiple registers or 2316 // register/stack-slot combinations. The types will not match 2317 // the registers; give up on memory f64 refs until we figure 2318 // out what to do about this. 2319 if (!VA.isRegLoc()) 2320 return false; 2321 if (!ArgLocs[++i].isRegLoc()) 2322 return false; 2323 if (RegVT == MVT::v2f64) { 2324 if (!ArgLocs[++i].isRegLoc()) 2325 return false; 2326 if (!ArgLocs[++i].isRegLoc()) 2327 return false; 2328 } 2329 } else if (!VA.isRegLoc()) { 2330 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2331 MFI, MRI, TII)) 2332 return false; 2333 } 2334 } 2335 } 2336 2337 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2338 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2339 return false; 2340 } 2341 2342 return true; 2343 } 2344 2345 bool 2346 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2347 MachineFunction &MF, bool isVarArg, 2348 const SmallVectorImpl<ISD::OutputArg> &Outs, 2349 LLVMContext &Context) const { 2350 SmallVector<CCValAssign, 16> RVLocs; 2351 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2352 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2353 } 2354 2355 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2356 const SDLoc &DL, SelectionDAG &DAG) { 2357 const MachineFunction &MF = DAG.getMachineFunction(); 2358 const Function *F = MF.getFunction(); 2359 2360 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2361 2362 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2363 // version of the "preferred return address". These offsets affect the return 2364 // instruction if this is a return from PL1 without hypervisor extensions. 2365 // IRQ/FIQ: +4 "subs pc, lr, #4" 2366 // SWI: 0 "subs pc, lr, #0" 2367 // ABORT: +4 "subs pc, lr, #4" 2368 // UNDEF: +4/+2 "subs pc, lr, #0" 2369 // UNDEF varies depending on where the exception came from ARM or Thumb 2370 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2371 2372 int64_t LROffset; 2373 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2374 IntKind == "ABORT") 2375 LROffset = 4; 2376 else if (IntKind == "SWI" || IntKind == "UNDEF") 2377 LROffset = 0; 2378 else 2379 report_fatal_error("Unsupported interrupt attribute. If present, value " 2380 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2381 2382 RetOps.insert(RetOps.begin() + 1, 2383 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2384 2385 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2386 } 2387 2388 SDValue 2389 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2390 bool isVarArg, 2391 const SmallVectorImpl<ISD::OutputArg> &Outs, 2392 const SmallVectorImpl<SDValue> &OutVals, 2393 const SDLoc &dl, SelectionDAG &DAG) const { 2394 2395 // CCValAssign - represent the assignment of the return value to a location. 2396 SmallVector<CCValAssign, 16> RVLocs; 2397 2398 // CCState - Info about the registers and stack slots. 2399 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2400 *DAG.getContext()); 2401 2402 // Analyze outgoing return values. 2403 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2404 2405 SDValue Flag; 2406 SmallVector<SDValue, 4> RetOps; 2407 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2408 bool isLittleEndian = Subtarget->isLittle(); 2409 2410 MachineFunction &MF = DAG.getMachineFunction(); 2411 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2412 AFI->setReturnRegsCount(RVLocs.size()); 2413 2414 // Copy the result values into the output registers. 2415 for (unsigned i = 0, realRVLocIdx = 0; 2416 i != RVLocs.size(); 2417 ++i, ++realRVLocIdx) { 2418 CCValAssign &VA = RVLocs[i]; 2419 assert(VA.isRegLoc() && "Can only return in registers!"); 2420 2421 SDValue Arg = OutVals[realRVLocIdx]; 2422 2423 switch (VA.getLocInfo()) { 2424 default: llvm_unreachable("Unknown loc info!"); 2425 case CCValAssign::Full: break; 2426 case CCValAssign::BCvt: 2427 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2428 break; 2429 } 2430 2431 if (VA.needsCustom()) { 2432 if (VA.getLocVT() == MVT::v2f64) { 2433 // Extract the first half and return it in two registers. 2434 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2435 DAG.getConstant(0, dl, MVT::i32)); 2436 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2437 DAG.getVTList(MVT::i32, MVT::i32), Half); 2438 2439 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2440 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2441 Flag); 2442 Flag = Chain.getValue(1); 2443 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2444 VA = RVLocs[++i]; // skip ahead to next loc 2445 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2446 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2447 Flag); 2448 Flag = Chain.getValue(1); 2449 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2450 VA = RVLocs[++i]; // skip ahead to next loc 2451 2452 // Extract the 2nd half and fall through to handle it as an f64 value. 2453 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2454 DAG.getConstant(1, dl, MVT::i32)); 2455 } 2456 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2457 // available. 2458 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2459 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2460 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2461 fmrrd.getValue(isLittleEndian ? 0 : 1), 2462 Flag); 2463 Flag = Chain.getValue(1); 2464 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2465 VA = RVLocs[++i]; // skip ahead to next loc 2466 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2467 fmrrd.getValue(isLittleEndian ? 1 : 0), 2468 Flag); 2469 } else 2470 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2471 2472 // Guarantee that all emitted copies are 2473 // stuck together, avoiding something bad. 2474 Flag = Chain.getValue(1); 2475 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2476 } 2477 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2478 const MCPhysReg *I = 2479 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2480 if (I) { 2481 for (; *I; ++I) { 2482 if (ARM::GPRRegClass.contains(*I)) 2483 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2484 else if (ARM::DPRRegClass.contains(*I)) 2485 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2486 else 2487 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2488 } 2489 } 2490 2491 // Update chain and glue. 2492 RetOps[0] = Chain; 2493 if (Flag.getNode()) 2494 RetOps.push_back(Flag); 2495 2496 // CPUs which aren't M-class use a special sequence to return from 2497 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2498 // though we use "subs pc, lr, #N"). 2499 // 2500 // M-class CPUs actually use a normal return sequence with a special 2501 // (hardware-provided) value in LR, so the normal code path works. 2502 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2503 !Subtarget->isMClass()) { 2504 if (Subtarget->isThumb1Only()) 2505 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2506 return LowerInterruptReturn(RetOps, dl, DAG); 2507 } 2508 2509 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2510 } 2511 2512 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2513 if (N->getNumValues() != 1) 2514 return false; 2515 if (!N->hasNUsesOfValue(1, 0)) 2516 return false; 2517 2518 SDValue TCChain = Chain; 2519 SDNode *Copy = *N->use_begin(); 2520 if (Copy->getOpcode() == ISD::CopyToReg) { 2521 // If the copy has a glue operand, we conservatively assume it isn't safe to 2522 // perform a tail call. 2523 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2524 return false; 2525 TCChain = Copy->getOperand(0); 2526 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2527 SDNode *VMov = Copy; 2528 // f64 returned in a pair of GPRs. 2529 SmallPtrSet<SDNode*, 2> Copies; 2530 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2531 UI != UE; ++UI) { 2532 if (UI->getOpcode() != ISD::CopyToReg) 2533 return false; 2534 Copies.insert(*UI); 2535 } 2536 if (Copies.size() > 2) 2537 return false; 2538 2539 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2540 UI != UE; ++UI) { 2541 SDValue UseChain = UI->getOperand(0); 2542 if (Copies.count(UseChain.getNode())) 2543 // Second CopyToReg 2544 Copy = *UI; 2545 else { 2546 // We are at the top of this chain. 2547 // If the copy has a glue operand, we conservatively assume it 2548 // isn't safe to perform a tail call. 2549 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2550 return false; 2551 // First CopyToReg 2552 TCChain = UseChain; 2553 } 2554 } 2555 } else if (Copy->getOpcode() == ISD::BITCAST) { 2556 // f32 returned in a single GPR. 2557 if (!Copy->hasOneUse()) 2558 return false; 2559 Copy = *Copy->use_begin(); 2560 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2561 return false; 2562 // If the copy has a glue operand, we conservatively assume it isn't safe to 2563 // perform a tail call. 2564 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2565 return false; 2566 TCChain = Copy->getOperand(0); 2567 } else { 2568 return false; 2569 } 2570 2571 bool HasRet = false; 2572 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2573 UI != UE; ++UI) { 2574 if (UI->getOpcode() != ARMISD::RET_FLAG && 2575 UI->getOpcode() != ARMISD::INTRET_FLAG) 2576 return false; 2577 HasRet = true; 2578 } 2579 2580 if (!HasRet) 2581 return false; 2582 2583 Chain = TCChain; 2584 return true; 2585 } 2586 2587 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2588 if (!Subtarget->supportsTailCall()) 2589 return false; 2590 2591 auto Attr = 2592 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2593 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2594 return false; 2595 2596 return true; 2597 } 2598 2599 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2600 // and pass the lower and high parts through. 2601 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2602 SDLoc DL(Op); 2603 SDValue WriteValue = Op->getOperand(2); 2604 2605 // This function is only supposed to be called for i64 type argument. 2606 assert(WriteValue.getValueType() == MVT::i64 2607 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2608 2609 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2610 DAG.getConstant(0, DL, MVT::i32)); 2611 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2612 DAG.getConstant(1, DL, MVT::i32)); 2613 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2614 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2615 } 2616 2617 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2618 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2619 // one of the above mentioned nodes. It has to be wrapped because otherwise 2620 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2621 // be used to form addressing mode. These wrapped nodes will be selected 2622 // into MOVi. 2623 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2624 EVT PtrVT = Op.getValueType(); 2625 // FIXME there is no actual debug info here 2626 SDLoc dl(Op); 2627 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2628 SDValue Res; 2629 if (CP->isMachineConstantPoolEntry()) 2630 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2631 CP->getAlignment()); 2632 else 2633 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2634 CP->getAlignment()); 2635 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2636 } 2637 2638 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2639 return MachineJumpTableInfo::EK_Inline; 2640 } 2641 2642 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2643 SelectionDAG &DAG) const { 2644 MachineFunction &MF = DAG.getMachineFunction(); 2645 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2646 unsigned ARMPCLabelIndex = 0; 2647 SDLoc DL(Op); 2648 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2649 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2650 SDValue CPAddr; 2651 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2652 if (!IsPositionIndependent) { 2653 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2654 } else { 2655 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2656 ARMPCLabelIndex = AFI->createPICLabelUId(); 2657 ARMConstantPoolValue *CPV = 2658 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2659 ARMCP::CPBlockAddress, PCAdj); 2660 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2661 } 2662 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2663 SDValue Result = DAG.getLoad( 2664 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2665 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2666 if (!IsPositionIndependent) 2667 return Result; 2668 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2669 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2670 } 2671 2672 /// \brief Convert a TLS address reference into the correct sequence of loads 2673 /// and calls to compute the variable's address for Darwin, and return an 2674 /// SDValue containing the final node. 2675 2676 /// Darwin only has one TLS scheme which must be capable of dealing with the 2677 /// fully general situation, in the worst case. This means: 2678 /// + "extern __thread" declaration. 2679 /// + Defined in a possibly unknown dynamic library. 2680 /// 2681 /// The general system is that each __thread variable has a [3 x i32] descriptor 2682 /// which contains information used by the runtime to calculate the address. The 2683 /// only part of this the compiler needs to know about is the first word, which 2684 /// contains a function pointer that must be called with the address of the 2685 /// entire descriptor in "r0". 2686 /// 2687 /// Since this descriptor may be in a different unit, in general access must 2688 /// proceed along the usual ARM rules. A common sequence to produce is: 2689 /// 2690 /// movw rT1, :lower16:_var$non_lazy_ptr 2691 /// movt rT1, :upper16:_var$non_lazy_ptr 2692 /// ldr r0, [rT1] 2693 /// ldr rT2, [r0] 2694 /// blx rT2 2695 /// [...address now in r0...] 2696 SDValue 2697 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2698 SelectionDAG &DAG) const { 2699 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2700 SDLoc DL(Op); 2701 2702 // First step is to get the address of the actua global symbol. This is where 2703 // the TLS descriptor lives. 2704 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2705 2706 // The first entry in the descriptor is a function pointer that we must call 2707 // to obtain the address of the variable. 2708 SDValue Chain = DAG.getEntryNode(); 2709 SDValue FuncTLVGet = DAG.getLoad( 2710 MVT::i32, DL, Chain, DescAddr, 2711 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2712 /* Alignment = */ 4, 2713 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2714 MachineMemOperand::MOInvariant); 2715 Chain = FuncTLVGet.getValue(1); 2716 2717 MachineFunction &F = DAG.getMachineFunction(); 2718 MachineFrameInfo &MFI = F.getFrameInfo(); 2719 MFI.setAdjustsStack(true); 2720 2721 // TLS calls preserve all registers except those that absolutely must be 2722 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2723 // silly). 2724 auto TRI = 2725 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2726 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2727 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2728 2729 // Finally, we can make the call. This is just a degenerate version of a 2730 // normal AArch64 call node: r0 takes the address of the descriptor, and 2731 // returns the address of the variable in this thread. 2732 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2733 Chain = 2734 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2735 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2736 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2737 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2738 } 2739 2740 SDValue 2741 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2742 SelectionDAG &DAG) const { 2743 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2744 2745 SDValue Chain = DAG.getEntryNode(); 2746 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2747 SDLoc DL(Op); 2748 2749 // Load the current TEB (thread environment block) 2750 SDValue Ops[] = {Chain, 2751 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2752 DAG.getConstant(15, DL, MVT::i32), 2753 DAG.getConstant(0, DL, MVT::i32), 2754 DAG.getConstant(13, DL, MVT::i32), 2755 DAG.getConstant(0, DL, MVT::i32), 2756 DAG.getConstant(2, DL, MVT::i32)}; 2757 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2758 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2759 2760 SDValue TEB = CurrentTEB.getValue(0); 2761 Chain = CurrentTEB.getValue(1); 2762 2763 // Load the ThreadLocalStoragePointer from the TEB 2764 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2765 SDValue TLSArray = 2766 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2767 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2768 2769 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2770 // offset into the TLSArray. 2771 2772 // Load the TLS index from the C runtime 2773 SDValue TLSIndex = 2774 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2775 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2776 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2777 2778 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2779 DAG.getConstant(2, DL, MVT::i32)); 2780 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2781 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2782 MachinePointerInfo()); 2783 2784 // Get the offset of the start of the .tls section (section base) 2785 const auto *GA = cast<GlobalAddressSDNode>(Op); 2786 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2787 SDValue Offset = DAG.getLoad( 2788 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2789 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2790 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2791 2792 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2793 } 2794 2795 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2796 SDValue 2797 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2798 SelectionDAG &DAG) const { 2799 SDLoc dl(GA); 2800 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2801 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2802 MachineFunction &MF = DAG.getMachineFunction(); 2803 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2804 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2805 ARMConstantPoolValue *CPV = 2806 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2807 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2808 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2809 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2810 Argument = DAG.getLoad( 2811 PtrVT, dl, DAG.getEntryNode(), Argument, 2812 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2813 SDValue Chain = Argument.getValue(1); 2814 2815 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2816 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2817 2818 // call __tls_get_addr. 2819 ArgListTy Args; 2820 ArgListEntry Entry; 2821 Entry.Node = Argument; 2822 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2823 Args.push_back(Entry); 2824 2825 // FIXME: is there useful debug info available here? 2826 TargetLowering::CallLoweringInfo CLI(DAG); 2827 CLI.setDebugLoc(dl).setChain(Chain) 2828 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2829 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2830 2831 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2832 return CallResult.first; 2833 } 2834 2835 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2836 // "local exec" model. 2837 SDValue 2838 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2839 SelectionDAG &DAG, 2840 TLSModel::Model model) const { 2841 const GlobalValue *GV = GA->getGlobal(); 2842 SDLoc dl(GA); 2843 SDValue Offset; 2844 SDValue Chain = DAG.getEntryNode(); 2845 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2846 // Get the Thread Pointer 2847 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2848 2849 if (model == TLSModel::InitialExec) { 2850 MachineFunction &MF = DAG.getMachineFunction(); 2851 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2852 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2853 // Initial exec model. 2854 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2855 ARMConstantPoolValue *CPV = 2856 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2857 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2858 true); 2859 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2860 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2861 Offset = DAG.getLoad( 2862 PtrVT, dl, Chain, Offset, 2863 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2864 Chain = Offset.getValue(1); 2865 2866 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2867 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2868 2869 Offset = DAG.getLoad( 2870 PtrVT, dl, Chain, Offset, 2871 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2872 } else { 2873 // local exec model 2874 assert(model == TLSModel::LocalExec); 2875 ARMConstantPoolValue *CPV = 2876 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2877 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2878 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2879 Offset = DAG.getLoad( 2880 PtrVT, dl, Chain, Offset, 2881 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2882 } 2883 2884 // The address of the thread local variable is the add of the thread 2885 // pointer with the offset of the variable. 2886 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2887 } 2888 2889 SDValue 2890 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2891 if (Subtarget->isTargetDarwin()) 2892 return LowerGlobalTLSAddressDarwin(Op, DAG); 2893 2894 if (Subtarget->isTargetWindows()) 2895 return LowerGlobalTLSAddressWindows(Op, DAG); 2896 2897 // TODO: implement the "local dynamic" model 2898 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2899 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2900 if (DAG.getTarget().Options.EmulatedTLS) 2901 return LowerToTLSEmulatedModel(GA, DAG); 2902 2903 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2904 2905 switch (model) { 2906 case TLSModel::GeneralDynamic: 2907 case TLSModel::LocalDynamic: 2908 return LowerToTLSGeneralDynamicModel(GA, DAG); 2909 case TLSModel::InitialExec: 2910 case TLSModel::LocalExec: 2911 return LowerToTLSExecModels(GA, DAG, model); 2912 } 2913 llvm_unreachable("bogus TLS model"); 2914 } 2915 2916 /// Return true if all users of V are within function F, looking through 2917 /// ConstantExprs. 2918 static bool allUsersAreInFunction(const Value *V, const Function *F) { 2919 SmallVector<const User*,4> Worklist; 2920 for (auto *U : V->users()) 2921 Worklist.push_back(U); 2922 while (!Worklist.empty()) { 2923 auto *U = Worklist.pop_back_val(); 2924 if (isa<ConstantExpr>(U)) { 2925 for (auto *UU : U->users()) 2926 Worklist.push_back(UU); 2927 continue; 2928 } 2929 2930 auto *I = dyn_cast<Instruction>(U); 2931 if (!I || I->getParent()->getParent() != F) 2932 return false; 2933 } 2934 return true; 2935 } 2936 2937 /// Return true if all users of V are within some (any) function, looking through 2938 /// ConstantExprs. In other words, are there any global constant users? 2939 static bool allUsersAreInFunctions(const Value *V) { 2940 SmallVector<const User*,4> Worklist; 2941 for (auto *U : V->users()) 2942 Worklist.push_back(U); 2943 while (!Worklist.empty()) { 2944 auto *U = Worklist.pop_back_val(); 2945 if (isa<ConstantExpr>(U)) { 2946 for (auto *UU : U->users()) 2947 Worklist.push_back(UU); 2948 continue; 2949 } 2950 2951 if (!isa<Instruction>(U)) 2952 return false; 2953 } 2954 return true; 2955 } 2956 2957 // Return true if T is an integer, float or an array/vector of either. 2958 static bool isSimpleType(Type *T) { 2959 if (T->isIntegerTy() || T->isFloatingPointTy()) 2960 return true; 2961 Type *SubT = nullptr; 2962 if (T->isArrayTy()) 2963 SubT = T->getArrayElementType(); 2964 else if (T->isVectorTy()) 2965 SubT = T->getVectorElementType(); 2966 else 2967 return false; 2968 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 2969 } 2970 2971 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 2972 EVT PtrVT, const SDLoc &dl) { 2973 // If we're creating a pool entry for a constant global with unnamed address, 2974 // and the global is small enough, we can emit it inline into the constant pool 2975 // to save ourselves an indirection. 2976 // 2977 // This is a win if the constant is only used in one function (so it doesn't 2978 // need to be duplicated) or duplicating the constant wouldn't increase code 2979 // size (implying the constant is no larger than 4 bytes). 2980 const Function *F = DAG.getMachineFunction().getFunction(); 2981 2982 // We rely on this decision to inline being idemopotent and unrelated to the 2983 // use-site. We know that if we inline a variable at one use site, we'll 2984 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 2985 // doesn't know about this optimization, so bail out if it's enabled else 2986 // we could decide to inline here (and thus never emit the GV) but require 2987 // the GV from fast-isel generated code. 2988 if (!EnableConstpoolPromotion || 2989 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 2990 return SDValue(); 2991 2992 auto *GVar = dyn_cast<GlobalVariable>(GV); 2993 if (!GVar || !GVar->hasInitializer() || 2994 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 2995 !GVar->hasLocalLinkage()) 2996 return SDValue(); 2997 2998 // Ensure that we don't try and inline any type that contains pointers. If 2999 // we inline a value that contains relocations, we move the relocations from 3000 // .data to .text which is not ideal. 3001 auto *Init = GVar->getInitializer(); 3002 if (!isSimpleType(Init->getType())) 3003 return SDValue(); 3004 3005 // The constant islands pass can only really deal with alignment requests 3006 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3007 // any type wanting greater alignment requirements than 4 bytes. We also 3008 // can only promote constants that are multiples of 4 bytes in size or 3009 // are paddable to a multiple of 4. Currently we only try and pad constants 3010 // that are strings for simplicity. 3011 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3012 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3013 unsigned Align = GVar->getAlignment(); 3014 unsigned RequiredPadding = 4 - (Size % 4); 3015 bool PaddingPossible = 3016 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3017 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize) 3018 return SDValue(); 3019 3020 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3021 MachineFunction &MF = DAG.getMachineFunction(); 3022 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3023 3024 // We can't bloat the constant pool too much, else the ConstantIslands pass 3025 // may fail to converge. If we haven't promoted this global yet (it may have 3026 // multiple uses), and promoting it would increase the constant pool size (Sz 3027 // > 4), ensure we have space to do so up to MaxTotal. 3028 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3029 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3030 ConstpoolPromotionMaxTotal) 3031 return SDValue(); 3032 3033 // This is only valid if all users are in a single function OR it has users 3034 // in multiple functions but it no larger than a pointer. We also check if 3035 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3036 // address taken. 3037 if (!allUsersAreInFunction(GVar, F) && 3038 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3039 return SDValue(); 3040 3041 // We're going to inline this global. Pad it out if needed. 3042 if (RequiredPadding != 4) { 3043 StringRef S = CDAInit->getAsString(); 3044 3045 SmallVector<uint8_t,16> V(S.size()); 3046 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3047 while (RequiredPadding--) 3048 V.push_back(0); 3049 Init = ConstantDataArray::get(*DAG.getContext(), V); 3050 } 3051 3052 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3053 SDValue CPAddr = 3054 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3055 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3056 AFI->markGlobalAsPromotedToConstantPool(GVar); 3057 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3058 PaddedSize - 4); 3059 } 3060 ++NumConstpoolPromoted; 3061 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3062 } 3063 3064 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3065 SelectionDAG &DAG) const { 3066 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3067 SDLoc dl(Op); 3068 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3069 const TargetMachine &TM = getTargetMachine(); 3070 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3071 GV = GA->getBaseObject(); 3072 bool IsRO = 3073 (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3074 isa<Function>(GV); 3075 3076 // promoteToConstantPool only if not generating XO text section 3077 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3078 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3079 return V; 3080 3081 if (isPositionIndependent()) { 3082 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3083 3084 MachineFunction &MF = DAG.getMachineFunction(); 3085 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3086 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3087 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3088 SDLoc dl(Op); 3089 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3090 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 3091 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 3092 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 3093 /*AddCurrentAddress=*/UseGOT_PREL); 3094 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3095 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3096 SDValue Result = DAG.getLoad( 3097 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3098 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3099 SDValue Chain = Result.getValue(1); 3100 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3101 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3102 if (UseGOT_PREL) 3103 Result = 3104 DAG.getLoad(PtrVT, dl, Chain, Result, 3105 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3106 return Result; 3107 } else if (Subtarget->isROPI() && IsRO) { 3108 // PC-relative. 3109 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3110 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3111 return Result; 3112 } else if (Subtarget->isRWPI() && !IsRO) { 3113 // SB-relative. 3114 ARMConstantPoolValue *CPV = 3115 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3116 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3117 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3118 SDValue G = DAG.getLoad( 3119 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3120 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3121 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3122 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, G); 3123 return Result; 3124 } 3125 3126 // If we have T2 ops, we can materialize the address directly via movt/movw 3127 // pair. This is always cheaper. 3128 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3129 ++NumMovwMovt; 3130 // FIXME: Once remat is capable of dealing with instructions with register 3131 // operands, expand this into two nodes. 3132 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3133 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3134 } else { 3135 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3136 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3137 return DAG.getLoad( 3138 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3139 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3140 } 3141 } 3142 3143 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3144 SelectionDAG &DAG) const { 3145 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3146 "ROPI/RWPI not currently supported for Darwin"); 3147 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3148 SDLoc dl(Op); 3149 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3150 3151 if (Subtarget->useMovt(DAG.getMachineFunction())) 3152 ++NumMovwMovt; 3153 3154 // FIXME: Once remat is capable of dealing with instructions with register 3155 // operands, expand this into multiple nodes 3156 unsigned Wrapper = 3157 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3158 3159 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3160 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3161 3162 if (Subtarget->isGVIndirectSymbol(GV)) 3163 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3164 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3165 return Result; 3166 } 3167 3168 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3169 SelectionDAG &DAG) const { 3170 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3171 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3172 "Windows on ARM expects to use movw/movt"); 3173 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3174 "ROPI/RWPI not currently supported for Windows"); 3175 3176 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3177 const ARMII::TOF TargetFlags = 3178 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3179 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3180 SDValue Result; 3181 SDLoc DL(Op); 3182 3183 ++NumMovwMovt; 3184 3185 // FIXME: Once remat is capable of dealing with instructions with register 3186 // operands, expand this into two nodes. 3187 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3188 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3189 TargetFlags)); 3190 if (GV->hasDLLImportStorageClass()) 3191 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3192 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3193 return Result; 3194 } 3195 3196 SDValue 3197 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3198 SDLoc dl(Op); 3199 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3200 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3201 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3202 Op.getOperand(1), Val); 3203 } 3204 3205 SDValue 3206 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3207 SDLoc dl(Op); 3208 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3209 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3210 } 3211 3212 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3213 SelectionDAG &DAG) const { 3214 SDLoc dl(Op); 3215 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3216 Op.getOperand(0)); 3217 } 3218 3219 SDValue 3220 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3221 const ARMSubtarget *Subtarget) const { 3222 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3223 SDLoc dl(Op); 3224 switch (IntNo) { 3225 default: return SDValue(); // Don't custom lower most intrinsics. 3226 case Intrinsic::thread_pointer: { 3227 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3228 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3229 } 3230 case Intrinsic::eh_sjlj_lsda: { 3231 MachineFunction &MF = DAG.getMachineFunction(); 3232 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3233 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3234 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3235 SDValue CPAddr; 3236 bool IsPositionIndependent = isPositionIndependent(); 3237 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3238 ARMConstantPoolValue *CPV = 3239 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 3240 ARMCP::CPLSDA, PCAdj); 3241 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3242 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3243 SDValue Result = DAG.getLoad( 3244 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3245 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3246 3247 if (IsPositionIndependent) { 3248 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3249 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3250 } 3251 return Result; 3252 } 3253 case Intrinsic::arm_neon_vmulls: 3254 case Intrinsic::arm_neon_vmullu: { 3255 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3256 ? ARMISD::VMULLs : ARMISD::VMULLu; 3257 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3258 Op.getOperand(1), Op.getOperand(2)); 3259 } 3260 case Intrinsic::arm_neon_vminnm: 3261 case Intrinsic::arm_neon_vmaxnm: { 3262 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3263 ? ISD::FMINNUM : ISD::FMAXNUM; 3264 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3265 Op.getOperand(1), Op.getOperand(2)); 3266 } 3267 case Intrinsic::arm_neon_vminu: 3268 case Intrinsic::arm_neon_vmaxu: { 3269 if (Op.getValueType().isFloatingPoint()) 3270 return SDValue(); 3271 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3272 ? ISD::UMIN : ISD::UMAX; 3273 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3274 Op.getOperand(1), Op.getOperand(2)); 3275 } 3276 case Intrinsic::arm_neon_vmins: 3277 case Intrinsic::arm_neon_vmaxs: { 3278 // v{min,max}s is overloaded between signed integers and floats. 3279 if (!Op.getValueType().isFloatingPoint()) { 3280 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3281 ? ISD::SMIN : ISD::SMAX; 3282 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3283 Op.getOperand(1), Op.getOperand(2)); 3284 } 3285 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3286 ? ISD::FMINNAN : ISD::FMAXNAN; 3287 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3288 Op.getOperand(1), Op.getOperand(2)); 3289 } 3290 } 3291 } 3292 3293 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3294 const ARMSubtarget *Subtarget) { 3295 // FIXME: handle "fence singlethread" more efficiently. 3296 SDLoc dl(Op); 3297 if (!Subtarget->hasDataBarrier()) { 3298 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3299 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3300 // here. 3301 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3302 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3303 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3304 DAG.getConstant(0, dl, MVT::i32)); 3305 } 3306 3307 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3308 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3309 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3310 if (Subtarget->isMClass()) { 3311 // Only a full system barrier exists in the M-class architectures. 3312 Domain = ARM_MB::SY; 3313 } else if (Subtarget->preferISHSTBarriers() && 3314 Ord == AtomicOrdering::Release) { 3315 // Swift happens to implement ISHST barriers in a way that's compatible with 3316 // Release semantics but weaker than ISH so we'd be fools not to use 3317 // it. Beware: other processors probably don't! 3318 Domain = ARM_MB::ISHST; 3319 } 3320 3321 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3322 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3323 DAG.getConstant(Domain, dl, MVT::i32)); 3324 } 3325 3326 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3327 const ARMSubtarget *Subtarget) { 3328 // ARM pre v5TE and Thumb1 does not have preload instructions. 3329 if (!(Subtarget->isThumb2() || 3330 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3331 // Just preserve the chain. 3332 return Op.getOperand(0); 3333 3334 SDLoc dl(Op); 3335 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3336 if (!isRead && 3337 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3338 // ARMv7 with MP extension has PLDW. 3339 return Op.getOperand(0); 3340 3341 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3342 if (Subtarget->isThumb()) { 3343 // Invert the bits. 3344 isRead = ~isRead & 1; 3345 isData = ~isData & 1; 3346 } 3347 3348 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3349 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3350 DAG.getConstant(isData, dl, MVT::i32)); 3351 } 3352 3353 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3354 MachineFunction &MF = DAG.getMachineFunction(); 3355 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3356 3357 // vastart just stores the address of the VarArgsFrameIndex slot into the 3358 // memory location argument. 3359 SDLoc dl(Op); 3360 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3361 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3362 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3363 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3364 MachinePointerInfo(SV)); 3365 } 3366 3367 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3368 CCValAssign &NextVA, 3369 SDValue &Root, 3370 SelectionDAG &DAG, 3371 const SDLoc &dl) const { 3372 MachineFunction &MF = DAG.getMachineFunction(); 3373 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3374 3375 const TargetRegisterClass *RC; 3376 if (AFI->isThumb1OnlyFunction()) 3377 RC = &ARM::tGPRRegClass; 3378 else 3379 RC = &ARM::GPRRegClass; 3380 3381 // Transform the arguments stored in physical registers into virtual ones. 3382 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3383 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3384 3385 SDValue ArgValue2; 3386 if (NextVA.isMemLoc()) { 3387 MachineFrameInfo &MFI = MF.getFrameInfo(); 3388 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3389 3390 // Create load node to retrieve arguments from the stack. 3391 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3392 ArgValue2 = DAG.getLoad( 3393 MVT::i32, dl, Root, FIN, 3394 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3395 } else { 3396 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3397 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3398 } 3399 if (!Subtarget->isLittle()) 3400 std::swap (ArgValue, ArgValue2); 3401 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3402 } 3403 3404 // The remaining GPRs hold either the beginning of variable-argument 3405 // data, or the beginning of an aggregate passed by value (usually 3406 // byval). Either way, we allocate stack slots adjacent to the data 3407 // provided by our caller, and store the unallocated registers there. 3408 // If this is a variadic function, the va_list pointer will begin with 3409 // these values; otherwise, this reassembles a (byval) structure that 3410 // was split between registers and memory. 3411 // Return: The frame index registers were stored into. 3412 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3413 const SDLoc &dl, SDValue &Chain, 3414 const Value *OrigArg, 3415 unsigned InRegsParamRecordIdx, 3416 int ArgOffset, unsigned ArgSize) const { 3417 // Currently, two use-cases possible: 3418 // Case #1. Non-var-args function, and we meet first byval parameter. 3419 // Setup first unallocated register as first byval register; 3420 // eat all remained registers 3421 // (these two actions are performed by HandleByVal method). 3422 // Then, here, we initialize stack frame with 3423 // "store-reg" instructions. 3424 // Case #2. Var-args function, that doesn't contain byval parameters. 3425 // The same: eat all remained unallocated registers, 3426 // initialize stack frame. 3427 3428 MachineFunction &MF = DAG.getMachineFunction(); 3429 MachineFrameInfo &MFI = MF.getFrameInfo(); 3430 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3431 unsigned RBegin, REnd; 3432 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3433 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3434 } else { 3435 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3436 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3437 REnd = ARM::R4; 3438 } 3439 3440 if (REnd != RBegin) 3441 ArgOffset = -4 * (ARM::R4 - RBegin); 3442 3443 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3444 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3445 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3446 3447 SmallVector<SDValue, 4> MemOps; 3448 const TargetRegisterClass *RC = 3449 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3450 3451 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3452 unsigned VReg = MF.addLiveIn(Reg, RC); 3453 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3454 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3455 MachinePointerInfo(OrigArg, 4 * i)); 3456 MemOps.push_back(Store); 3457 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3458 } 3459 3460 if (!MemOps.empty()) 3461 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3462 return FrameIndex; 3463 } 3464 3465 // Setup stack frame, the va_list pointer will start from. 3466 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3467 const SDLoc &dl, SDValue &Chain, 3468 unsigned ArgOffset, 3469 unsigned TotalArgRegsSaveSize, 3470 bool ForceMutable) const { 3471 MachineFunction &MF = DAG.getMachineFunction(); 3472 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3473 3474 // Try to store any remaining integer argument regs 3475 // to their spots on the stack so that they may be loaded by dereferencing 3476 // the result of va_next. 3477 // If there is no regs to be stored, just point address after last 3478 // argument passed via stack. 3479 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3480 CCInfo.getInRegsParamsCount(), 3481 CCInfo.getNextStackOffset(), 4); 3482 AFI->setVarArgsFrameIndex(FrameIndex); 3483 } 3484 3485 SDValue ARMTargetLowering::LowerFormalArguments( 3486 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3487 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3488 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3489 MachineFunction &MF = DAG.getMachineFunction(); 3490 MachineFrameInfo &MFI = MF.getFrameInfo(); 3491 3492 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3493 3494 // Assign locations to all of the incoming arguments. 3495 SmallVector<CCValAssign, 16> ArgLocs; 3496 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3497 *DAG.getContext()); 3498 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3499 3500 SmallVector<SDValue, 16> ArgValues; 3501 SDValue ArgValue; 3502 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3503 unsigned CurArgIdx = 0; 3504 3505 // Initially ArgRegsSaveSize is zero. 3506 // Then we increase this value each time we meet byval parameter. 3507 // We also increase this value in case of varargs function. 3508 AFI->setArgRegsSaveSize(0); 3509 3510 // Calculate the amount of stack space that we need to allocate to store 3511 // byval and variadic arguments that are passed in registers. 3512 // We need to know this before we allocate the first byval or variadic 3513 // argument, as they will be allocated a stack slot below the CFA (Canonical 3514 // Frame Address, the stack pointer at entry to the function). 3515 unsigned ArgRegBegin = ARM::R4; 3516 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3517 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3518 break; 3519 3520 CCValAssign &VA = ArgLocs[i]; 3521 unsigned Index = VA.getValNo(); 3522 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3523 if (!Flags.isByVal()) 3524 continue; 3525 3526 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3527 unsigned RBegin, REnd; 3528 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3529 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3530 3531 CCInfo.nextInRegsParam(); 3532 } 3533 CCInfo.rewindByValRegsInfo(); 3534 3535 int lastInsIndex = -1; 3536 if (isVarArg && MFI.hasVAStart()) { 3537 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3538 if (RegIdx != array_lengthof(GPRArgRegs)) 3539 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3540 } 3541 3542 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3543 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3544 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3545 3546 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3547 CCValAssign &VA = ArgLocs[i]; 3548 if (Ins[VA.getValNo()].isOrigArg()) { 3549 std::advance(CurOrigArg, 3550 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3551 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3552 } 3553 // Arguments stored in registers. 3554 if (VA.isRegLoc()) { 3555 EVT RegVT = VA.getLocVT(); 3556 3557 if (VA.needsCustom()) { 3558 // f64 and vector types are split up into multiple registers or 3559 // combinations of registers and stack slots. 3560 if (VA.getLocVT() == MVT::v2f64) { 3561 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3562 Chain, DAG, dl); 3563 VA = ArgLocs[++i]; // skip ahead to next loc 3564 SDValue ArgValue2; 3565 if (VA.isMemLoc()) { 3566 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3567 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3568 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3569 MachinePointerInfo::getFixedStack( 3570 DAG.getMachineFunction(), FI)); 3571 } else { 3572 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3573 Chain, DAG, dl); 3574 } 3575 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3576 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3577 ArgValue, ArgValue1, 3578 DAG.getIntPtrConstant(0, dl)); 3579 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3580 ArgValue, ArgValue2, 3581 DAG.getIntPtrConstant(1, dl)); 3582 } else 3583 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3584 3585 } else { 3586 const TargetRegisterClass *RC; 3587 3588 if (RegVT == MVT::f32) 3589 RC = &ARM::SPRRegClass; 3590 else if (RegVT == MVT::f64) 3591 RC = &ARM::DPRRegClass; 3592 else if (RegVT == MVT::v2f64) 3593 RC = &ARM::QPRRegClass; 3594 else if (RegVT == MVT::i32) 3595 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3596 : &ARM::GPRRegClass; 3597 else 3598 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3599 3600 // Transform the arguments in physical registers into virtual ones. 3601 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3602 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3603 } 3604 3605 // If this is an 8 or 16-bit value, it is really passed promoted 3606 // to 32 bits. Insert an assert[sz]ext to capture this, then 3607 // truncate to the right size. 3608 switch (VA.getLocInfo()) { 3609 default: llvm_unreachable("Unknown loc info!"); 3610 case CCValAssign::Full: break; 3611 case CCValAssign::BCvt: 3612 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3613 break; 3614 case CCValAssign::SExt: 3615 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3616 DAG.getValueType(VA.getValVT())); 3617 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3618 break; 3619 case CCValAssign::ZExt: 3620 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3621 DAG.getValueType(VA.getValVT())); 3622 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3623 break; 3624 } 3625 3626 InVals.push_back(ArgValue); 3627 3628 } else { // VA.isRegLoc() 3629 // sanity check 3630 assert(VA.isMemLoc()); 3631 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3632 3633 int index = VA.getValNo(); 3634 3635 // Some Ins[] entries become multiple ArgLoc[] entries. 3636 // Process them only once. 3637 if (index != lastInsIndex) 3638 { 3639 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3640 // FIXME: For now, all byval parameter objects are marked mutable. 3641 // This can be changed with more analysis. 3642 // In case of tail call optimization mark all arguments mutable. 3643 // Since they could be overwritten by lowering of arguments in case of 3644 // a tail call. 3645 if (Flags.isByVal()) { 3646 assert(Ins[index].isOrigArg() && 3647 "Byval arguments cannot be implicit"); 3648 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3649 3650 int FrameIndex = StoreByValRegs( 3651 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3652 VA.getLocMemOffset(), Flags.getByValSize()); 3653 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3654 CCInfo.nextInRegsParam(); 3655 } else { 3656 unsigned FIOffset = VA.getLocMemOffset(); 3657 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3658 FIOffset, true); 3659 3660 // Create load nodes to retrieve arguments from the stack. 3661 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3662 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3663 MachinePointerInfo::getFixedStack( 3664 DAG.getMachineFunction(), FI))); 3665 } 3666 lastInsIndex = index; 3667 } 3668 } 3669 } 3670 3671 // varargs 3672 if (isVarArg && MFI.hasVAStart()) 3673 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3674 CCInfo.getNextStackOffset(), 3675 TotalArgRegsSaveSize); 3676 3677 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3678 3679 return Chain; 3680 } 3681 3682 /// isFloatingPointZero - Return true if this is +0.0. 3683 static bool isFloatingPointZero(SDValue Op) { 3684 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3685 return CFP->getValueAPF().isPosZero(); 3686 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3687 // Maybe this has already been legalized into the constant pool? 3688 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3689 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3690 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3691 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3692 return CFP->getValueAPF().isPosZero(); 3693 } 3694 } else if (Op->getOpcode() == ISD::BITCAST && 3695 Op->getValueType(0) == MVT::f64) { 3696 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3697 // created by LowerConstantFP(). 3698 SDValue BitcastOp = Op->getOperand(0); 3699 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3700 isNullConstant(BitcastOp->getOperand(0))) 3701 return true; 3702 } 3703 return false; 3704 } 3705 3706 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3707 /// the given operands. 3708 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3709 SDValue &ARMcc, SelectionDAG &DAG, 3710 const SDLoc &dl) const { 3711 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3712 unsigned C = RHSC->getZExtValue(); 3713 if (!isLegalICmpImmediate(C)) { 3714 // Constant does not fit, try adjusting it by one? 3715 switch (CC) { 3716 default: break; 3717 case ISD::SETLT: 3718 case ISD::SETGE: 3719 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3720 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3721 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3722 } 3723 break; 3724 case ISD::SETULT: 3725 case ISD::SETUGE: 3726 if (C != 0 && isLegalICmpImmediate(C-1)) { 3727 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3728 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3729 } 3730 break; 3731 case ISD::SETLE: 3732 case ISD::SETGT: 3733 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3734 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3735 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3736 } 3737 break; 3738 case ISD::SETULE: 3739 case ISD::SETUGT: 3740 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3741 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3742 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3743 } 3744 break; 3745 } 3746 } 3747 } 3748 3749 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3750 ARMISD::NodeType CompareType; 3751 switch (CondCode) { 3752 default: 3753 CompareType = ARMISD::CMP; 3754 break; 3755 case ARMCC::EQ: 3756 case ARMCC::NE: 3757 // Uses only Z Flag 3758 CompareType = ARMISD::CMPZ; 3759 break; 3760 } 3761 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3762 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3763 } 3764 3765 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3766 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3767 SelectionDAG &DAG, const SDLoc &dl) const { 3768 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3769 SDValue Cmp; 3770 if (!isFloatingPointZero(RHS)) 3771 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3772 else 3773 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3774 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3775 } 3776 3777 /// duplicateCmp - Glue values can have only one use, so this function 3778 /// duplicates a comparison node. 3779 SDValue 3780 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3781 unsigned Opc = Cmp.getOpcode(); 3782 SDLoc DL(Cmp); 3783 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3784 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3785 3786 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3787 Cmp = Cmp.getOperand(0); 3788 Opc = Cmp.getOpcode(); 3789 if (Opc == ARMISD::CMPFP) 3790 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3791 else { 3792 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3793 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3794 } 3795 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3796 } 3797 3798 std::pair<SDValue, SDValue> 3799 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3800 SDValue &ARMcc) const { 3801 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3802 3803 SDValue Value, OverflowCmp; 3804 SDValue LHS = Op.getOperand(0); 3805 SDValue RHS = Op.getOperand(1); 3806 SDLoc dl(Op); 3807 3808 // FIXME: We are currently always generating CMPs because we don't support 3809 // generating CMN through the backend. This is not as good as the natural 3810 // CMP case because it causes a register dependency and cannot be folded 3811 // later. 3812 3813 switch (Op.getOpcode()) { 3814 default: 3815 llvm_unreachable("Unknown overflow instruction!"); 3816 case ISD::SADDO: 3817 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3818 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3819 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3820 break; 3821 case ISD::UADDO: 3822 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3823 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3824 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3825 break; 3826 case ISD::SSUBO: 3827 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3828 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3829 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3830 break; 3831 case ISD::USUBO: 3832 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3833 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3834 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3835 break; 3836 } // switch (...) 3837 3838 return std::make_pair(Value, OverflowCmp); 3839 } 3840 3841 SDValue 3842 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3843 // Let legalize expand this if it isn't a legal type yet. 3844 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3845 return SDValue(); 3846 3847 SDValue Value, OverflowCmp; 3848 SDValue ARMcc; 3849 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3850 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3851 SDLoc dl(Op); 3852 // We use 0 and 1 as false and true values. 3853 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3854 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3855 EVT VT = Op.getValueType(); 3856 3857 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3858 ARMcc, CCR, OverflowCmp); 3859 3860 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3861 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3862 } 3863 3864 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3865 SDValue Cond = Op.getOperand(0); 3866 SDValue SelectTrue = Op.getOperand(1); 3867 SDValue SelectFalse = Op.getOperand(2); 3868 SDLoc dl(Op); 3869 unsigned Opc = Cond.getOpcode(); 3870 3871 if (Cond.getResNo() == 1 && 3872 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3873 Opc == ISD::USUBO)) { 3874 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3875 return SDValue(); 3876 3877 SDValue Value, OverflowCmp; 3878 SDValue ARMcc; 3879 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3880 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3881 EVT VT = Op.getValueType(); 3882 3883 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3884 OverflowCmp, DAG); 3885 } 3886 3887 // Convert: 3888 // 3889 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3890 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3891 // 3892 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3893 const ConstantSDNode *CMOVTrue = 3894 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3895 const ConstantSDNode *CMOVFalse = 3896 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3897 3898 if (CMOVTrue && CMOVFalse) { 3899 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3900 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3901 3902 SDValue True; 3903 SDValue False; 3904 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3905 True = SelectTrue; 3906 False = SelectFalse; 3907 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3908 True = SelectFalse; 3909 False = SelectTrue; 3910 } 3911 3912 if (True.getNode() && False.getNode()) { 3913 EVT VT = Op.getValueType(); 3914 SDValue ARMcc = Cond.getOperand(2); 3915 SDValue CCR = Cond.getOperand(3); 3916 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3917 assert(True.getValueType() == VT); 3918 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3919 } 3920 } 3921 } 3922 3923 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3924 // undefined bits before doing a full-word comparison with zero. 3925 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3926 DAG.getConstant(1, dl, Cond.getValueType())); 3927 3928 return DAG.getSelectCC(dl, Cond, 3929 DAG.getConstant(0, dl, Cond.getValueType()), 3930 SelectTrue, SelectFalse, ISD::SETNE); 3931 } 3932 3933 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3934 bool &swpCmpOps, bool &swpVselOps) { 3935 // Start by selecting the GE condition code for opcodes that return true for 3936 // 'equality' 3937 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3938 CC == ISD::SETULE) 3939 CondCode = ARMCC::GE; 3940 3941 // and GT for opcodes that return false for 'equality'. 3942 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3943 CC == ISD::SETULT) 3944 CondCode = ARMCC::GT; 3945 3946 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3947 // to swap the compare operands. 3948 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3949 CC == ISD::SETULT) 3950 swpCmpOps = true; 3951 3952 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3953 // If we have an unordered opcode, we need to swap the operands to the VSEL 3954 // instruction (effectively negating the condition). 3955 // 3956 // This also has the effect of swapping which one of 'less' or 'greater' 3957 // returns true, so we also swap the compare operands. It also switches 3958 // whether we return true for 'equality', so we compensate by picking the 3959 // opposite condition code to our original choice. 3960 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3961 CC == ISD::SETUGT) { 3962 swpCmpOps = !swpCmpOps; 3963 swpVselOps = !swpVselOps; 3964 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3965 } 3966 3967 // 'ordered' is 'anything but unordered', so use the VS condition code and 3968 // swap the VSEL operands. 3969 if (CC == ISD::SETO) { 3970 CondCode = ARMCC::VS; 3971 swpVselOps = true; 3972 } 3973 3974 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3975 // code and swap the VSEL operands. 3976 if (CC == ISD::SETUNE) { 3977 CondCode = ARMCC::EQ; 3978 swpVselOps = true; 3979 } 3980 } 3981 3982 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 3983 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 3984 SDValue Cmp, SelectionDAG &DAG) const { 3985 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 3986 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3987 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 3988 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 3989 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 3990 3991 SDValue TrueLow = TrueVal.getValue(0); 3992 SDValue TrueHigh = TrueVal.getValue(1); 3993 SDValue FalseLow = FalseVal.getValue(0); 3994 SDValue FalseHigh = FalseVal.getValue(1); 3995 3996 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 3997 ARMcc, CCR, Cmp); 3998 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 3999 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4000 4001 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4002 } else { 4003 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4004 Cmp); 4005 } 4006 } 4007 4008 static bool isGTorGE(ISD::CondCode CC) { 4009 return CC == ISD::SETGT || CC == ISD::SETGE; 4010 } 4011 4012 static bool isLTorLE(ISD::CondCode CC) { 4013 return CC == ISD::SETLT || CC == ISD::SETLE; 4014 } 4015 4016 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4017 // All of these conditions (and their <= and >= counterparts) will do: 4018 // x < k ? k : x 4019 // x > k ? x : k 4020 // k < x ? x : k 4021 // k > x ? k : x 4022 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4023 const SDValue TrueVal, const SDValue FalseVal, 4024 const ISD::CondCode CC, const SDValue K) { 4025 return (isGTorGE(CC) && 4026 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4027 (isLTorLE(CC) && 4028 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4029 } 4030 4031 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4032 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4033 const SDValue TrueVal, const SDValue FalseVal, 4034 const ISD::CondCode CC, const SDValue K) { 4035 return (isGTorGE(CC) && 4036 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4037 (isLTorLE(CC) && 4038 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4039 } 4040 4041 // Check if two chained conditionals could be converted into SSAT. 4042 // 4043 // SSAT can replace a set of two conditional selectors that bound a number to an 4044 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4045 // 4046 // x < -k ? -k : (x > k ? k : x) 4047 // x < -k ? -k : (x < k ? x : k) 4048 // x > -k ? (x > k ? k : x) : -k 4049 // x < k ? (x < -k ? -k : x) : k 4050 // etc. 4051 // 4052 // It returns true if the conversion can be done, false otherwise. 4053 // Additionally, the variable is returned in parameter V and the constant in K. 4054 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4055 uint64_t &K) { 4056 SDValue LHS1 = Op.getOperand(0); 4057 SDValue RHS1 = Op.getOperand(1); 4058 SDValue TrueVal1 = Op.getOperand(2); 4059 SDValue FalseVal1 = Op.getOperand(3); 4060 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4061 4062 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4063 if (Op2.getOpcode() != ISD::SELECT_CC) 4064 return false; 4065 4066 SDValue LHS2 = Op2.getOperand(0); 4067 SDValue RHS2 = Op2.getOperand(1); 4068 SDValue TrueVal2 = Op2.getOperand(2); 4069 SDValue FalseVal2 = Op2.getOperand(3); 4070 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4071 4072 // Find out which are the constants and which are the variables 4073 // in each conditional 4074 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4075 ? &RHS1 4076 : nullptr; 4077 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4078 ? &RHS2 4079 : nullptr; 4080 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4081 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4082 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4083 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4084 4085 // We must detect cases where the original operations worked with 16- or 4086 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4087 // must work with sign-extended values but the select operations return 4088 // the original non-extended value. 4089 SDValue V2TmpReg = V2Tmp; 4090 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4091 V2TmpReg = V2Tmp->getOperand(0); 4092 4093 // Check that the registers and the constants have the correct values 4094 // in both conditionals 4095 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4096 V2TmpReg != V2) 4097 return false; 4098 4099 // Figure out which conditional is saturating the lower/upper bound. 4100 const SDValue *LowerCheckOp = 4101 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4102 ? &Op 4103 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4104 ? &Op2 4105 : nullptr; 4106 const SDValue *UpperCheckOp = 4107 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4108 ? &Op 4109 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4110 ? &Op2 4111 : nullptr; 4112 4113 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4114 return false; 4115 4116 // Check that the constant in the lower-bound check is 4117 // the opposite of the constant in the upper-bound check 4118 // in 1's complement. 4119 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4120 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4121 int64_t PosVal = std::max(Val1, Val2); 4122 4123 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4124 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4125 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) { 4126 4127 V = V2; 4128 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4129 return true; 4130 } 4131 4132 return false; 4133 } 4134 4135 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4136 EVT VT = Op.getValueType(); 4137 SDLoc dl(Op); 4138 4139 // Try to convert two saturating conditional selects into a single SSAT 4140 SDValue SatValue; 4141 uint64_t SatConstant; 4142 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4143 isSaturatingConditional(Op, SatValue, SatConstant)) 4144 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4145 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4146 4147 SDValue LHS = Op.getOperand(0); 4148 SDValue RHS = Op.getOperand(1); 4149 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4150 SDValue TrueVal = Op.getOperand(2); 4151 SDValue FalseVal = Op.getOperand(3); 4152 4153 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4154 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4155 dl); 4156 4157 // If softenSetCCOperands only returned one value, we should compare it to 4158 // zero. 4159 if (!RHS.getNode()) { 4160 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4161 CC = ISD::SETNE; 4162 } 4163 } 4164 4165 if (LHS.getValueType() == MVT::i32) { 4166 // Try to generate VSEL on ARMv8. 4167 // The VSEL instruction can't use all the usual ARM condition 4168 // codes: it only has two bits to select the condition code, so it's 4169 // constrained to use only GE, GT, VS and EQ. 4170 // 4171 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4172 // swap the operands of the previous compare instruction (effectively 4173 // inverting the compare condition, swapping 'less' and 'greater') and 4174 // sometimes need to swap the operands to the VSEL (which inverts the 4175 // condition in the sense of firing whenever the previous condition didn't) 4176 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4177 TrueVal.getValueType() == MVT::f64)) { 4178 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4179 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4180 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4181 CC = ISD::getSetCCInverse(CC, true); 4182 std::swap(TrueVal, FalseVal); 4183 } 4184 } 4185 4186 SDValue ARMcc; 4187 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4188 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4189 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4190 } 4191 4192 ARMCC::CondCodes CondCode, CondCode2; 4193 FPCCToARMCC(CC, CondCode, CondCode2); 4194 4195 // Try to generate VMAXNM/VMINNM on ARMv8. 4196 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4197 TrueVal.getValueType() == MVT::f64)) { 4198 bool swpCmpOps = false; 4199 bool swpVselOps = false; 4200 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4201 4202 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4203 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4204 if (swpCmpOps) 4205 std::swap(LHS, RHS); 4206 if (swpVselOps) 4207 std::swap(TrueVal, FalseVal); 4208 } 4209 } 4210 4211 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4212 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 4213 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4214 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4215 if (CondCode2 != ARMCC::AL) { 4216 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4217 // FIXME: Needs another CMP because flag can have but one use. 4218 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 4219 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4220 } 4221 return Result; 4222 } 4223 4224 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4225 /// to morph to an integer compare sequence. 4226 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4227 const ARMSubtarget *Subtarget) { 4228 SDNode *N = Op.getNode(); 4229 if (!N->hasOneUse()) 4230 // Otherwise it requires moving the value from fp to integer registers. 4231 return false; 4232 if (!N->getNumValues()) 4233 return false; 4234 EVT VT = Op.getValueType(); 4235 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4236 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4237 // vmrs are very slow, e.g. cortex-a8. 4238 return false; 4239 4240 if (isFloatingPointZero(Op)) { 4241 SeenZero = true; 4242 return true; 4243 } 4244 return ISD::isNormalLoad(N); 4245 } 4246 4247 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4248 if (isFloatingPointZero(Op)) 4249 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4250 4251 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4252 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4253 Ld->getPointerInfo(), Ld->getAlignment(), 4254 Ld->getMemOperand()->getFlags()); 4255 4256 llvm_unreachable("Unknown VFP cmp argument!"); 4257 } 4258 4259 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4260 SDValue &RetVal1, SDValue &RetVal2) { 4261 SDLoc dl(Op); 4262 4263 if (isFloatingPointZero(Op)) { 4264 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4265 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4266 return; 4267 } 4268 4269 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4270 SDValue Ptr = Ld->getBasePtr(); 4271 RetVal1 = 4272 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4273 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4274 4275 EVT PtrType = Ptr.getValueType(); 4276 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4277 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4278 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4279 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4280 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4281 Ld->getMemOperand()->getFlags()); 4282 return; 4283 } 4284 4285 llvm_unreachable("Unknown VFP cmp argument!"); 4286 } 4287 4288 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4289 /// f32 and even f64 comparisons to integer ones. 4290 SDValue 4291 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4292 SDValue Chain = Op.getOperand(0); 4293 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4294 SDValue LHS = Op.getOperand(2); 4295 SDValue RHS = Op.getOperand(3); 4296 SDValue Dest = Op.getOperand(4); 4297 SDLoc dl(Op); 4298 4299 bool LHSSeenZero = false; 4300 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4301 bool RHSSeenZero = false; 4302 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4303 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4304 // If unsafe fp math optimization is enabled and there are no other uses of 4305 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4306 // to an integer comparison. 4307 if (CC == ISD::SETOEQ) 4308 CC = ISD::SETEQ; 4309 else if (CC == ISD::SETUNE) 4310 CC = ISD::SETNE; 4311 4312 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4313 SDValue ARMcc; 4314 if (LHS.getValueType() == MVT::f32) { 4315 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4316 bitcastf32Toi32(LHS, DAG), Mask); 4317 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4318 bitcastf32Toi32(RHS, DAG), Mask); 4319 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4320 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4321 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4322 Chain, Dest, ARMcc, CCR, Cmp); 4323 } 4324 4325 SDValue LHS1, LHS2; 4326 SDValue RHS1, RHS2; 4327 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4328 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4329 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4330 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4331 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4332 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4333 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4334 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4335 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4336 } 4337 4338 return SDValue(); 4339 } 4340 4341 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4342 SDValue Chain = Op.getOperand(0); 4343 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4344 SDValue LHS = Op.getOperand(2); 4345 SDValue RHS = Op.getOperand(3); 4346 SDValue Dest = Op.getOperand(4); 4347 SDLoc dl(Op); 4348 4349 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4350 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4351 dl); 4352 4353 // If softenSetCCOperands only returned one value, we should compare it to 4354 // zero. 4355 if (!RHS.getNode()) { 4356 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4357 CC = ISD::SETNE; 4358 } 4359 } 4360 4361 if (LHS.getValueType() == MVT::i32) { 4362 SDValue ARMcc; 4363 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4364 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4365 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4366 Chain, Dest, ARMcc, CCR, Cmp); 4367 } 4368 4369 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4370 4371 if (getTargetMachine().Options.UnsafeFPMath && 4372 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4373 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4374 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4375 return Result; 4376 } 4377 4378 ARMCC::CondCodes CondCode, CondCode2; 4379 FPCCToARMCC(CC, CondCode, CondCode2); 4380 4381 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4382 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 4383 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4384 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4385 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4386 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4387 if (CondCode2 != ARMCC::AL) { 4388 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4389 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4390 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4391 } 4392 return Res; 4393 } 4394 4395 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4396 SDValue Chain = Op.getOperand(0); 4397 SDValue Table = Op.getOperand(1); 4398 SDValue Index = Op.getOperand(2); 4399 SDLoc dl(Op); 4400 4401 EVT PTy = getPointerTy(DAG.getDataLayout()); 4402 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4403 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4404 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4405 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4406 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4407 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4408 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4409 // which does another jump to the destination. This also makes it easier 4410 // to translate it to TBB / TBH later (Thumb2 only). 4411 // FIXME: This might not work if the function is extremely large. 4412 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4413 Addr, Op.getOperand(2), JTI); 4414 } 4415 if (isPositionIndependent() || Subtarget->isROPI()) { 4416 Addr = 4417 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4418 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4419 Chain = Addr.getValue(1); 4420 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4421 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4422 } else { 4423 Addr = 4424 DAG.getLoad(PTy, dl, Chain, Addr, 4425 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4426 Chain = Addr.getValue(1); 4427 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4428 } 4429 } 4430 4431 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4432 EVT VT = Op.getValueType(); 4433 SDLoc dl(Op); 4434 4435 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4436 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4437 return Op; 4438 return DAG.UnrollVectorOp(Op.getNode()); 4439 } 4440 4441 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4442 "Invalid type for custom lowering!"); 4443 if (VT != MVT::v4i16) 4444 return DAG.UnrollVectorOp(Op.getNode()); 4445 4446 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4447 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4448 } 4449 4450 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4451 EVT VT = Op.getValueType(); 4452 if (VT.isVector()) 4453 return LowerVectorFP_TO_INT(Op, DAG); 4454 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4455 RTLIB::Libcall LC; 4456 if (Op.getOpcode() == ISD::FP_TO_SINT) 4457 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4458 Op.getValueType()); 4459 else 4460 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4461 Op.getValueType()); 4462 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4463 /*isSigned*/ false, SDLoc(Op)).first; 4464 } 4465 4466 return Op; 4467 } 4468 4469 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4470 EVT VT = Op.getValueType(); 4471 SDLoc dl(Op); 4472 4473 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4474 if (VT.getVectorElementType() == MVT::f32) 4475 return Op; 4476 return DAG.UnrollVectorOp(Op.getNode()); 4477 } 4478 4479 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4480 "Invalid type for custom lowering!"); 4481 if (VT != MVT::v4f32) 4482 return DAG.UnrollVectorOp(Op.getNode()); 4483 4484 unsigned CastOpc; 4485 unsigned Opc; 4486 switch (Op.getOpcode()) { 4487 default: llvm_unreachable("Invalid opcode!"); 4488 case ISD::SINT_TO_FP: 4489 CastOpc = ISD::SIGN_EXTEND; 4490 Opc = ISD::SINT_TO_FP; 4491 break; 4492 case ISD::UINT_TO_FP: 4493 CastOpc = ISD::ZERO_EXTEND; 4494 Opc = ISD::UINT_TO_FP; 4495 break; 4496 } 4497 4498 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4499 return DAG.getNode(Opc, dl, VT, Op); 4500 } 4501 4502 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4503 EVT VT = Op.getValueType(); 4504 if (VT.isVector()) 4505 return LowerVectorINT_TO_FP(Op, DAG); 4506 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4507 RTLIB::Libcall LC; 4508 if (Op.getOpcode() == ISD::SINT_TO_FP) 4509 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4510 Op.getValueType()); 4511 else 4512 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4513 Op.getValueType()); 4514 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4515 /*isSigned*/ false, SDLoc(Op)).first; 4516 } 4517 4518 return Op; 4519 } 4520 4521 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4522 // Implement fcopysign with a fabs and a conditional fneg. 4523 SDValue Tmp0 = Op.getOperand(0); 4524 SDValue Tmp1 = Op.getOperand(1); 4525 SDLoc dl(Op); 4526 EVT VT = Op.getValueType(); 4527 EVT SrcVT = Tmp1.getValueType(); 4528 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4529 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4530 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4531 4532 if (UseNEON) { 4533 // Use VBSL to copy the sign bit. 4534 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4535 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4536 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4537 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4538 if (VT == MVT::f64) 4539 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4540 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4541 DAG.getConstant(32, dl, MVT::i32)); 4542 else /*if (VT == MVT::f32)*/ 4543 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4544 if (SrcVT == MVT::f32) { 4545 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4546 if (VT == MVT::f64) 4547 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4548 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4549 DAG.getConstant(32, dl, MVT::i32)); 4550 } else if (VT == MVT::f32) 4551 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4552 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4553 DAG.getConstant(32, dl, MVT::i32)); 4554 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4555 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4556 4557 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4558 dl, MVT::i32); 4559 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4560 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4561 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4562 4563 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4564 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4565 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4566 if (VT == MVT::f32) { 4567 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4568 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4569 DAG.getConstant(0, dl, MVT::i32)); 4570 } else { 4571 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4572 } 4573 4574 return Res; 4575 } 4576 4577 // Bitcast operand 1 to i32. 4578 if (SrcVT == MVT::f64) 4579 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4580 Tmp1).getValue(1); 4581 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4582 4583 // Or in the signbit with integer operations. 4584 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4585 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4586 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4587 if (VT == MVT::f32) { 4588 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4589 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4590 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4591 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4592 } 4593 4594 // f64: Or the high part with signbit and then combine two parts. 4595 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4596 Tmp0); 4597 SDValue Lo = Tmp0.getValue(0); 4598 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4599 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4600 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4601 } 4602 4603 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4604 MachineFunction &MF = DAG.getMachineFunction(); 4605 MachineFrameInfo &MFI = MF.getFrameInfo(); 4606 MFI.setReturnAddressIsTaken(true); 4607 4608 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4609 return SDValue(); 4610 4611 EVT VT = Op.getValueType(); 4612 SDLoc dl(Op); 4613 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4614 if (Depth) { 4615 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4616 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4617 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4618 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4619 MachinePointerInfo()); 4620 } 4621 4622 // Return LR, which contains the return address. Mark it an implicit live-in. 4623 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4624 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4625 } 4626 4627 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4628 const ARMBaseRegisterInfo &ARI = 4629 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4630 MachineFunction &MF = DAG.getMachineFunction(); 4631 MachineFrameInfo &MFI = MF.getFrameInfo(); 4632 MFI.setFrameAddressIsTaken(true); 4633 4634 EVT VT = Op.getValueType(); 4635 SDLoc dl(Op); // FIXME probably not meaningful 4636 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4637 unsigned FrameReg = ARI.getFrameRegister(MF); 4638 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4639 while (Depth--) 4640 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4641 MachinePointerInfo()); 4642 return FrameAddr; 4643 } 4644 4645 // FIXME? Maybe this could be a TableGen attribute on some registers and 4646 // this table could be generated automatically from RegInfo. 4647 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4648 SelectionDAG &DAG) const { 4649 unsigned Reg = StringSwitch<unsigned>(RegName) 4650 .Case("sp", ARM::SP) 4651 .Default(0); 4652 if (Reg) 4653 return Reg; 4654 report_fatal_error(Twine("Invalid register name \"" 4655 + StringRef(RegName) + "\".")); 4656 } 4657 4658 // Result is 64 bit value so split into two 32 bit values and return as a 4659 // pair of values. 4660 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4661 SelectionDAG &DAG) { 4662 SDLoc DL(N); 4663 4664 // This function is only supposed to be called for i64 type destination. 4665 assert(N->getValueType(0) == MVT::i64 4666 && "ExpandREAD_REGISTER called for non-i64 type result."); 4667 4668 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4669 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4670 N->getOperand(0), 4671 N->getOperand(1)); 4672 4673 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4674 Read.getValue(1))); 4675 Results.push_back(Read.getOperand(0)); 4676 } 4677 4678 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4679 /// When \p DstVT, the destination type of \p BC, is on the vector 4680 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4681 /// it might be possible to combine them, such that everything stays on the 4682 /// vector register bank. 4683 /// \p return The node that would replace \p BT, if the combine 4684 /// is possible. 4685 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4686 SelectionDAG &DAG) { 4687 SDValue Op = BC->getOperand(0); 4688 EVT DstVT = BC->getValueType(0); 4689 4690 // The only vector instruction that can produce a scalar (remember, 4691 // since the bitcast was about to be turned into VMOVDRR, the source 4692 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4693 // Moreover, we can do this combine only if there is one use. 4694 // Finally, if the destination type is not a vector, there is not 4695 // much point on forcing everything on the vector bank. 4696 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4697 !Op.hasOneUse()) 4698 return SDValue(); 4699 4700 // If the index is not constant, we will introduce an additional 4701 // multiply that will stick. 4702 // Give up in that case. 4703 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4704 if (!Index) 4705 return SDValue(); 4706 unsigned DstNumElt = DstVT.getVectorNumElements(); 4707 4708 // Compute the new index. 4709 const APInt &APIntIndex = Index->getAPIntValue(); 4710 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4711 NewIndex *= APIntIndex; 4712 // Check if the new constant index fits into i32. 4713 if (NewIndex.getBitWidth() > 32) 4714 return SDValue(); 4715 4716 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4717 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4718 SDLoc dl(Op); 4719 SDValue ExtractSrc = Op.getOperand(0); 4720 EVT VecVT = EVT::getVectorVT( 4721 *DAG.getContext(), DstVT.getScalarType(), 4722 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4723 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4724 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4725 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4726 } 4727 4728 /// ExpandBITCAST - If the target supports VFP, this function is called to 4729 /// expand a bit convert where either the source or destination type is i64 to 4730 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4731 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4732 /// vectors), since the legalizer won't know what to do with that. 4733 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4734 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4735 SDLoc dl(N); 4736 SDValue Op = N->getOperand(0); 4737 4738 // This function is only supposed to be called for i64 types, either as the 4739 // source or destination of the bit convert. 4740 EVT SrcVT = Op.getValueType(); 4741 EVT DstVT = N->getValueType(0); 4742 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4743 "ExpandBITCAST called for non-i64 type"); 4744 4745 // Turn i64->f64 into VMOVDRR. 4746 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4747 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4748 // if we can combine the bitcast with its source. 4749 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4750 return Val; 4751 4752 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4753 DAG.getConstant(0, dl, MVT::i32)); 4754 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4755 DAG.getConstant(1, dl, MVT::i32)); 4756 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4757 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4758 } 4759 4760 // Turn f64->i64 into VMOVRRD. 4761 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4762 SDValue Cvt; 4763 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4764 SrcVT.getVectorNumElements() > 1) 4765 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4766 DAG.getVTList(MVT::i32, MVT::i32), 4767 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4768 else 4769 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4770 DAG.getVTList(MVT::i32, MVT::i32), Op); 4771 // Merge the pieces into a single i64 value. 4772 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4773 } 4774 4775 return SDValue(); 4776 } 4777 4778 /// getZeroVector - Returns a vector of specified type with all zero elements. 4779 /// Zero vectors are used to represent vector negation and in those cases 4780 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4781 /// not support i64 elements, so sometimes the zero vectors will need to be 4782 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4783 /// zero vector. 4784 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 4785 assert(VT.isVector() && "Expected a vector type"); 4786 // The canonical modified immediate encoding of a zero vector is....0! 4787 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4788 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4789 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4790 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4791 } 4792 4793 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4794 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4795 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4796 SelectionDAG &DAG) const { 4797 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4798 EVT VT = Op.getValueType(); 4799 unsigned VTBits = VT.getSizeInBits(); 4800 SDLoc dl(Op); 4801 SDValue ShOpLo = Op.getOperand(0); 4802 SDValue ShOpHi = Op.getOperand(1); 4803 SDValue ShAmt = Op.getOperand(2); 4804 SDValue ARMcc; 4805 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4806 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4807 4808 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4809 4810 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4811 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4812 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4813 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4814 DAG.getConstant(VTBits, dl, MVT::i32)); 4815 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4816 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4817 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4818 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4819 ISD::SETGE, ARMcc, DAG, dl); 4820 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 4821 ARMcc, CCR, CmpLo); 4822 4823 4824 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4825 SDValue HiBigShift = Opc == ISD::SRA 4826 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4827 DAG.getConstant(VTBits - 1, dl, VT)) 4828 : DAG.getConstant(0, dl, VT); 4829 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4830 ISD::SETGE, ARMcc, DAG, dl); 4831 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 4832 ARMcc, CCR, CmpHi); 4833 4834 SDValue Ops[2] = { Lo, Hi }; 4835 return DAG.getMergeValues(Ops, dl); 4836 } 4837 4838 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4839 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4840 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4841 SelectionDAG &DAG) const { 4842 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4843 EVT VT = Op.getValueType(); 4844 unsigned VTBits = VT.getSizeInBits(); 4845 SDLoc dl(Op); 4846 SDValue ShOpLo = Op.getOperand(0); 4847 SDValue ShOpHi = Op.getOperand(1); 4848 SDValue ShAmt = Op.getOperand(2); 4849 SDValue ARMcc; 4850 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4851 4852 assert(Op.getOpcode() == ISD::SHL_PARTS); 4853 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4854 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4855 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4856 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4857 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4858 4859 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4860 DAG.getConstant(VTBits, dl, MVT::i32)); 4861 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4862 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4863 ISD::SETGE, ARMcc, DAG, dl); 4864 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 4865 ARMcc, CCR, CmpHi); 4866 4867 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4868 ISD::SETGE, ARMcc, DAG, dl); 4869 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4870 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 4871 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 4872 4873 SDValue Ops[2] = { Lo, Hi }; 4874 return DAG.getMergeValues(Ops, dl); 4875 } 4876 4877 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4878 SelectionDAG &DAG) const { 4879 // The rounding mode is in bits 23:22 of the FPSCR. 4880 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4881 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4882 // so that the shift + and get folded into a bitfield extract. 4883 SDLoc dl(Op); 4884 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4885 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4886 MVT::i32)); 4887 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4888 DAG.getConstant(1U << 22, dl, MVT::i32)); 4889 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4890 DAG.getConstant(22, dl, MVT::i32)); 4891 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4892 DAG.getConstant(3, dl, MVT::i32)); 4893 } 4894 4895 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4896 const ARMSubtarget *ST) { 4897 SDLoc dl(N); 4898 EVT VT = N->getValueType(0); 4899 if (VT.isVector()) { 4900 assert(ST->hasNEON()); 4901 4902 // Compute the least significant set bit: LSB = X & -X 4903 SDValue X = N->getOperand(0); 4904 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4905 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4906 4907 EVT ElemTy = VT.getVectorElementType(); 4908 4909 if (ElemTy == MVT::i8) { 4910 // Compute with: cttz(x) = ctpop(lsb - 1) 4911 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4912 DAG.getTargetConstant(1, dl, ElemTy)); 4913 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4914 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4915 } 4916 4917 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4918 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4919 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4920 unsigned NumBits = ElemTy.getSizeInBits(); 4921 SDValue WidthMinus1 = 4922 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4923 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4924 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4925 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4926 } 4927 4928 // Compute with: cttz(x) = ctpop(lsb - 1) 4929 4930 // Since we can only compute the number of bits in a byte with vcnt.8, we 4931 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4932 // and i64. 4933 4934 // Compute LSB - 1. 4935 SDValue Bits; 4936 if (ElemTy == MVT::i64) { 4937 // Load constant 0xffff'ffff'ffff'ffff to register. 4938 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4939 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4940 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4941 } else { 4942 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4943 DAG.getTargetConstant(1, dl, ElemTy)); 4944 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4945 } 4946 4947 // Count #bits with vcnt.8. 4948 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4949 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4950 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4951 4952 // Gather the #bits with vpaddl (pairwise add.) 4953 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4954 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4955 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4956 Cnt8); 4957 if (ElemTy == MVT::i16) 4958 return Cnt16; 4959 4960 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4961 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4962 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4963 Cnt16); 4964 if (ElemTy == MVT::i32) 4965 return Cnt32; 4966 4967 assert(ElemTy == MVT::i64); 4968 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4969 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4970 Cnt32); 4971 return Cnt64; 4972 } 4973 4974 if (!ST->hasV6T2Ops()) 4975 return SDValue(); 4976 4977 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 4978 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 4979 } 4980 4981 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 4982 /// for each 16-bit element from operand, repeated. The basic idea is to 4983 /// leverage vcnt to get the 8-bit counts, gather and add the results. 4984 /// 4985 /// Trace for v4i16: 4986 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 4987 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 4988 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 4989 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 4990 /// [b0 b1 b2 b3 b4 b5 b6 b7] 4991 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 4992 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 4993 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 4994 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 4995 EVT VT = N->getValueType(0); 4996 SDLoc DL(N); 4997 4998 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4999 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5000 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5001 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5002 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5003 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5004 } 5005 5006 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5007 /// bit-count for each 16-bit element from the operand. We need slightly 5008 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5009 /// 64/128-bit registers. 5010 /// 5011 /// Trace for v4i16: 5012 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5013 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5014 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5015 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5016 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5017 EVT VT = N->getValueType(0); 5018 SDLoc DL(N); 5019 5020 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5021 if (VT.is64BitVector()) { 5022 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5023 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5024 DAG.getIntPtrConstant(0, DL)); 5025 } else { 5026 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5027 BitCounts, DAG.getIntPtrConstant(0, DL)); 5028 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5029 } 5030 } 5031 5032 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5033 /// bit-count for each 32-bit element from the operand. The idea here is 5034 /// to split the vector into 16-bit elements, leverage the 16-bit count 5035 /// routine, and then combine the results. 5036 /// 5037 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5038 /// input = [v0 v1 ] (vi: 32-bit elements) 5039 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5040 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5041 /// vrev: N0 = [k1 k0 k3 k2 ] 5042 /// [k0 k1 k2 k3 ] 5043 /// N1 =+[k1 k0 k3 k2 ] 5044 /// [k0 k2 k1 k3 ] 5045 /// N2 =+[k1 k3 k0 k2 ] 5046 /// [k0 k2 k1 k3 ] 5047 /// Extended =+[k1 k3 k0 k2 ] 5048 /// [k0 k2 ] 5049 /// Extracted=+[k1 k3 ] 5050 /// 5051 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5052 EVT VT = N->getValueType(0); 5053 SDLoc DL(N); 5054 5055 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5056 5057 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5058 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5059 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5060 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5061 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5062 5063 if (VT.is64BitVector()) { 5064 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5065 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5066 DAG.getIntPtrConstant(0, DL)); 5067 } else { 5068 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5069 DAG.getIntPtrConstant(0, DL)); 5070 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5071 } 5072 } 5073 5074 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5075 const ARMSubtarget *ST) { 5076 EVT VT = N->getValueType(0); 5077 5078 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5079 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5080 VT == MVT::v4i16 || VT == MVT::v8i16) && 5081 "Unexpected type for custom ctpop lowering"); 5082 5083 if (VT.getVectorElementType() == MVT::i32) 5084 return lowerCTPOP32BitElements(N, DAG); 5085 else 5086 return lowerCTPOP16BitElements(N, DAG); 5087 } 5088 5089 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5090 const ARMSubtarget *ST) { 5091 EVT VT = N->getValueType(0); 5092 SDLoc dl(N); 5093 5094 if (!VT.isVector()) 5095 return SDValue(); 5096 5097 // Lower vector shifts on NEON to use VSHL. 5098 assert(ST->hasNEON() && "unexpected vector shift"); 5099 5100 // Left shifts translate directly to the vshiftu intrinsic. 5101 if (N->getOpcode() == ISD::SHL) 5102 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5103 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5104 MVT::i32), 5105 N->getOperand(0), N->getOperand(1)); 5106 5107 assert((N->getOpcode() == ISD::SRA || 5108 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5109 5110 // NEON uses the same intrinsics for both left and right shifts. For 5111 // right shifts, the shift amounts are negative, so negate the vector of 5112 // shift amounts. 5113 EVT ShiftVT = N->getOperand(1).getValueType(); 5114 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5115 getZeroVector(ShiftVT, DAG, dl), 5116 N->getOperand(1)); 5117 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5118 Intrinsic::arm_neon_vshifts : 5119 Intrinsic::arm_neon_vshiftu); 5120 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5121 DAG.getConstant(vshiftInt, dl, MVT::i32), 5122 N->getOperand(0), NegatedCount); 5123 } 5124 5125 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5126 const ARMSubtarget *ST) { 5127 EVT VT = N->getValueType(0); 5128 SDLoc dl(N); 5129 5130 // We can get here for a node like i32 = ISD::SHL i32, i64 5131 if (VT != MVT::i64) 5132 return SDValue(); 5133 5134 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5135 "Unknown shift to lower!"); 5136 5137 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5138 if (!isOneConstant(N->getOperand(1))) 5139 return SDValue(); 5140 5141 // If we are in thumb mode, we don't have RRX. 5142 if (ST->isThumb1Only()) return SDValue(); 5143 5144 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5145 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5146 DAG.getConstant(0, dl, MVT::i32)); 5147 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5148 DAG.getConstant(1, dl, MVT::i32)); 5149 5150 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5151 // captures the result into a carry flag. 5152 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5153 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5154 5155 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5156 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5157 5158 // Merge the pieces into a single i64 value. 5159 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5160 } 5161 5162 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5163 SDValue TmpOp0, TmpOp1; 5164 bool Invert = false; 5165 bool Swap = false; 5166 unsigned Opc = 0; 5167 5168 SDValue Op0 = Op.getOperand(0); 5169 SDValue Op1 = Op.getOperand(1); 5170 SDValue CC = Op.getOperand(2); 5171 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5172 EVT VT = Op.getValueType(); 5173 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5174 SDLoc dl(Op); 5175 5176 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5177 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5178 // Special-case integer 64-bit equality comparisons. They aren't legal, 5179 // but they can be lowered with a few vector instructions. 5180 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5181 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5182 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5183 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5184 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5185 DAG.getCondCode(ISD::SETEQ)); 5186 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5187 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5188 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5189 if (SetCCOpcode == ISD::SETNE) 5190 Merged = DAG.getNOT(dl, Merged, CmpVT); 5191 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5192 return Merged; 5193 } 5194 5195 if (CmpVT.getVectorElementType() == MVT::i64) 5196 // 64-bit comparisons are not legal in general. 5197 return SDValue(); 5198 5199 if (Op1.getValueType().isFloatingPoint()) { 5200 switch (SetCCOpcode) { 5201 default: llvm_unreachable("Illegal FP comparison"); 5202 case ISD::SETUNE: 5203 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5204 case ISD::SETOEQ: 5205 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5206 case ISD::SETOLT: 5207 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5208 case ISD::SETOGT: 5209 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5210 case ISD::SETOLE: 5211 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5212 case ISD::SETOGE: 5213 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5214 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5215 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5216 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5217 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5218 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5219 case ISD::SETONE: 5220 // Expand this to (OLT | OGT). 5221 TmpOp0 = Op0; 5222 TmpOp1 = Op1; 5223 Opc = ISD::OR; 5224 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5225 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5226 break; 5227 case ISD::SETUO: 5228 Invert = true; 5229 LLVM_FALLTHROUGH; 5230 case ISD::SETO: 5231 // Expand this to (OLT | OGE). 5232 TmpOp0 = Op0; 5233 TmpOp1 = Op1; 5234 Opc = ISD::OR; 5235 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5236 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5237 break; 5238 } 5239 } else { 5240 // Integer comparisons. 5241 switch (SetCCOpcode) { 5242 default: llvm_unreachable("Illegal integer comparison"); 5243 case ISD::SETNE: Invert = true; 5244 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5245 case ISD::SETLT: Swap = true; 5246 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5247 case ISD::SETLE: Swap = true; 5248 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5249 case ISD::SETULT: Swap = true; 5250 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5251 case ISD::SETULE: Swap = true; 5252 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5253 } 5254 5255 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5256 if (Opc == ARMISD::VCEQ) { 5257 5258 SDValue AndOp; 5259 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5260 AndOp = Op0; 5261 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5262 AndOp = Op1; 5263 5264 // Ignore bitconvert. 5265 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5266 AndOp = AndOp.getOperand(0); 5267 5268 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5269 Opc = ARMISD::VTST; 5270 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5271 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5272 Invert = !Invert; 5273 } 5274 } 5275 } 5276 5277 if (Swap) 5278 std::swap(Op0, Op1); 5279 5280 // If one of the operands is a constant vector zero, attempt to fold the 5281 // comparison to a specialized compare-against-zero form. 5282 SDValue SingleOp; 5283 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5284 SingleOp = Op0; 5285 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5286 if (Opc == ARMISD::VCGE) 5287 Opc = ARMISD::VCLEZ; 5288 else if (Opc == ARMISD::VCGT) 5289 Opc = ARMISD::VCLTZ; 5290 SingleOp = Op1; 5291 } 5292 5293 SDValue Result; 5294 if (SingleOp.getNode()) { 5295 switch (Opc) { 5296 case ARMISD::VCEQ: 5297 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5298 case ARMISD::VCGE: 5299 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5300 case ARMISD::VCLEZ: 5301 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5302 case ARMISD::VCGT: 5303 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5304 case ARMISD::VCLTZ: 5305 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5306 default: 5307 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5308 } 5309 } else { 5310 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5311 } 5312 5313 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5314 5315 if (Invert) 5316 Result = DAG.getNOT(dl, Result, VT); 5317 5318 return Result; 5319 } 5320 5321 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5322 SDValue LHS = Op.getOperand(0); 5323 SDValue RHS = Op.getOperand(1); 5324 SDValue Carry = Op.getOperand(2); 5325 SDValue Cond = Op.getOperand(3); 5326 SDLoc DL(Op); 5327 5328 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5329 5330 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5331 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5332 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5333 5334 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5335 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5336 SDValue ARMcc = DAG.getConstant( 5337 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5338 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5339 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5340 Cmp.getValue(1), SDValue()); 5341 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5342 CCR, Chain.getValue(1)); 5343 } 5344 5345 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5346 /// valid vector constant for a NEON instruction with a "modified immediate" 5347 /// operand (e.g., VMOV). If so, return the encoded value. 5348 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5349 unsigned SplatBitSize, SelectionDAG &DAG, 5350 const SDLoc &dl, EVT &VT, bool is128Bits, 5351 NEONModImmType type) { 5352 unsigned OpCmode, Imm; 5353 5354 // SplatBitSize is set to the smallest size that splats the vector, so a 5355 // zero vector will always have SplatBitSize == 8. However, NEON modified 5356 // immediate instructions others than VMOV do not support the 8-bit encoding 5357 // of a zero vector, and the default encoding of zero is supposed to be the 5358 // 32-bit version. 5359 if (SplatBits == 0) 5360 SplatBitSize = 32; 5361 5362 switch (SplatBitSize) { 5363 case 8: 5364 if (type != VMOVModImm) 5365 return SDValue(); 5366 // Any 1-byte value is OK. Op=0, Cmode=1110. 5367 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5368 OpCmode = 0xe; 5369 Imm = SplatBits; 5370 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5371 break; 5372 5373 case 16: 5374 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5375 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5376 if ((SplatBits & ~0xff) == 0) { 5377 // Value = 0x00nn: Op=x, Cmode=100x. 5378 OpCmode = 0x8; 5379 Imm = SplatBits; 5380 break; 5381 } 5382 if ((SplatBits & ~0xff00) == 0) { 5383 // Value = 0xnn00: Op=x, Cmode=101x. 5384 OpCmode = 0xa; 5385 Imm = SplatBits >> 8; 5386 break; 5387 } 5388 return SDValue(); 5389 5390 case 32: 5391 // NEON's 32-bit VMOV supports splat values where: 5392 // * only one byte is nonzero, or 5393 // * the least significant byte is 0xff and the second byte is nonzero, or 5394 // * the least significant 2 bytes are 0xff and the third is nonzero. 5395 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5396 if ((SplatBits & ~0xff) == 0) { 5397 // Value = 0x000000nn: Op=x, Cmode=000x. 5398 OpCmode = 0; 5399 Imm = SplatBits; 5400 break; 5401 } 5402 if ((SplatBits & ~0xff00) == 0) { 5403 // Value = 0x0000nn00: Op=x, Cmode=001x. 5404 OpCmode = 0x2; 5405 Imm = SplatBits >> 8; 5406 break; 5407 } 5408 if ((SplatBits & ~0xff0000) == 0) { 5409 // Value = 0x00nn0000: Op=x, Cmode=010x. 5410 OpCmode = 0x4; 5411 Imm = SplatBits >> 16; 5412 break; 5413 } 5414 if ((SplatBits & ~0xff000000) == 0) { 5415 // Value = 0xnn000000: Op=x, Cmode=011x. 5416 OpCmode = 0x6; 5417 Imm = SplatBits >> 24; 5418 break; 5419 } 5420 5421 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5422 if (type == OtherModImm) return SDValue(); 5423 5424 if ((SplatBits & ~0xffff) == 0 && 5425 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5426 // Value = 0x0000nnff: Op=x, Cmode=1100. 5427 OpCmode = 0xc; 5428 Imm = SplatBits >> 8; 5429 break; 5430 } 5431 5432 if ((SplatBits & ~0xffffff) == 0 && 5433 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5434 // Value = 0x00nnffff: Op=x, Cmode=1101. 5435 OpCmode = 0xd; 5436 Imm = SplatBits >> 16; 5437 break; 5438 } 5439 5440 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5441 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5442 // VMOV.I32. A (very) minor optimization would be to replicate the value 5443 // and fall through here to test for a valid 64-bit splat. But, then the 5444 // caller would also need to check and handle the change in size. 5445 return SDValue(); 5446 5447 case 64: { 5448 if (type != VMOVModImm) 5449 return SDValue(); 5450 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5451 uint64_t BitMask = 0xff; 5452 uint64_t Val = 0; 5453 unsigned ImmMask = 1; 5454 Imm = 0; 5455 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5456 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5457 Val |= BitMask; 5458 Imm |= ImmMask; 5459 } else if ((SplatBits & BitMask) != 0) { 5460 return SDValue(); 5461 } 5462 BitMask <<= 8; 5463 ImmMask <<= 1; 5464 } 5465 5466 if (DAG.getDataLayout().isBigEndian()) 5467 // swap higher and lower 32 bit word 5468 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5469 5470 // Op=1, Cmode=1110. 5471 OpCmode = 0x1e; 5472 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5473 break; 5474 } 5475 5476 default: 5477 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5478 } 5479 5480 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5481 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5482 } 5483 5484 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5485 const ARMSubtarget *ST) const { 5486 bool IsDouble = Op.getValueType() == MVT::f64; 5487 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5488 const APFloat &FPVal = CFP->getValueAPF(); 5489 5490 // Prevent floating-point constants from using literal loads 5491 // when execute-only is enabled. 5492 if (ST->genExecuteOnly()) { 5493 APInt INTVal = FPVal.bitcastToAPInt(); 5494 SDLoc DL(CFP); 5495 if (IsDouble) { 5496 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5497 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5498 if (!ST->isLittle()) 5499 std::swap(Lo, Hi); 5500 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5501 } else { 5502 return DAG.getConstant(INTVal, DL, MVT::i32); 5503 } 5504 } 5505 5506 if (!ST->hasVFP3()) 5507 return SDValue(); 5508 5509 // Use the default (constant pool) lowering for double constants when we have 5510 // an SP-only FPU 5511 if (IsDouble && Subtarget->isFPOnlySP()) 5512 return SDValue(); 5513 5514 // Try splatting with a VMOV.f32... 5515 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5516 5517 if (ImmVal != -1) { 5518 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5519 // We have code in place to select a valid ConstantFP already, no need to 5520 // do any mangling. 5521 return Op; 5522 } 5523 5524 // It's a float and we are trying to use NEON operations where 5525 // possible. Lower it to a splat followed by an extract. 5526 SDLoc DL(Op); 5527 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5528 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5529 NewVal); 5530 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5531 DAG.getConstant(0, DL, MVT::i32)); 5532 } 5533 5534 // The rest of our options are NEON only, make sure that's allowed before 5535 // proceeding.. 5536 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5537 return SDValue(); 5538 5539 EVT VMovVT; 5540 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5541 5542 // It wouldn't really be worth bothering for doubles except for one very 5543 // important value, which does happen to match: 0.0. So make sure we don't do 5544 // anything stupid. 5545 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5546 return SDValue(); 5547 5548 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5549 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5550 VMovVT, false, VMOVModImm); 5551 if (NewVal != SDValue()) { 5552 SDLoc DL(Op); 5553 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5554 NewVal); 5555 if (IsDouble) 5556 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5557 5558 // It's a float: cast and extract a vector element. 5559 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5560 VecConstant); 5561 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5562 DAG.getConstant(0, DL, MVT::i32)); 5563 } 5564 5565 // Finally, try a VMVN.i32 5566 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5567 false, VMVNModImm); 5568 if (NewVal != SDValue()) { 5569 SDLoc DL(Op); 5570 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5571 5572 if (IsDouble) 5573 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5574 5575 // It's a float: cast and extract a vector element. 5576 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5577 VecConstant); 5578 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5579 DAG.getConstant(0, DL, MVT::i32)); 5580 } 5581 5582 return SDValue(); 5583 } 5584 5585 // check if an VEXT instruction can handle the shuffle mask when the 5586 // vector sources of the shuffle are the same. 5587 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5588 unsigned NumElts = VT.getVectorNumElements(); 5589 5590 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5591 if (M[0] < 0) 5592 return false; 5593 5594 Imm = M[0]; 5595 5596 // If this is a VEXT shuffle, the immediate value is the index of the first 5597 // element. The other shuffle indices must be the successive elements after 5598 // the first one. 5599 unsigned ExpectedElt = Imm; 5600 for (unsigned i = 1; i < NumElts; ++i) { 5601 // Increment the expected index. If it wraps around, just follow it 5602 // back to index zero and keep going. 5603 ++ExpectedElt; 5604 if (ExpectedElt == NumElts) 5605 ExpectedElt = 0; 5606 5607 if (M[i] < 0) continue; // ignore UNDEF indices 5608 if (ExpectedElt != static_cast<unsigned>(M[i])) 5609 return false; 5610 } 5611 5612 return true; 5613 } 5614 5615 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5616 bool &ReverseVEXT, unsigned &Imm) { 5617 unsigned NumElts = VT.getVectorNumElements(); 5618 ReverseVEXT = false; 5619 5620 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5621 if (M[0] < 0) 5622 return false; 5623 5624 Imm = M[0]; 5625 5626 // If this is a VEXT shuffle, the immediate value is the index of the first 5627 // element. The other shuffle indices must be the successive elements after 5628 // the first one. 5629 unsigned ExpectedElt = Imm; 5630 for (unsigned i = 1; i < NumElts; ++i) { 5631 // Increment the expected index. If it wraps around, it may still be 5632 // a VEXT but the source vectors must be swapped. 5633 ExpectedElt += 1; 5634 if (ExpectedElt == NumElts * 2) { 5635 ExpectedElt = 0; 5636 ReverseVEXT = true; 5637 } 5638 5639 if (M[i] < 0) continue; // ignore UNDEF indices 5640 if (ExpectedElt != static_cast<unsigned>(M[i])) 5641 return false; 5642 } 5643 5644 // Adjust the index value if the source operands will be swapped. 5645 if (ReverseVEXT) 5646 Imm -= NumElts; 5647 5648 return true; 5649 } 5650 5651 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5652 /// instruction with the specified blocksize. (The order of the elements 5653 /// within each block of the vector is reversed.) 5654 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5655 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5656 "Only possible block sizes for VREV are: 16, 32, 64"); 5657 5658 unsigned EltSz = VT.getScalarSizeInBits(); 5659 if (EltSz == 64) 5660 return false; 5661 5662 unsigned NumElts = VT.getVectorNumElements(); 5663 unsigned BlockElts = M[0] + 1; 5664 // If the first shuffle index is UNDEF, be optimistic. 5665 if (M[0] < 0) 5666 BlockElts = BlockSize / EltSz; 5667 5668 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5669 return false; 5670 5671 for (unsigned i = 0; i < NumElts; ++i) { 5672 if (M[i] < 0) continue; // ignore UNDEF indices 5673 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5674 return false; 5675 } 5676 5677 return true; 5678 } 5679 5680 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5681 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5682 // range, then 0 is placed into the resulting vector. So pretty much any mask 5683 // of 8 elements can work here. 5684 return VT == MVT::v8i8 && M.size() == 8; 5685 } 5686 5687 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5688 // checking that pairs of elements in the shuffle mask represent the same index 5689 // in each vector, incrementing the expected index by 2 at each step. 5690 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5691 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5692 // v2={e,f,g,h} 5693 // WhichResult gives the offset for each element in the mask based on which 5694 // of the two results it belongs to. 5695 // 5696 // The transpose can be represented either as: 5697 // result1 = shufflevector v1, v2, result1_shuffle_mask 5698 // result2 = shufflevector v1, v2, result2_shuffle_mask 5699 // where v1/v2 and the shuffle masks have the same number of elements 5700 // (here WhichResult (see below) indicates which result is being checked) 5701 // 5702 // or as: 5703 // results = shufflevector v1, v2, shuffle_mask 5704 // where both results are returned in one vector and the shuffle mask has twice 5705 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5706 // want to check the low half and high half of the shuffle mask as if it were 5707 // the other case 5708 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5709 unsigned EltSz = VT.getScalarSizeInBits(); 5710 if (EltSz == 64) 5711 return false; 5712 5713 unsigned NumElts = VT.getVectorNumElements(); 5714 if (M.size() != NumElts && M.size() != NumElts*2) 5715 return false; 5716 5717 // If the mask is twice as long as the input vector then we need to check the 5718 // upper and lower parts of the mask with a matching value for WhichResult 5719 // FIXME: A mask with only even values will be rejected in case the first 5720 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5721 // M[0] is used to determine WhichResult 5722 for (unsigned i = 0; i < M.size(); i += NumElts) { 5723 if (M.size() == NumElts * 2) 5724 WhichResult = i / NumElts; 5725 else 5726 WhichResult = M[i] == 0 ? 0 : 1; 5727 for (unsigned j = 0; j < NumElts; j += 2) { 5728 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5729 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5730 return false; 5731 } 5732 } 5733 5734 if (M.size() == NumElts*2) 5735 WhichResult = 0; 5736 5737 return true; 5738 } 5739 5740 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5741 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5742 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5743 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5744 unsigned EltSz = VT.getScalarSizeInBits(); 5745 if (EltSz == 64) 5746 return false; 5747 5748 unsigned NumElts = VT.getVectorNumElements(); 5749 if (M.size() != NumElts && M.size() != NumElts*2) 5750 return false; 5751 5752 for (unsigned i = 0; i < M.size(); i += NumElts) { 5753 if (M.size() == NumElts * 2) 5754 WhichResult = i / NumElts; 5755 else 5756 WhichResult = M[i] == 0 ? 0 : 1; 5757 for (unsigned j = 0; j < NumElts; j += 2) { 5758 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5759 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5760 return false; 5761 } 5762 } 5763 5764 if (M.size() == NumElts*2) 5765 WhichResult = 0; 5766 5767 return true; 5768 } 5769 5770 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5771 // that the mask elements are either all even and in steps of size 2 or all odd 5772 // and in steps of size 2. 5773 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5774 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5775 // v2={e,f,g,h} 5776 // Requires similar checks to that of isVTRNMask with 5777 // respect the how results are returned. 5778 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5779 unsigned EltSz = VT.getScalarSizeInBits(); 5780 if (EltSz == 64) 5781 return false; 5782 5783 unsigned NumElts = VT.getVectorNumElements(); 5784 if (M.size() != NumElts && M.size() != NumElts*2) 5785 return false; 5786 5787 for (unsigned i = 0; i < M.size(); i += NumElts) { 5788 WhichResult = M[i] == 0 ? 0 : 1; 5789 for (unsigned j = 0; j < NumElts; ++j) { 5790 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5791 return false; 5792 } 5793 } 5794 5795 if (M.size() == NumElts*2) 5796 WhichResult = 0; 5797 5798 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5799 if (VT.is64BitVector() && EltSz == 32) 5800 return false; 5801 5802 return true; 5803 } 5804 5805 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5806 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5807 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5808 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5809 unsigned EltSz = VT.getScalarSizeInBits(); 5810 if (EltSz == 64) 5811 return false; 5812 5813 unsigned NumElts = VT.getVectorNumElements(); 5814 if (M.size() != NumElts && M.size() != NumElts*2) 5815 return false; 5816 5817 unsigned Half = NumElts / 2; 5818 for (unsigned i = 0; i < M.size(); i += NumElts) { 5819 WhichResult = M[i] == 0 ? 0 : 1; 5820 for (unsigned j = 0; j < NumElts; j += Half) { 5821 unsigned Idx = WhichResult; 5822 for (unsigned k = 0; k < Half; ++k) { 5823 int MIdx = M[i + j + k]; 5824 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5825 return false; 5826 Idx += 2; 5827 } 5828 } 5829 } 5830 5831 if (M.size() == NumElts*2) 5832 WhichResult = 0; 5833 5834 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5835 if (VT.is64BitVector() && EltSz == 32) 5836 return false; 5837 5838 return true; 5839 } 5840 5841 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5842 // that pairs of elements of the shufflemask represent the same index in each 5843 // vector incrementing sequentially through the vectors. 5844 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5845 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5846 // v2={e,f,g,h} 5847 // Requires similar checks to that of isVTRNMask with respect the how results 5848 // are returned. 5849 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5850 unsigned EltSz = VT.getScalarSizeInBits(); 5851 if (EltSz == 64) 5852 return false; 5853 5854 unsigned NumElts = VT.getVectorNumElements(); 5855 if (M.size() != NumElts && M.size() != NumElts*2) 5856 return false; 5857 5858 for (unsigned i = 0; i < M.size(); i += NumElts) { 5859 WhichResult = M[i] == 0 ? 0 : 1; 5860 unsigned Idx = WhichResult * NumElts / 2; 5861 for (unsigned j = 0; j < NumElts; j += 2) { 5862 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5863 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5864 return false; 5865 Idx += 1; 5866 } 5867 } 5868 5869 if (M.size() == NumElts*2) 5870 WhichResult = 0; 5871 5872 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5873 if (VT.is64BitVector() && EltSz == 32) 5874 return false; 5875 5876 return true; 5877 } 5878 5879 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5880 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5881 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5882 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5883 unsigned EltSz = VT.getScalarSizeInBits(); 5884 if (EltSz == 64) 5885 return false; 5886 5887 unsigned NumElts = VT.getVectorNumElements(); 5888 if (M.size() != NumElts && M.size() != NumElts*2) 5889 return false; 5890 5891 for (unsigned i = 0; i < M.size(); i += NumElts) { 5892 WhichResult = M[i] == 0 ? 0 : 1; 5893 unsigned Idx = WhichResult * NumElts / 2; 5894 for (unsigned j = 0; j < NumElts; j += 2) { 5895 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5896 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5897 return false; 5898 Idx += 1; 5899 } 5900 } 5901 5902 if (M.size() == NumElts*2) 5903 WhichResult = 0; 5904 5905 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5906 if (VT.is64BitVector() && EltSz == 32) 5907 return false; 5908 5909 return true; 5910 } 5911 5912 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5913 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5914 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5915 unsigned &WhichResult, 5916 bool &isV_UNDEF) { 5917 isV_UNDEF = false; 5918 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5919 return ARMISD::VTRN; 5920 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5921 return ARMISD::VUZP; 5922 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5923 return ARMISD::VZIP; 5924 5925 isV_UNDEF = true; 5926 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5927 return ARMISD::VTRN; 5928 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5929 return ARMISD::VUZP; 5930 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5931 return ARMISD::VZIP; 5932 5933 return 0; 5934 } 5935 5936 /// \return true if this is a reverse operation on an vector. 5937 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5938 unsigned NumElts = VT.getVectorNumElements(); 5939 // Make sure the mask has the right size. 5940 if (NumElts != M.size()) 5941 return false; 5942 5943 // Look for <15, ..., 3, -1, 1, 0>. 5944 for (unsigned i = 0; i != NumElts; ++i) 5945 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5946 return false; 5947 5948 return true; 5949 } 5950 5951 // If N is an integer constant that can be moved into a register in one 5952 // instruction, return an SDValue of such a constant (will become a MOV 5953 // instruction). Otherwise return null. 5954 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5955 const ARMSubtarget *ST, const SDLoc &dl) { 5956 uint64_t Val; 5957 if (!isa<ConstantSDNode>(N)) 5958 return SDValue(); 5959 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5960 5961 if (ST->isThumb1Only()) { 5962 if (Val <= 255 || ~Val <= 255) 5963 return DAG.getConstant(Val, dl, MVT::i32); 5964 } else { 5965 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5966 return DAG.getConstant(Val, dl, MVT::i32); 5967 } 5968 return SDValue(); 5969 } 5970 5971 // If this is a case we can't handle, return null and let the default 5972 // expansion code take care of it. 5973 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 5974 const ARMSubtarget *ST) const { 5975 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 5976 SDLoc dl(Op); 5977 EVT VT = Op.getValueType(); 5978 5979 APInt SplatBits, SplatUndef; 5980 unsigned SplatBitSize; 5981 bool HasAnyUndefs; 5982 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5983 if (SplatUndef.isAllOnesValue()) 5984 return DAG.getUNDEF(VT); 5985 5986 if (SplatBitSize <= 64) { 5987 // Check if an immediate VMOV works. 5988 EVT VmovVT; 5989 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 5990 SplatUndef.getZExtValue(), SplatBitSize, 5991 DAG, dl, VmovVT, VT.is128BitVector(), 5992 VMOVModImm); 5993 if (Val.getNode()) { 5994 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 5995 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5996 } 5997 5998 // Try an immediate VMVN. 5999 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6000 Val = isNEONModifiedImm(NegatedImm, 6001 SplatUndef.getZExtValue(), SplatBitSize, 6002 DAG, dl, VmovVT, VT.is128BitVector(), 6003 VMVNModImm); 6004 if (Val.getNode()) { 6005 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6006 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6007 } 6008 6009 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6010 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6011 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6012 if (ImmVal != -1) { 6013 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6014 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6015 } 6016 } 6017 } 6018 } 6019 6020 // Scan through the operands to see if only one value is used. 6021 // 6022 // As an optimisation, even if more than one value is used it may be more 6023 // profitable to splat with one value then change some lanes. 6024 // 6025 // Heuristically we decide to do this if the vector has a "dominant" value, 6026 // defined as splatted to more than half of the lanes. 6027 unsigned NumElts = VT.getVectorNumElements(); 6028 bool isOnlyLowElement = true; 6029 bool usesOnlyOneValue = true; 6030 bool hasDominantValue = false; 6031 bool isConstant = true; 6032 6033 // Map of the number of times a particular SDValue appears in the 6034 // element list. 6035 DenseMap<SDValue, unsigned> ValueCounts; 6036 SDValue Value; 6037 for (unsigned i = 0; i < NumElts; ++i) { 6038 SDValue V = Op.getOperand(i); 6039 if (V.isUndef()) 6040 continue; 6041 if (i > 0) 6042 isOnlyLowElement = false; 6043 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6044 isConstant = false; 6045 6046 ValueCounts.insert(std::make_pair(V, 0)); 6047 unsigned &Count = ValueCounts[V]; 6048 6049 // Is this value dominant? (takes up more than half of the lanes) 6050 if (++Count > (NumElts / 2)) { 6051 hasDominantValue = true; 6052 Value = V; 6053 } 6054 } 6055 if (ValueCounts.size() != 1) 6056 usesOnlyOneValue = false; 6057 if (!Value.getNode() && !ValueCounts.empty()) 6058 Value = ValueCounts.begin()->first; 6059 6060 if (ValueCounts.empty()) 6061 return DAG.getUNDEF(VT); 6062 6063 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6064 // Keep going if we are hitting this case. 6065 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6066 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6067 6068 unsigned EltSize = VT.getScalarSizeInBits(); 6069 6070 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6071 // i32 and try again. 6072 if (hasDominantValue && EltSize <= 32) { 6073 if (!isConstant) { 6074 SDValue N; 6075 6076 // If we are VDUPing a value that comes directly from a vector, that will 6077 // cause an unnecessary move to and from a GPR, where instead we could 6078 // just use VDUPLANE. We can only do this if the lane being extracted 6079 // is at a constant index, as the VDUP from lane instructions only have 6080 // constant-index forms. 6081 ConstantSDNode *constIndex; 6082 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6083 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6084 // We need to create a new undef vector to use for the VDUPLANE if the 6085 // size of the vector from which we get the value is different than the 6086 // size of the vector that we need to create. We will insert the element 6087 // such that the register coalescer will remove unnecessary copies. 6088 if (VT != Value->getOperand(0).getValueType()) { 6089 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6090 VT.getVectorNumElements(); 6091 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6092 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6093 Value, DAG.getConstant(index, dl, MVT::i32)), 6094 DAG.getConstant(index, dl, MVT::i32)); 6095 } else 6096 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6097 Value->getOperand(0), Value->getOperand(1)); 6098 } else 6099 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6100 6101 if (!usesOnlyOneValue) { 6102 // The dominant value was splatted as 'N', but we now have to insert 6103 // all differing elements. 6104 for (unsigned I = 0; I < NumElts; ++I) { 6105 if (Op.getOperand(I) == Value) 6106 continue; 6107 SmallVector<SDValue, 3> Ops; 6108 Ops.push_back(N); 6109 Ops.push_back(Op.getOperand(I)); 6110 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6111 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6112 } 6113 } 6114 return N; 6115 } 6116 if (VT.getVectorElementType().isFloatingPoint()) { 6117 SmallVector<SDValue, 8> Ops; 6118 for (unsigned i = 0; i < NumElts; ++i) 6119 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6120 Op.getOperand(i))); 6121 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6122 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6123 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6124 if (Val.getNode()) 6125 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6126 } 6127 if (usesOnlyOneValue) { 6128 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6129 if (isConstant && Val.getNode()) 6130 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6131 } 6132 } 6133 6134 // If all elements are constants and the case above didn't get hit, fall back 6135 // to the default expansion, which will generate a load from the constant 6136 // pool. 6137 if (isConstant) 6138 return SDValue(); 6139 6140 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6141 if (NumElts >= 4) { 6142 SDValue shuffle = ReconstructShuffle(Op, DAG); 6143 if (shuffle != SDValue()) 6144 return shuffle; 6145 } 6146 6147 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6148 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6149 // into two 64-bit vectors; we might discover a better way to lower it. 6150 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6151 EVT ExtVT = VT.getVectorElementType(); 6152 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6153 SDValue Lower = 6154 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6155 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6156 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6157 SDValue Upper = DAG.getBuildVector( 6158 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6159 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6160 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6161 if (Lower && Upper) 6162 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6163 } 6164 6165 // Vectors with 32- or 64-bit elements can be built by directly assigning 6166 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6167 // will be legalized. 6168 if (EltSize >= 32) { 6169 // Do the expansion with floating-point types, since that is what the VFP 6170 // registers are defined to use, and since i64 is not legal. 6171 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6172 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6173 SmallVector<SDValue, 8> Ops; 6174 for (unsigned i = 0; i < NumElts; ++i) 6175 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6176 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6177 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6178 } 6179 6180 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6181 // know the default expansion would otherwise fall back on something even 6182 // worse. For a vector with one or two non-undef values, that's 6183 // scalar_to_vector for the elements followed by a shuffle (provided the 6184 // shuffle is valid for the target) and materialization element by element 6185 // on the stack followed by a load for everything else. 6186 if (!isConstant && !usesOnlyOneValue) { 6187 SDValue Vec = DAG.getUNDEF(VT); 6188 for (unsigned i = 0 ; i < NumElts; ++i) { 6189 SDValue V = Op.getOperand(i); 6190 if (V.isUndef()) 6191 continue; 6192 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6193 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6194 } 6195 return Vec; 6196 } 6197 6198 return SDValue(); 6199 } 6200 6201 // Gather data to see if the operation can be modelled as a 6202 // shuffle in combination with VEXTs. 6203 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6204 SelectionDAG &DAG) const { 6205 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6206 SDLoc dl(Op); 6207 EVT VT = Op.getValueType(); 6208 unsigned NumElts = VT.getVectorNumElements(); 6209 6210 struct ShuffleSourceInfo { 6211 SDValue Vec; 6212 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6213 unsigned MaxElt = 0; 6214 6215 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6216 // be compatible with the shuffle we intend to construct. As a result 6217 // ShuffleVec will be some sliding window into the original Vec. 6218 SDValue ShuffleVec; 6219 6220 // Code should guarantee that element i in Vec starts at element "WindowBase 6221 // + i * WindowScale in ShuffleVec". 6222 int WindowBase = 0; 6223 int WindowScale = 1; 6224 6225 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6226 6227 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6228 }; 6229 6230 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6231 // node. 6232 SmallVector<ShuffleSourceInfo, 2> Sources; 6233 for (unsigned i = 0; i < NumElts; ++i) { 6234 SDValue V = Op.getOperand(i); 6235 if (V.isUndef()) 6236 continue; 6237 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6238 // A shuffle can only come from building a vector from various 6239 // elements of other vectors. 6240 return SDValue(); 6241 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6242 // Furthermore, shuffles require a constant mask, whereas extractelts 6243 // accept variable indices. 6244 return SDValue(); 6245 } 6246 6247 // Add this element source to the list if it's not already there. 6248 SDValue SourceVec = V.getOperand(0); 6249 auto Source = llvm::find(Sources, SourceVec); 6250 if (Source == Sources.end()) 6251 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6252 6253 // Update the minimum and maximum lane number seen. 6254 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6255 Source->MinElt = std::min(Source->MinElt, EltNo); 6256 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6257 } 6258 6259 // Currently only do something sane when at most two source vectors 6260 // are involved. 6261 if (Sources.size() > 2) 6262 return SDValue(); 6263 6264 // Find out the smallest element size among result and two sources, and use 6265 // it as element size to build the shuffle_vector. 6266 EVT SmallestEltTy = VT.getVectorElementType(); 6267 for (auto &Source : Sources) { 6268 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6269 if (SrcEltTy.bitsLT(SmallestEltTy)) 6270 SmallestEltTy = SrcEltTy; 6271 } 6272 unsigned ResMultiplier = 6273 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6274 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6275 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6276 6277 // If the source vector is too wide or too narrow, we may nevertheless be able 6278 // to construct a compatible shuffle either by concatenating it with UNDEF or 6279 // extracting a suitable range of elements. 6280 for (auto &Src : Sources) { 6281 EVT SrcVT = Src.ShuffleVec.getValueType(); 6282 6283 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6284 continue; 6285 6286 // This stage of the search produces a source with the same element type as 6287 // the original, but with a total width matching the BUILD_VECTOR output. 6288 EVT EltVT = SrcVT.getVectorElementType(); 6289 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6290 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6291 6292 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6293 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6294 return SDValue(); 6295 // We can pad out the smaller vector for free, so if it's part of a 6296 // shuffle... 6297 Src.ShuffleVec = 6298 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6299 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6300 continue; 6301 } 6302 6303 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6304 return SDValue(); 6305 6306 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6307 // Span too large for a VEXT to cope 6308 return SDValue(); 6309 } 6310 6311 if (Src.MinElt >= NumSrcElts) { 6312 // The extraction can just take the second half 6313 Src.ShuffleVec = 6314 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6315 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6316 Src.WindowBase = -NumSrcElts; 6317 } else if (Src.MaxElt < NumSrcElts) { 6318 // The extraction can just take the first half 6319 Src.ShuffleVec = 6320 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6321 DAG.getConstant(0, dl, MVT::i32)); 6322 } else { 6323 // An actual VEXT is needed 6324 SDValue VEXTSrc1 = 6325 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6326 DAG.getConstant(0, dl, MVT::i32)); 6327 SDValue VEXTSrc2 = 6328 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6329 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6330 6331 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6332 VEXTSrc2, 6333 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6334 Src.WindowBase = -Src.MinElt; 6335 } 6336 } 6337 6338 // Another possible incompatibility occurs from the vector element types. We 6339 // can fix this by bitcasting the source vectors to the same type we intend 6340 // for the shuffle. 6341 for (auto &Src : Sources) { 6342 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6343 if (SrcEltTy == SmallestEltTy) 6344 continue; 6345 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6346 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6347 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6348 Src.WindowBase *= Src.WindowScale; 6349 } 6350 6351 // Final sanity check before we try to actually produce a shuffle. 6352 DEBUG( 6353 for (auto Src : Sources) 6354 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6355 ); 6356 6357 // The stars all align, our next step is to produce the mask for the shuffle. 6358 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6359 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6360 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6361 SDValue Entry = Op.getOperand(i); 6362 if (Entry.isUndef()) 6363 continue; 6364 6365 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6366 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6367 6368 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6369 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6370 // segment. 6371 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6372 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6373 VT.getScalarSizeInBits()); 6374 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6375 6376 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6377 // starting at the appropriate offset. 6378 int *LaneMask = &Mask[i * ResMultiplier]; 6379 6380 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6381 ExtractBase += NumElts * (Src - Sources.begin()); 6382 for (int j = 0; j < LanesDefined; ++j) 6383 LaneMask[j] = ExtractBase + j; 6384 } 6385 6386 // Final check before we try to produce nonsense... 6387 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6388 return SDValue(); 6389 6390 // We can't handle more than two sources. This should have already 6391 // been checked before this point. 6392 assert(Sources.size() <= 2 && "Too many sources!"); 6393 6394 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6395 for (unsigned i = 0; i < Sources.size(); ++i) 6396 ShuffleOps[i] = Sources[i].ShuffleVec; 6397 6398 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6399 ShuffleOps[1], Mask); 6400 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6401 } 6402 6403 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6404 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6405 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6406 /// are assumed to be legal. 6407 bool 6408 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6409 EVT VT) const { 6410 if (VT.getVectorNumElements() == 4 && 6411 (VT.is128BitVector() || VT.is64BitVector())) { 6412 unsigned PFIndexes[4]; 6413 for (unsigned i = 0; i != 4; ++i) { 6414 if (M[i] < 0) 6415 PFIndexes[i] = 8; 6416 else 6417 PFIndexes[i] = M[i]; 6418 } 6419 6420 // Compute the index in the perfect shuffle table. 6421 unsigned PFTableIndex = 6422 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6423 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6424 unsigned Cost = (PFEntry >> 30); 6425 6426 if (Cost <= 4) 6427 return true; 6428 } 6429 6430 bool ReverseVEXT, isV_UNDEF; 6431 unsigned Imm, WhichResult; 6432 6433 unsigned EltSize = VT.getScalarSizeInBits(); 6434 return (EltSize >= 32 || 6435 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6436 isVREVMask(M, VT, 64) || 6437 isVREVMask(M, VT, 32) || 6438 isVREVMask(M, VT, 16) || 6439 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6440 isVTBLMask(M, VT) || 6441 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6442 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6443 } 6444 6445 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6446 /// the specified operations to build the shuffle. 6447 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6448 SDValue RHS, SelectionDAG &DAG, 6449 const SDLoc &dl) { 6450 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6451 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6452 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6453 6454 enum { 6455 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6456 OP_VREV, 6457 OP_VDUP0, 6458 OP_VDUP1, 6459 OP_VDUP2, 6460 OP_VDUP3, 6461 OP_VEXT1, 6462 OP_VEXT2, 6463 OP_VEXT3, 6464 OP_VUZPL, // VUZP, left result 6465 OP_VUZPR, // VUZP, right result 6466 OP_VZIPL, // VZIP, left result 6467 OP_VZIPR, // VZIP, right result 6468 OP_VTRNL, // VTRN, left result 6469 OP_VTRNR // VTRN, right result 6470 }; 6471 6472 if (OpNum == OP_COPY) { 6473 if (LHSID == (1*9+2)*9+3) return LHS; 6474 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6475 return RHS; 6476 } 6477 6478 SDValue OpLHS, OpRHS; 6479 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6480 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6481 EVT VT = OpLHS.getValueType(); 6482 6483 switch (OpNum) { 6484 default: llvm_unreachable("Unknown shuffle opcode!"); 6485 case OP_VREV: 6486 // VREV divides the vector in half and swaps within the half. 6487 if (VT.getVectorElementType() == MVT::i32 || 6488 VT.getVectorElementType() == MVT::f32) 6489 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6490 // vrev <4 x i16> -> VREV32 6491 if (VT.getVectorElementType() == MVT::i16) 6492 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6493 // vrev <4 x i8> -> VREV16 6494 assert(VT.getVectorElementType() == MVT::i8); 6495 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6496 case OP_VDUP0: 6497 case OP_VDUP1: 6498 case OP_VDUP2: 6499 case OP_VDUP3: 6500 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6501 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6502 case OP_VEXT1: 6503 case OP_VEXT2: 6504 case OP_VEXT3: 6505 return DAG.getNode(ARMISD::VEXT, dl, VT, 6506 OpLHS, OpRHS, 6507 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6508 case OP_VUZPL: 6509 case OP_VUZPR: 6510 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6511 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6512 case OP_VZIPL: 6513 case OP_VZIPR: 6514 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6515 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6516 case OP_VTRNL: 6517 case OP_VTRNR: 6518 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6519 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6520 } 6521 } 6522 6523 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6524 ArrayRef<int> ShuffleMask, 6525 SelectionDAG &DAG) { 6526 // Check to see if we can use the VTBL instruction. 6527 SDValue V1 = Op.getOperand(0); 6528 SDValue V2 = Op.getOperand(1); 6529 SDLoc DL(Op); 6530 6531 SmallVector<SDValue, 8> VTBLMask; 6532 for (ArrayRef<int>::iterator 6533 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6534 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6535 6536 if (V2.getNode()->isUndef()) 6537 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6538 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6539 6540 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6541 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6542 } 6543 6544 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6545 SelectionDAG &DAG) { 6546 SDLoc DL(Op); 6547 SDValue OpLHS = Op.getOperand(0); 6548 EVT VT = OpLHS.getValueType(); 6549 6550 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6551 "Expect an v8i16/v16i8 type"); 6552 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6553 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6554 // extract the first 8 bytes into the top double word and the last 8 bytes 6555 // into the bottom double word. The v8i16 case is similar. 6556 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6557 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6558 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6559 } 6560 6561 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6562 SDValue V1 = Op.getOperand(0); 6563 SDValue V2 = Op.getOperand(1); 6564 SDLoc dl(Op); 6565 EVT VT = Op.getValueType(); 6566 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6567 6568 // Convert shuffles that are directly supported on NEON to target-specific 6569 // DAG nodes, instead of keeping them as shuffles and matching them again 6570 // during code selection. This is more efficient and avoids the possibility 6571 // of inconsistencies between legalization and selection. 6572 // FIXME: floating-point vectors should be canonicalized to integer vectors 6573 // of the same time so that they get CSEd properly. 6574 ArrayRef<int> ShuffleMask = SVN->getMask(); 6575 6576 unsigned EltSize = VT.getScalarSizeInBits(); 6577 if (EltSize <= 32) { 6578 if (SVN->isSplat()) { 6579 int Lane = SVN->getSplatIndex(); 6580 // If this is undef splat, generate it via "just" vdup, if possible. 6581 if (Lane == -1) Lane = 0; 6582 6583 // Test if V1 is a SCALAR_TO_VECTOR. 6584 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6585 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6586 } 6587 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6588 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6589 // reaches it). 6590 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6591 !isa<ConstantSDNode>(V1.getOperand(0))) { 6592 bool IsScalarToVector = true; 6593 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6594 if (!V1.getOperand(i).isUndef()) { 6595 IsScalarToVector = false; 6596 break; 6597 } 6598 if (IsScalarToVector) 6599 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6600 } 6601 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6602 DAG.getConstant(Lane, dl, MVT::i32)); 6603 } 6604 6605 bool ReverseVEXT; 6606 unsigned Imm; 6607 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6608 if (ReverseVEXT) 6609 std::swap(V1, V2); 6610 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6611 DAG.getConstant(Imm, dl, MVT::i32)); 6612 } 6613 6614 if (isVREVMask(ShuffleMask, VT, 64)) 6615 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6616 if (isVREVMask(ShuffleMask, VT, 32)) 6617 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6618 if (isVREVMask(ShuffleMask, VT, 16)) 6619 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6620 6621 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6622 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6623 DAG.getConstant(Imm, dl, MVT::i32)); 6624 } 6625 6626 // Check for Neon shuffles that modify both input vectors in place. 6627 // If both results are used, i.e., if there are two shuffles with the same 6628 // source operands and with masks corresponding to both results of one of 6629 // these operations, DAG memoization will ensure that a single node is 6630 // used for both shuffles. 6631 unsigned WhichResult; 6632 bool isV_UNDEF; 6633 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6634 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6635 if (isV_UNDEF) 6636 V2 = V1; 6637 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6638 .getValue(WhichResult); 6639 } 6640 6641 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6642 // shuffles that produce a result larger than their operands with: 6643 // shuffle(concat(v1, undef), concat(v2, undef)) 6644 // -> 6645 // shuffle(concat(v1, v2), undef) 6646 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6647 // 6648 // This is useful in the general case, but there are special cases where 6649 // native shuffles produce larger results: the two-result ops. 6650 // 6651 // Look through the concat when lowering them: 6652 // shuffle(concat(v1, v2), undef) 6653 // -> 6654 // concat(VZIP(v1, v2):0, :1) 6655 // 6656 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6657 SDValue SubV1 = V1->getOperand(0); 6658 SDValue SubV2 = V1->getOperand(1); 6659 EVT SubVT = SubV1.getValueType(); 6660 6661 // We expect these to have been canonicalized to -1. 6662 assert(llvm::all_of(ShuffleMask, [&](int i) { 6663 return i < (int)VT.getVectorNumElements(); 6664 }) && "Unexpected shuffle index into UNDEF operand!"); 6665 6666 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6667 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6668 if (isV_UNDEF) 6669 SubV2 = SubV1; 6670 assert((WhichResult == 0) && 6671 "In-place shuffle of concat can only have one result!"); 6672 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6673 SubV1, SubV2); 6674 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6675 Res.getValue(1)); 6676 } 6677 } 6678 } 6679 6680 // If the shuffle is not directly supported and it has 4 elements, use 6681 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6682 unsigned NumElts = VT.getVectorNumElements(); 6683 if (NumElts == 4) { 6684 unsigned PFIndexes[4]; 6685 for (unsigned i = 0; i != 4; ++i) { 6686 if (ShuffleMask[i] < 0) 6687 PFIndexes[i] = 8; 6688 else 6689 PFIndexes[i] = ShuffleMask[i]; 6690 } 6691 6692 // Compute the index in the perfect shuffle table. 6693 unsigned PFTableIndex = 6694 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6695 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6696 unsigned Cost = (PFEntry >> 30); 6697 6698 if (Cost <= 4) 6699 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6700 } 6701 6702 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6703 if (EltSize >= 32) { 6704 // Do the expansion with floating-point types, since that is what the VFP 6705 // registers are defined to use, and since i64 is not legal. 6706 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6707 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6708 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6709 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6710 SmallVector<SDValue, 8> Ops; 6711 for (unsigned i = 0; i < NumElts; ++i) { 6712 if (ShuffleMask[i] < 0) 6713 Ops.push_back(DAG.getUNDEF(EltVT)); 6714 else 6715 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6716 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6717 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6718 dl, MVT::i32))); 6719 } 6720 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6721 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6722 } 6723 6724 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6725 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6726 6727 if (VT == MVT::v8i8) 6728 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6729 return NewOp; 6730 6731 return SDValue(); 6732 } 6733 6734 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6735 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6736 SDValue Lane = Op.getOperand(2); 6737 if (!isa<ConstantSDNode>(Lane)) 6738 return SDValue(); 6739 6740 return Op; 6741 } 6742 6743 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6744 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6745 SDValue Lane = Op.getOperand(1); 6746 if (!isa<ConstantSDNode>(Lane)) 6747 return SDValue(); 6748 6749 SDValue Vec = Op.getOperand(0); 6750 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 6751 SDLoc dl(Op); 6752 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6753 } 6754 6755 return Op; 6756 } 6757 6758 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6759 // The only time a CONCAT_VECTORS operation can have legal types is when 6760 // two 64-bit vectors are concatenated to a 128-bit vector. 6761 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6762 "unexpected CONCAT_VECTORS"); 6763 SDLoc dl(Op); 6764 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6765 SDValue Op0 = Op.getOperand(0); 6766 SDValue Op1 = Op.getOperand(1); 6767 if (!Op0.isUndef()) 6768 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6769 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6770 DAG.getIntPtrConstant(0, dl)); 6771 if (!Op1.isUndef()) 6772 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6773 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6774 DAG.getIntPtrConstant(1, dl)); 6775 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6776 } 6777 6778 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6779 /// element has been zero/sign-extended, depending on the isSigned parameter, 6780 /// from an integer type half its size. 6781 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6782 bool isSigned) { 6783 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6784 EVT VT = N->getValueType(0); 6785 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6786 SDNode *BVN = N->getOperand(0).getNode(); 6787 if (BVN->getValueType(0) != MVT::v4i32 || 6788 BVN->getOpcode() != ISD::BUILD_VECTOR) 6789 return false; 6790 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6791 unsigned HiElt = 1 - LoElt; 6792 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6793 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6794 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6795 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6796 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6797 return false; 6798 if (isSigned) { 6799 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6800 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6801 return true; 6802 } else { 6803 if (Hi0->isNullValue() && Hi1->isNullValue()) 6804 return true; 6805 } 6806 return false; 6807 } 6808 6809 if (N->getOpcode() != ISD::BUILD_VECTOR) 6810 return false; 6811 6812 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6813 SDNode *Elt = N->getOperand(i).getNode(); 6814 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6815 unsigned EltSize = VT.getScalarSizeInBits(); 6816 unsigned HalfSize = EltSize / 2; 6817 if (isSigned) { 6818 if (!isIntN(HalfSize, C->getSExtValue())) 6819 return false; 6820 } else { 6821 if (!isUIntN(HalfSize, C->getZExtValue())) 6822 return false; 6823 } 6824 continue; 6825 } 6826 return false; 6827 } 6828 6829 return true; 6830 } 6831 6832 /// isSignExtended - Check if a node is a vector value that is sign-extended 6833 /// or a constant BUILD_VECTOR with sign-extended elements. 6834 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6835 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6836 return true; 6837 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6838 return true; 6839 return false; 6840 } 6841 6842 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6843 /// or a constant BUILD_VECTOR with zero-extended elements. 6844 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6845 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6846 return true; 6847 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6848 return true; 6849 return false; 6850 } 6851 6852 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6853 if (OrigVT.getSizeInBits() >= 64) 6854 return OrigVT; 6855 6856 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6857 6858 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6859 switch (OrigSimpleTy) { 6860 default: llvm_unreachable("Unexpected Vector Type"); 6861 case MVT::v2i8: 6862 case MVT::v2i16: 6863 return MVT::v2i32; 6864 case MVT::v4i8: 6865 return MVT::v4i16; 6866 } 6867 } 6868 6869 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6870 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6871 /// We insert the required extension here to get the vector to fill a D register. 6872 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6873 const EVT &OrigTy, 6874 const EVT &ExtTy, 6875 unsigned ExtOpcode) { 6876 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6877 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6878 // 64-bits we need to insert a new extension so that it will be 64-bits. 6879 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6880 if (OrigTy.getSizeInBits() >= 64) 6881 return N; 6882 6883 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6884 EVT NewVT = getExtensionTo64Bits(OrigTy); 6885 6886 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6887 } 6888 6889 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6890 /// does not do any sign/zero extension. If the original vector is less 6891 /// than 64 bits, an appropriate extension will be added after the load to 6892 /// reach a total size of 64 bits. We have to add the extension separately 6893 /// because ARM does not have a sign/zero extending load for vectors. 6894 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6895 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6896 6897 // The load already has the right type. 6898 if (ExtendedTy == LD->getMemoryVT()) 6899 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6900 LD->getBasePtr(), LD->getPointerInfo(), 6901 LD->getAlignment(), LD->getMemOperand()->getFlags()); 6902 6903 // We need to create a zextload/sextload. We cannot just create a load 6904 // followed by a zext/zext node because LowerMUL is also run during normal 6905 // operation legalization where we can't create illegal types. 6906 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6907 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6908 LD->getMemoryVT(), LD->getAlignment(), 6909 LD->getMemOperand()->getFlags()); 6910 } 6911 6912 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6913 /// extending load, or BUILD_VECTOR with extended elements, return the 6914 /// unextended value. The unextended vector should be 64 bits so that it can 6915 /// be used as an operand to a VMULL instruction. If the original vector size 6916 /// before extension is less than 64 bits we add a an extension to resize 6917 /// the vector to 64 bits. 6918 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6919 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6920 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6921 N->getOperand(0)->getValueType(0), 6922 N->getValueType(0), 6923 N->getOpcode()); 6924 6925 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6926 return SkipLoadExtensionForVMULL(LD, DAG); 6927 6928 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6929 // have been legalized as a BITCAST from v4i32. 6930 if (N->getOpcode() == ISD::BITCAST) { 6931 SDNode *BVN = N->getOperand(0).getNode(); 6932 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6933 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6934 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6935 return DAG.getBuildVector( 6936 MVT::v2i32, SDLoc(N), 6937 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 6938 } 6939 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6940 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6941 EVT VT = N->getValueType(0); 6942 unsigned EltSize = VT.getScalarSizeInBits() / 2; 6943 unsigned NumElts = VT.getVectorNumElements(); 6944 MVT TruncVT = MVT::getIntegerVT(EltSize); 6945 SmallVector<SDValue, 8> Ops; 6946 SDLoc dl(N); 6947 for (unsigned i = 0; i != NumElts; ++i) { 6948 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6949 const APInt &CInt = C->getAPIntValue(); 6950 // Element types smaller than 32 bits are not legal, so use i32 elements. 6951 // The values are implicitly truncated so sext vs. zext doesn't matter. 6952 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6953 } 6954 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 6955 } 6956 6957 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6958 unsigned Opcode = N->getOpcode(); 6959 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6960 SDNode *N0 = N->getOperand(0).getNode(); 6961 SDNode *N1 = N->getOperand(1).getNode(); 6962 return N0->hasOneUse() && N1->hasOneUse() && 6963 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6964 } 6965 return false; 6966 } 6967 6968 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 6969 unsigned Opcode = N->getOpcode(); 6970 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6971 SDNode *N0 = N->getOperand(0).getNode(); 6972 SDNode *N1 = N->getOperand(1).getNode(); 6973 return N0->hasOneUse() && N1->hasOneUse() && 6974 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 6975 } 6976 return false; 6977 } 6978 6979 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 6980 // Multiplications are only custom-lowered for 128-bit vectors so that 6981 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 6982 EVT VT = Op.getValueType(); 6983 assert(VT.is128BitVector() && VT.isInteger() && 6984 "unexpected type for custom-lowering ISD::MUL"); 6985 SDNode *N0 = Op.getOperand(0).getNode(); 6986 SDNode *N1 = Op.getOperand(1).getNode(); 6987 unsigned NewOpc = 0; 6988 bool isMLA = false; 6989 bool isN0SExt = isSignExtended(N0, DAG); 6990 bool isN1SExt = isSignExtended(N1, DAG); 6991 if (isN0SExt && isN1SExt) 6992 NewOpc = ARMISD::VMULLs; 6993 else { 6994 bool isN0ZExt = isZeroExtended(N0, DAG); 6995 bool isN1ZExt = isZeroExtended(N1, DAG); 6996 if (isN0ZExt && isN1ZExt) 6997 NewOpc = ARMISD::VMULLu; 6998 else if (isN1SExt || isN1ZExt) { 6999 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7000 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7001 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7002 NewOpc = ARMISD::VMULLs; 7003 isMLA = true; 7004 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7005 NewOpc = ARMISD::VMULLu; 7006 isMLA = true; 7007 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7008 std::swap(N0, N1); 7009 NewOpc = ARMISD::VMULLu; 7010 isMLA = true; 7011 } 7012 } 7013 7014 if (!NewOpc) { 7015 if (VT == MVT::v2i64) 7016 // Fall through to expand this. It is not legal. 7017 return SDValue(); 7018 else 7019 // Other vector multiplications are legal. 7020 return Op; 7021 } 7022 } 7023 7024 // Legalize to a VMULL instruction. 7025 SDLoc DL(Op); 7026 SDValue Op0; 7027 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7028 if (!isMLA) { 7029 Op0 = SkipExtensionForVMULL(N0, DAG); 7030 assert(Op0.getValueType().is64BitVector() && 7031 Op1.getValueType().is64BitVector() && 7032 "unexpected types for extended operands to VMULL"); 7033 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7034 } 7035 7036 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7037 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7038 // vmull q0, d4, d6 7039 // vmlal q0, d5, d6 7040 // is faster than 7041 // vaddl q0, d4, d5 7042 // vmovl q1, d6 7043 // vmul q0, q0, q1 7044 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7045 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7046 EVT Op1VT = Op1.getValueType(); 7047 return DAG.getNode(N0->getOpcode(), DL, VT, 7048 DAG.getNode(NewOpc, DL, VT, 7049 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7050 DAG.getNode(NewOpc, DL, VT, 7051 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7052 } 7053 7054 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7055 SelectionDAG &DAG) { 7056 // TODO: Should this propagate fast-math-flags? 7057 7058 // Convert to float 7059 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7060 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7061 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7062 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7063 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7064 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7065 // Get reciprocal estimate. 7066 // float4 recip = vrecpeq_f32(yf); 7067 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7068 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7069 Y); 7070 // Because char has a smaller range than uchar, we can actually get away 7071 // without any newton steps. This requires that we use a weird bias 7072 // of 0xb000, however (again, this has been exhaustively tested). 7073 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7074 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7075 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7076 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7077 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7078 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7079 // Convert back to short. 7080 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7081 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7082 return X; 7083 } 7084 7085 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7086 SelectionDAG &DAG) { 7087 // TODO: Should this propagate fast-math-flags? 7088 7089 SDValue N2; 7090 // Convert to float. 7091 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7092 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7093 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7094 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7095 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7096 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7097 7098 // Use reciprocal estimate and one refinement step. 7099 // float4 recip = vrecpeq_f32(yf); 7100 // recip *= vrecpsq_f32(yf, recip); 7101 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7102 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7103 N1); 7104 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7105 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7106 N1, N2); 7107 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7108 // Because short has a smaller range than ushort, we can actually get away 7109 // with only a single newton step. This requires that we use a weird bias 7110 // of 89, however (again, this has been exhaustively tested). 7111 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7112 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7113 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7114 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7115 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7116 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7117 // Convert back to integer and return. 7118 // return vmovn_s32(vcvt_s32_f32(result)); 7119 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7120 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7121 return N0; 7122 } 7123 7124 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7125 EVT VT = Op.getValueType(); 7126 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7127 "unexpected type for custom-lowering ISD::SDIV"); 7128 7129 SDLoc dl(Op); 7130 SDValue N0 = Op.getOperand(0); 7131 SDValue N1 = Op.getOperand(1); 7132 SDValue N2, N3; 7133 7134 if (VT == MVT::v8i8) { 7135 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7136 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7137 7138 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7139 DAG.getIntPtrConstant(4, dl)); 7140 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7141 DAG.getIntPtrConstant(4, dl)); 7142 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7143 DAG.getIntPtrConstant(0, dl)); 7144 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7145 DAG.getIntPtrConstant(0, dl)); 7146 7147 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7148 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7149 7150 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7151 N0 = LowerCONCAT_VECTORS(N0, DAG); 7152 7153 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7154 return N0; 7155 } 7156 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7157 } 7158 7159 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7160 // TODO: Should this propagate fast-math-flags? 7161 EVT VT = Op.getValueType(); 7162 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7163 "unexpected type for custom-lowering ISD::UDIV"); 7164 7165 SDLoc dl(Op); 7166 SDValue N0 = Op.getOperand(0); 7167 SDValue N1 = Op.getOperand(1); 7168 SDValue N2, N3; 7169 7170 if (VT == MVT::v8i8) { 7171 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7172 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7173 7174 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7175 DAG.getIntPtrConstant(4, dl)); 7176 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7177 DAG.getIntPtrConstant(4, dl)); 7178 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7179 DAG.getIntPtrConstant(0, dl)); 7180 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7181 DAG.getIntPtrConstant(0, dl)); 7182 7183 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7184 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7185 7186 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7187 N0 = LowerCONCAT_VECTORS(N0, DAG); 7188 7189 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7190 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7191 MVT::i32), 7192 N0); 7193 return N0; 7194 } 7195 7196 // v4i16 sdiv ... Convert to float. 7197 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7198 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7199 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7200 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7201 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7202 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7203 7204 // Use reciprocal estimate and two refinement steps. 7205 // float4 recip = vrecpeq_f32(yf); 7206 // recip *= vrecpsq_f32(yf, recip); 7207 // recip *= vrecpsq_f32(yf, recip); 7208 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7209 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7210 BN1); 7211 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7212 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7213 BN1, N2); 7214 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7215 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7216 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7217 BN1, N2); 7218 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7219 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7220 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7221 // and that it will never cause us to return an answer too large). 7222 // float4 result = as_float4(as_int4(xf*recip) + 2); 7223 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7224 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7225 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7226 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7227 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7228 // Convert back to integer and return. 7229 // return vmovn_u32(vcvt_s32_f32(result)); 7230 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7231 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7232 return N0; 7233 } 7234 7235 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7236 EVT VT = Op.getNode()->getValueType(0); 7237 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7238 7239 unsigned Opc; 7240 bool ExtraOp = false; 7241 switch (Op.getOpcode()) { 7242 default: llvm_unreachable("Invalid code"); 7243 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7244 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7245 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7246 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7247 } 7248 7249 if (!ExtraOp) 7250 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7251 Op.getOperand(1)); 7252 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7253 Op.getOperand(1), Op.getOperand(2)); 7254 } 7255 7256 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7257 assert(Subtarget->isTargetDarwin()); 7258 7259 // For iOS, we want to call an alternative entry point: __sincos_stret, 7260 // return values are passed via sret. 7261 SDLoc dl(Op); 7262 SDValue Arg = Op.getOperand(0); 7263 EVT ArgVT = Arg.getValueType(); 7264 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7265 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7266 7267 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7268 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7269 7270 // Pair of floats / doubles used to pass the result. 7271 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 7272 auto &DL = DAG.getDataLayout(); 7273 7274 ArgListTy Args; 7275 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7276 SDValue SRet; 7277 if (ShouldUseSRet) { 7278 // Create stack object for sret. 7279 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7280 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7281 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7282 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7283 7284 ArgListEntry Entry; 7285 Entry.Node = SRet; 7286 Entry.Ty = RetTy->getPointerTo(); 7287 Entry.isSExt = false; 7288 Entry.isZExt = false; 7289 Entry.isSRet = true; 7290 Args.push_back(Entry); 7291 RetTy = Type::getVoidTy(*DAG.getContext()); 7292 } 7293 7294 ArgListEntry Entry; 7295 Entry.Node = Arg; 7296 Entry.Ty = ArgTy; 7297 Entry.isSExt = false; 7298 Entry.isZExt = false; 7299 Args.push_back(Entry); 7300 7301 const char *LibcallName = 7302 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 7303 RTLIB::Libcall LC = 7304 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 7305 CallingConv::ID CC = getLibcallCallingConv(LC); 7306 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7307 7308 TargetLowering::CallLoweringInfo CLI(DAG); 7309 CLI.setDebugLoc(dl) 7310 .setChain(DAG.getEntryNode()) 7311 .setCallee(CC, RetTy, Callee, std::move(Args)) 7312 .setDiscardResult(ShouldUseSRet); 7313 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7314 7315 if (!ShouldUseSRet) 7316 return CallResult.first; 7317 7318 SDValue LoadSin = 7319 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7320 7321 // Address of cos field. 7322 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7323 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7324 SDValue LoadCos = 7325 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7326 7327 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7328 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7329 LoadSin.getValue(0), LoadCos.getValue(0)); 7330 } 7331 7332 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7333 bool Signed, 7334 SDValue &Chain) const { 7335 EVT VT = Op.getValueType(); 7336 assert((VT == MVT::i32 || VT == MVT::i64) && 7337 "unexpected type for custom lowering DIV"); 7338 SDLoc dl(Op); 7339 7340 const auto &DL = DAG.getDataLayout(); 7341 const auto &TLI = DAG.getTargetLoweringInfo(); 7342 7343 const char *Name = nullptr; 7344 if (Signed) 7345 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7346 else 7347 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7348 7349 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7350 7351 ARMTargetLowering::ArgListTy Args; 7352 7353 for (auto AI : {1, 0}) { 7354 ArgListEntry Arg; 7355 Arg.Node = Op.getOperand(AI); 7356 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7357 Args.push_back(Arg); 7358 } 7359 7360 CallLoweringInfo CLI(DAG); 7361 CLI.setDebugLoc(dl) 7362 .setChain(Chain) 7363 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7364 ES, std::move(Args)); 7365 7366 return LowerCallTo(CLI).first; 7367 } 7368 7369 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7370 bool Signed) const { 7371 assert(Op.getValueType() == MVT::i32 && 7372 "unexpected type for custom lowering DIV"); 7373 SDLoc dl(Op); 7374 7375 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7376 DAG.getEntryNode(), Op.getOperand(1)); 7377 7378 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7379 } 7380 7381 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7382 SDLoc DL(N); 7383 SDValue Op = N->getOperand(1); 7384 if (N->getValueType(0) == MVT::i32) 7385 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7386 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7387 DAG.getConstant(0, DL, MVT::i32)); 7388 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7389 DAG.getConstant(1, DL, MVT::i32)); 7390 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7391 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7392 } 7393 7394 void ARMTargetLowering::ExpandDIV_Windows( 7395 SDValue Op, SelectionDAG &DAG, bool Signed, 7396 SmallVectorImpl<SDValue> &Results) const { 7397 const auto &DL = DAG.getDataLayout(); 7398 const auto &TLI = DAG.getTargetLoweringInfo(); 7399 7400 assert(Op.getValueType() == MVT::i64 && 7401 "unexpected type for custom lowering DIV"); 7402 SDLoc dl(Op); 7403 7404 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7405 7406 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7407 7408 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7409 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7410 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7411 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7412 7413 Results.push_back(Lower); 7414 Results.push_back(Upper); 7415 } 7416 7417 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7418 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7419 // Acquire/Release load/store is not legal for targets without a dmb or 7420 // equivalent available. 7421 return SDValue(); 7422 7423 // Monotonic load/store is legal for all targets. 7424 return Op; 7425 } 7426 7427 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7428 SmallVectorImpl<SDValue> &Results, 7429 SelectionDAG &DAG, 7430 const ARMSubtarget *Subtarget) { 7431 SDLoc DL(N); 7432 // Under Power Management extensions, the cycle-count is: 7433 // mrc p15, #0, <Rt>, c9, c13, #0 7434 SDValue Ops[] = { N->getOperand(0), // Chain 7435 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7436 DAG.getConstant(15, DL, MVT::i32), 7437 DAG.getConstant(0, DL, MVT::i32), 7438 DAG.getConstant(9, DL, MVT::i32), 7439 DAG.getConstant(13, DL, MVT::i32), 7440 DAG.getConstant(0, DL, MVT::i32) 7441 }; 7442 7443 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7444 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7445 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7446 DAG.getConstant(0, DL, MVT::i32))); 7447 Results.push_back(Cycles32.getValue(1)); 7448 } 7449 7450 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7451 SDLoc dl(V.getNode()); 7452 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7453 SDValue VHi = DAG.getAnyExtOrTrunc( 7454 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7455 dl, MVT::i32); 7456 SDValue RegClass = 7457 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7458 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7459 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7460 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7461 return SDValue( 7462 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7463 } 7464 7465 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7466 SmallVectorImpl<SDValue> & Results, 7467 SelectionDAG &DAG) { 7468 assert(N->getValueType(0) == MVT::i64 && 7469 "AtomicCmpSwap on types less than 64 should be legal"); 7470 SDValue Ops[] = {N->getOperand(1), 7471 createGPRPairNode(DAG, N->getOperand(2)), 7472 createGPRPairNode(DAG, N->getOperand(3)), 7473 N->getOperand(0)}; 7474 SDNode *CmpSwap = DAG.getMachineNode( 7475 ARM::CMP_SWAP_64, SDLoc(N), 7476 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7477 7478 MachineFunction &MF = DAG.getMachineFunction(); 7479 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7480 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7481 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7482 7483 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32, 7484 SDValue(CmpSwap, 0))); 7485 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32, 7486 SDValue(CmpSwap, 0))); 7487 Results.push_back(SDValue(CmpSwap, 2)); 7488 } 7489 7490 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 7491 SelectionDAG &DAG) { 7492 const auto &TLI = DAG.getTargetLoweringInfo(); 7493 7494 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 7495 "Custom lowering is MSVCRT specific!"); 7496 7497 SDLoc dl(Op); 7498 SDValue Val = Op.getOperand(0); 7499 MVT Ty = Val->getSimpleValueType(0); 7500 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 7501 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 7502 TLI.getPointerTy(DAG.getDataLayout())); 7503 7504 TargetLowering::ArgListTy Args; 7505 TargetLowering::ArgListEntry Entry; 7506 7507 Entry.Node = Val; 7508 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7509 Entry.isZExt = true; 7510 Args.push_back(Entry); 7511 7512 Entry.Node = Exponent; 7513 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 7514 Entry.isZExt = true; 7515 Args.push_back(Entry); 7516 7517 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7518 7519 // In the in-chain to the call is the entry node If we are emitting a 7520 // tailcall, the chain will be mutated if the node has a non-entry input 7521 // chain. 7522 SDValue InChain = DAG.getEntryNode(); 7523 SDValue TCChain = InChain; 7524 7525 const auto *F = DAG.getMachineFunction().getFunction(); 7526 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 7527 F->getReturnType() == LCRTy; 7528 if (IsTC) 7529 InChain = TCChain; 7530 7531 TargetLowering::CallLoweringInfo CLI(DAG); 7532 CLI.setDebugLoc(dl) 7533 .setChain(InChain) 7534 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 7535 .setTailCall(IsTC); 7536 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 7537 7538 // Return the chain (the DAG root) if it is a tail call 7539 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 7540 } 7541 7542 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7543 switch (Op.getOpcode()) { 7544 default: llvm_unreachable("Don't know how to custom lower this!"); 7545 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7546 case ISD::ConstantPool: 7547 if (Subtarget->genExecuteOnly()) 7548 llvm_unreachable("execute-only should not generate constant pools"); 7549 return LowerConstantPool(Op, DAG); 7550 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7551 case ISD::GlobalAddress: 7552 switch (Subtarget->getTargetTriple().getObjectFormat()) { 7553 default: llvm_unreachable("unknown object format"); 7554 case Triple::COFF: 7555 return LowerGlobalAddressWindows(Op, DAG); 7556 case Triple::ELF: 7557 return LowerGlobalAddressELF(Op, DAG); 7558 case Triple::MachO: 7559 return LowerGlobalAddressDarwin(Op, DAG); 7560 } 7561 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7562 case ISD::SELECT: return LowerSELECT(Op, DAG); 7563 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7564 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7565 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7566 case ISD::VASTART: return LowerVASTART(Op, DAG); 7567 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7568 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7569 case ISD::SINT_TO_FP: 7570 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7571 case ISD::FP_TO_SINT: 7572 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7573 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7574 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7575 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7576 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7577 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7578 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7579 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7580 Subtarget); 7581 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7582 case ISD::SHL: 7583 case ISD::SRL: 7584 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7585 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7586 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7587 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7588 case ISD::SRL_PARTS: 7589 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7590 case ISD::CTTZ: 7591 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7592 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7593 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7594 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7595 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7596 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7597 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7598 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7599 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7600 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7601 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7602 case ISD::MUL: return LowerMUL(Op, DAG); 7603 case ISD::SDIV: 7604 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7605 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7606 return LowerSDIV(Op, DAG); 7607 case ISD::UDIV: 7608 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7609 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7610 return LowerUDIV(Op, DAG); 7611 case ISD::ADDC: 7612 case ISD::ADDE: 7613 case ISD::SUBC: 7614 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7615 case ISD::SADDO: 7616 case ISD::UADDO: 7617 case ISD::SSUBO: 7618 case ISD::USUBO: 7619 return LowerXALUO(Op, DAG); 7620 case ISD::ATOMIC_LOAD: 7621 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7622 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7623 case ISD::SDIVREM: 7624 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7625 case ISD::DYNAMIC_STACKALLOC: 7626 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7627 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7628 llvm_unreachable("Don't know how to custom lower this!"); 7629 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7630 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7631 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 7632 case ARMISD::WIN__DBZCHK: return SDValue(); 7633 } 7634 } 7635 7636 /// ReplaceNodeResults - Replace the results of node with an illegal result 7637 /// type with new values built out of custom code. 7638 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7639 SmallVectorImpl<SDValue> &Results, 7640 SelectionDAG &DAG) const { 7641 SDValue Res; 7642 switch (N->getOpcode()) { 7643 default: 7644 llvm_unreachable("Don't know how to custom expand this!"); 7645 case ISD::READ_REGISTER: 7646 ExpandREAD_REGISTER(N, Results, DAG); 7647 break; 7648 case ISD::BITCAST: 7649 Res = ExpandBITCAST(N, DAG); 7650 break; 7651 case ISD::SRL: 7652 case ISD::SRA: 7653 Res = Expand64BitShift(N, DAG, Subtarget); 7654 break; 7655 case ISD::SREM: 7656 case ISD::UREM: 7657 Res = LowerREM(N, DAG); 7658 break; 7659 case ISD::SDIVREM: 7660 case ISD::UDIVREM: 7661 Res = LowerDivRem(SDValue(N, 0), DAG); 7662 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7663 Results.push_back(Res.getValue(0)); 7664 Results.push_back(Res.getValue(1)); 7665 return; 7666 case ISD::READCYCLECOUNTER: 7667 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7668 return; 7669 case ISD::UDIV: 7670 case ISD::SDIV: 7671 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7672 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7673 Results); 7674 case ISD::ATOMIC_CMP_SWAP: 7675 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7676 return; 7677 } 7678 if (Res.getNode()) 7679 Results.push_back(Res); 7680 } 7681 7682 //===----------------------------------------------------------------------===// 7683 // ARM Scheduler Hooks 7684 //===----------------------------------------------------------------------===// 7685 7686 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7687 /// registers the function context. 7688 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 7689 MachineBasicBlock *MBB, 7690 MachineBasicBlock *DispatchBB, 7691 int FI) const { 7692 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 7693 "ROPI/RWPI not currently supported with SjLj"); 7694 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7695 DebugLoc dl = MI.getDebugLoc(); 7696 MachineFunction *MF = MBB->getParent(); 7697 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7698 MachineConstantPool *MCP = MF->getConstantPool(); 7699 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7700 const Function *F = MF->getFunction(); 7701 7702 bool isThumb = Subtarget->isThumb(); 7703 bool isThumb2 = Subtarget->isThumb2(); 7704 7705 unsigned PCLabelId = AFI->createPICLabelUId(); 7706 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7707 ARMConstantPoolValue *CPV = 7708 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7709 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7710 7711 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7712 : &ARM::GPRRegClass; 7713 7714 // Grab constant pool and fixed stack memory operands. 7715 MachineMemOperand *CPMMO = 7716 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7717 MachineMemOperand::MOLoad, 4, 4); 7718 7719 MachineMemOperand *FIMMOSt = 7720 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7721 MachineMemOperand::MOStore, 4, 4); 7722 7723 // Load the address of the dispatch MBB into the jump buffer. 7724 if (isThumb2) { 7725 // Incoming value: jbuf 7726 // ldr.n r5, LCPI1_1 7727 // orr r5, r5, #1 7728 // add r5, pc 7729 // str r5, [$jbuf, #+4] ; &jbuf[1] 7730 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7731 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7732 .addConstantPoolIndex(CPI) 7733 .addMemOperand(CPMMO) 7734 .add(predOps(ARMCC::AL)); 7735 // Set the low bit because of thumb mode. 7736 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7737 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7738 .addReg(NewVReg1, RegState::Kill) 7739 .addImm(0x01) 7740 .add(predOps(ARMCC::AL)) 7741 .add(condCodeOp()); 7742 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7743 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7744 .addReg(NewVReg2, RegState::Kill) 7745 .addImm(PCLabelId); 7746 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7747 .addReg(NewVReg3, RegState::Kill) 7748 .addFrameIndex(FI) 7749 .addImm(36) // &jbuf[1] :: pc 7750 .addMemOperand(FIMMOSt) 7751 .add(predOps(ARMCC::AL)); 7752 } else if (isThumb) { 7753 // Incoming value: jbuf 7754 // ldr.n r1, LCPI1_4 7755 // add r1, pc 7756 // mov r2, #1 7757 // orrs r1, r2 7758 // add r2, $jbuf, #+4 ; &jbuf[1] 7759 // str r1, [r2] 7760 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7761 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7762 .addConstantPoolIndex(CPI) 7763 .addMemOperand(CPMMO) 7764 .add(predOps(ARMCC::AL)); 7765 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7766 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7767 .addReg(NewVReg1, RegState::Kill) 7768 .addImm(PCLabelId); 7769 // Set the low bit because of thumb mode. 7770 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7771 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7772 .addReg(ARM::CPSR, RegState::Define) 7773 .addImm(1) 7774 .add(predOps(ARMCC::AL)); 7775 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7776 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7777 .addReg(ARM::CPSR, RegState::Define) 7778 .addReg(NewVReg2, RegState::Kill) 7779 .addReg(NewVReg3, RegState::Kill) 7780 .add(predOps(ARMCC::AL)); 7781 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7782 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7783 .addFrameIndex(FI) 7784 .addImm(36); // &jbuf[1] :: pc 7785 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7786 .addReg(NewVReg4, RegState::Kill) 7787 .addReg(NewVReg5, RegState::Kill) 7788 .addImm(0) 7789 .addMemOperand(FIMMOSt) 7790 .add(predOps(ARMCC::AL)); 7791 } else { 7792 // Incoming value: jbuf 7793 // ldr r1, LCPI1_1 7794 // add r1, pc, r1 7795 // str r1, [$jbuf, #+4] ; &jbuf[1] 7796 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7797 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7798 .addConstantPoolIndex(CPI) 7799 .addImm(0) 7800 .addMemOperand(CPMMO) 7801 .add(predOps(ARMCC::AL)); 7802 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7803 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7804 .addReg(NewVReg1, RegState::Kill) 7805 .addImm(PCLabelId) 7806 .add(predOps(ARMCC::AL)); 7807 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7808 .addReg(NewVReg2, RegState::Kill) 7809 .addFrameIndex(FI) 7810 .addImm(36) // &jbuf[1] :: pc 7811 .addMemOperand(FIMMOSt) 7812 .add(predOps(ARMCC::AL)); 7813 } 7814 } 7815 7816 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 7817 MachineBasicBlock *MBB) const { 7818 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7819 DebugLoc dl = MI.getDebugLoc(); 7820 MachineFunction *MF = MBB->getParent(); 7821 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7822 MachineFrameInfo &MFI = MF->getFrameInfo(); 7823 int FI = MFI.getFunctionContextIndex(); 7824 7825 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7826 : &ARM::GPRnopcRegClass; 7827 7828 // Get a mapping of the call site numbers to all of the landing pads they're 7829 // associated with. 7830 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 7831 unsigned MaxCSNum = 0; 7832 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7833 ++BB) { 7834 if (!BB->isEHPad()) continue; 7835 7836 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7837 // pad. 7838 for (MachineBasicBlock::iterator 7839 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7840 if (!II->isEHLabel()) continue; 7841 7842 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7843 if (!MF->hasCallSiteLandingPad(Sym)) continue; 7844 7845 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 7846 for (SmallVectorImpl<unsigned>::iterator 7847 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7848 CSI != CSE; ++CSI) { 7849 CallSiteNumToLPad[*CSI].push_back(&*BB); 7850 MaxCSNum = std::max(MaxCSNum, *CSI); 7851 } 7852 break; 7853 } 7854 } 7855 7856 // Get an ordered list of the machine basic blocks for the jump table. 7857 std::vector<MachineBasicBlock*> LPadList; 7858 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7859 LPadList.reserve(CallSiteNumToLPad.size()); 7860 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7861 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7862 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7863 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7864 LPadList.push_back(*II); 7865 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7866 } 7867 } 7868 7869 assert(!LPadList.empty() && 7870 "No landing pad destinations for the dispatch jump table!"); 7871 7872 // Create the jump table and associated information. 7873 MachineJumpTableInfo *JTI = 7874 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7875 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7876 7877 // Create the MBBs for the dispatch code. 7878 7879 // Shove the dispatch's address into the return slot in the function context. 7880 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7881 DispatchBB->setIsEHPad(); 7882 7883 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7884 unsigned trap_opcode; 7885 if (Subtarget->isThumb()) 7886 trap_opcode = ARM::tTRAP; 7887 else 7888 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7889 7890 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7891 DispatchBB->addSuccessor(TrapBB); 7892 7893 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7894 DispatchBB->addSuccessor(DispContBB); 7895 7896 // Insert and MBBs. 7897 MF->insert(MF->end(), DispatchBB); 7898 MF->insert(MF->end(), DispContBB); 7899 MF->insert(MF->end(), TrapBB); 7900 7901 // Insert code into the entry block that creates and registers the function 7902 // context. 7903 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7904 7905 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7906 MachinePointerInfo::getFixedStack(*MF, FI), 7907 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7908 7909 MachineInstrBuilder MIB; 7910 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7911 7912 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7913 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7914 7915 // Add a register mask with no preserved registers. This results in all 7916 // registers being marked as clobbered. This can't work if the dispatch block 7917 // is in a Thumb1 function and is linked with ARM code which uses the FP 7918 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 7919 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 7920 7921 bool IsPositionIndependent = isPositionIndependent(); 7922 unsigned NumLPads = LPadList.size(); 7923 if (Subtarget->isThumb2()) { 7924 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7925 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7926 .addFrameIndex(FI) 7927 .addImm(4) 7928 .addMemOperand(FIMMOLd) 7929 .add(predOps(ARMCC::AL)); 7930 7931 if (NumLPads < 256) { 7932 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7933 .addReg(NewVReg1) 7934 .addImm(LPadList.size()) 7935 .add(predOps(ARMCC::AL)); 7936 } else { 7937 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7938 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7939 .addImm(NumLPads & 0xFFFF) 7940 .add(predOps(ARMCC::AL)); 7941 7942 unsigned VReg2 = VReg1; 7943 if ((NumLPads & 0xFFFF0000) != 0) { 7944 VReg2 = MRI->createVirtualRegister(TRC); 7945 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7946 .addReg(VReg1) 7947 .addImm(NumLPads >> 16) 7948 .add(predOps(ARMCC::AL)); 7949 } 7950 7951 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7952 .addReg(NewVReg1) 7953 .addReg(VReg2) 7954 .add(predOps(ARMCC::AL)); 7955 } 7956 7957 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7958 .addMBB(TrapBB) 7959 .addImm(ARMCC::HI) 7960 .addReg(ARM::CPSR); 7961 7962 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7963 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 7964 .addJumpTableIndex(MJTI) 7965 .add(predOps(ARMCC::AL)); 7966 7967 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7968 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 7969 .addReg(NewVReg3, RegState::Kill) 7970 .addReg(NewVReg1) 7971 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 7972 .add(predOps(ARMCC::AL)) 7973 .add(condCodeOp()); 7974 7975 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 7976 .addReg(NewVReg4, RegState::Kill) 7977 .addReg(NewVReg1) 7978 .addJumpTableIndex(MJTI); 7979 } else if (Subtarget->isThumb()) { 7980 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7981 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 7982 .addFrameIndex(FI) 7983 .addImm(1) 7984 .addMemOperand(FIMMOLd) 7985 .add(predOps(ARMCC::AL)); 7986 7987 if (NumLPads < 256) { 7988 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 7989 .addReg(NewVReg1) 7990 .addImm(NumLPads) 7991 .add(predOps(ARMCC::AL)); 7992 } else { 7993 MachineConstantPool *ConstantPool = MF->getConstantPool(); 7994 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 7995 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 7996 7997 // MachineConstantPool wants an explicit alignment. 7998 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 7999 if (Align == 0) 8000 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8001 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8002 8003 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8004 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8005 .addReg(VReg1, RegState::Define) 8006 .addConstantPoolIndex(Idx) 8007 .add(predOps(ARMCC::AL)); 8008 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8009 .addReg(NewVReg1) 8010 .addReg(VReg1) 8011 .add(predOps(ARMCC::AL)); 8012 } 8013 8014 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8015 .addMBB(TrapBB) 8016 .addImm(ARMCC::HI) 8017 .addReg(ARM::CPSR); 8018 8019 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8020 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8021 .addReg(ARM::CPSR, RegState::Define) 8022 .addReg(NewVReg1) 8023 .addImm(2) 8024 .add(predOps(ARMCC::AL)); 8025 8026 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8027 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8028 .addJumpTableIndex(MJTI) 8029 .add(predOps(ARMCC::AL)); 8030 8031 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8032 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8033 .addReg(ARM::CPSR, RegState::Define) 8034 .addReg(NewVReg2, RegState::Kill) 8035 .addReg(NewVReg3) 8036 .add(predOps(ARMCC::AL)); 8037 8038 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8039 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8040 8041 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8042 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8043 .addReg(NewVReg4, RegState::Kill) 8044 .addImm(0) 8045 .addMemOperand(JTMMOLd) 8046 .add(predOps(ARMCC::AL)); 8047 8048 unsigned NewVReg6 = NewVReg5; 8049 if (IsPositionIndependent) { 8050 NewVReg6 = MRI->createVirtualRegister(TRC); 8051 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8052 .addReg(ARM::CPSR, RegState::Define) 8053 .addReg(NewVReg5, RegState::Kill) 8054 .addReg(NewVReg3) 8055 .add(predOps(ARMCC::AL)); 8056 } 8057 8058 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8059 .addReg(NewVReg6, RegState::Kill) 8060 .addJumpTableIndex(MJTI); 8061 } else { 8062 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8063 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8064 .addFrameIndex(FI) 8065 .addImm(4) 8066 .addMemOperand(FIMMOLd) 8067 .add(predOps(ARMCC::AL)); 8068 8069 if (NumLPads < 256) { 8070 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8071 .addReg(NewVReg1) 8072 .addImm(NumLPads) 8073 .add(predOps(ARMCC::AL)); 8074 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8075 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8076 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8077 .addImm(NumLPads & 0xFFFF) 8078 .add(predOps(ARMCC::AL)); 8079 8080 unsigned VReg2 = VReg1; 8081 if ((NumLPads & 0xFFFF0000) != 0) { 8082 VReg2 = MRI->createVirtualRegister(TRC); 8083 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8084 .addReg(VReg1) 8085 .addImm(NumLPads >> 16) 8086 .add(predOps(ARMCC::AL)); 8087 } 8088 8089 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8090 .addReg(NewVReg1) 8091 .addReg(VReg2) 8092 .add(predOps(ARMCC::AL)); 8093 } else { 8094 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8095 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8096 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8097 8098 // MachineConstantPool wants an explicit alignment. 8099 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8100 if (Align == 0) 8101 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8102 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8103 8104 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8105 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8106 .addReg(VReg1, RegState::Define) 8107 .addConstantPoolIndex(Idx) 8108 .addImm(0) 8109 .add(predOps(ARMCC::AL)); 8110 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8111 .addReg(NewVReg1) 8112 .addReg(VReg1, RegState::Kill) 8113 .add(predOps(ARMCC::AL)); 8114 } 8115 8116 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8117 .addMBB(TrapBB) 8118 .addImm(ARMCC::HI) 8119 .addReg(ARM::CPSR); 8120 8121 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8122 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8123 .addReg(NewVReg1) 8124 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8125 .add(predOps(ARMCC::AL)) 8126 .add(condCodeOp()); 8127 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8128 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8129 .addJumpTableIndex(MJTI) 8130 .add(predOps(ARMCC::AL)); 8131 8132 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8133 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8134 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8135 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8136 .addReg(NewVReg3, RegState::Kill) 8137 .addReg(NewVReg4) 8138 .addImm(0) 8139 .addMemOperand(JTMMOLd) 8140 .add(predOps(ARMCC::AL)); 8141 8142 if (IsPositionIndependent) { 8143 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8144 .addReg(NewVReg5, RegState::Kill) 8145 .addReg(NewVReg4) 8146 .addJumpTableIndex(MJTI); 8147 } else { 8148 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8149 .addReg(NewVReg5, RegState::Kill) 8150 .addJumpTableIndex(MJTI); 8151 } 8152 } 8153 8154 // Add the jump table entries as successors to the MBB. 8155 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8156 for (std::vector<MachineBasicBlock*>::iterator 8157 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8158 MachineBasicBlock *CurMBB = *I; 8159 if (SeenMBBs.insert(CurMBB).second) 8160 DispContBB->addSuccessor(CurMBB); 8161 } 8162 8163 // N.B. the order the invoke BBs are processed in doesn't matter here. 8164 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8165 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8166 for (MachineBasicBlock *BB : InvokeBBs) { 8167 8168 // Remove the landing pad successor from the invoke block and replace it 8169 // with the new dispatch block. 8170 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8171 BB->succ_end()); 8172 while (!Successors.empty()) { 8173 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8174 if (SMBB->isEHPad()) { 8175 BB->removeSuccessor(SMBB); 8176 MBBLPads.push_back(SMBB); 8177 } 8178 } 8179 8180 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8181 BB->normalizeSuccProbs(); 8182 8183 // Find the invoke call and mark all of the callee-saved registers as 8184 // 'implicit defined' so that they're spilled. This prevents code from 8185 // moving instructions to before the EH block, where they will never be 8186 // executed. 8187 for (MachineBasicBlock::reverse_iterator 8188 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8189 if (!II->isCall()) continue; 8190 8191 DenseMap<unsigned, bool> DefRegs; 8192 for (MachineInstr::mop_iterator 8193 OI = II->operands_begin(), OE = II->operands_end(); 8194 OI != OE; ++OI) { 8195 if (!OI->isReg()) continue; 8196 DefRegs[OI->getReg()] = true; 8197 } 8198 8199 MachineInstrBuilder MIB(*MF, &*II); 8200 8201 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8202 unsigned Reg = SavedRegs[i]; 8203 if (Subtarget->isThumb2() && 8204 !ARM::tGPRRegClass.contains(Reg) && 8205 !ARM::hGPRRegClass.contains(Reg)) 8206 continue; 8207 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8208 continue; 8209 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8210 continue; 8211 if (!DefRegs[Reg]) 8212 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8213 } 8214 8215 break; 8216 } 8217 } 8218 8219 // Mark all former landing pads as non-landing pads. The dispatch is the only 8220 // landing pad now. 8221 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8222 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8223 (*I)->setIsEHPad(false); 8224 8225 // The instruction is gone now. 8226 MI.eraseFromParent(); 8227 } 8228 8229 static 8230 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8231 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8232 E = MBB->succ_end(); I != E; ++I) 8233 if (*I != Succ) 8234 return *I; 8235 llvm_unreachable("Expecting a BB with two successors!"); 8236 } 8237 8238 /// Return the load opcode for a given load size. If load size >= 8, 8239 /// neon opcode will be returned. 8240 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8241 if (LdSize >= 8) 8242 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8243 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8244 if (IsThumb1) 8245 return LdSize == 4 ? ARM::tLDRi 8246 : LdSize == 2 ? ARM::tLDRHi 8247 : LdSize == 1 ? ARM::tLDRBi : 0; 8248 if (IsThumb2) 8249 return LdSize == 4 ? ARM::t2LDR_POST 8250 : LdSize == 2 ? ARM::t2LDRH_POST 8251 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8252 return LdSize == 4 ? ARM::LDR_POST_IMM 8253 : LdSize == 2 ? ARM::LDRH_POST 8254 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8255 } 8256 8257 /// Return the store opcode for a given store size. If store size >= 8, 8258 /// neon opcode will be returned. 8259 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8260 if (StSize >= 8) 8261 return StSize == 16 ? ARM::VST1q32wb_fixed 8262 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8263 if (IsThumb1) 8264 return StSize == 4 ? ARM::tSTRi 8265 : StSize == 2 ? ARM::tSTRHi 8266 : StSize == 1 ? ARM::tSTRBi : 0; 8267 if (IsThumb2) 8268 return StSize == 4 ? ARM::t2STR_POST 8269 : StSize == 2 ? ARM::t2STRH_POST 8270 : StSize == 1 ? ARM::t2STRB_POST : 0; 8271 return StSize == 4 ? ARM::STR_POST_IMM 8272 : StSize == 2 ? ARM::STRH_POST 8273 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8274 } 8275 8276 /// Emit a post-increment load operation with given size. The instructions 8277 /// will be added to BB at Pos. 8278 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8279 const TargetInstrInfo *TII, const DebugLoc &dl, 8280 unsigned LdSize, unsigned Data, unsigned AddrIn, 8281 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8282 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8283 assert(LdOpc != 0 && "Should have a load opcode"); 8284 if (LdSize >= 8) { 8285 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8286 .addReg(AddrOut, RegState::Define) 8287 .addReg(AddrIn) 8288 .addImm(0) 8289 .add(predOps(ARMCC::AL)); 8290 } else if (IsThumb1) { 8291 // load + update AddrIn 8292 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8293 .addReg(AddrIn) 8294 .addImm(0) 8295 .add(predOps(ARMCC::AL)); 8296 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8297 .add(t1CondCodeOp()) 8298 .addReg(AddrIn) 8299 .addImm(LdSize) 8300 .add(predOps(ARMCC::AL)); 8301 } else if (IsThumb2) { 8302 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8303 .addReg(AddrOut, RegState::Define) 8304 .addReg(AddrIn) 8305 .addImm(LdSize) 8306 .add(predOps(ARMCC::AL)); 8307 } else { // arm 8308 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8309 .addReg(AddrOut, RegState::Define) 8310 .addReg(AddrIn) 8311 .addReg(0) 8312 .addImm(LdSize) 8313 .add(predOps(ARMCC::AL)); 8314 } 8315 } 8316 8317 /// Emit a post-increment store operation with given size. The instructions 8318 /// will be added to BB at Pos. 8319 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8320 const TargetInstrInfo *TII, const DebugLoc &dl, 8321 unsigned StSize, unsigned Data, unsigned AddrIn, 8322 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8323 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8324 assert(StOpc != 0 && "Should have a store opcode"); 8325 if (StSize >= 8) { 8326 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8327 .addReg(AddrIn) 8328 .addImm(0) 8329 .addReg(Data) 8330 .add(predOps(ARMCC::AL)); 8331 } else if (IsThumb1) { 8332 // store + update AddrIn 8333 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8334 .addReg(Data) 8335 .addReg(AddrIn) 8336 .addImm(0) 8337 .add(predOps(ARMCC::AL)); 8338 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8339 .add(t1CondCodeOp()) 8340 .addReg(AddrIn) 8341 .addImm(StSize) 8342 .add(predOps(ARMCC::AL)); 8343 } else if (IsThumb2) { 8344 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8345 .addReg(Data) 8346 .addReg(AddrIn) 8347 .addImm(StSize) 8348 .add(predOps(ARMCC::AL)); 8349 } else { // arm 8350 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8351 .addReg(Data) 8352 .addReg(AddrIn) 8353 .addReg(0) 8354 .addImm(StSize) 8355 .add(predOps(ARMCC::AL)); 8356 } 8357 } 8358 8359 MachineBasicBlock * 8360 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8361 MachineBasicBlock *BB) const { 8362 // This pseudo instruction has 3 operands: dst, src, size 8363 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8364 // Otherwise, we will generate unrolled scalar copies. 8365 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8366 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8367 MachineFunction::iterator It = ++BB->getIterator(); 8368 8369 unsigned dest = MI.getOperand(0).getReg(); 8370 unsigned src = MI.getOperand(1).getReg(); 8371 unsigned SizeVal = MI.getOperand(2).getImm(); 8372 unsigned Align = MI.getOperand(3).getImm(); 8373 DebugLoc dl = MI.getDebugLoc(); 8374 8375 MachineFunction *MF = BB->getParent(); 8376 MachineRegisterInfo &MRI = MF->getRegInfo(); 8377 unsigned UnitSize = 0; 8378 const TargetRegisterClass *TRC = nullptr; 8379 const TargetRegisterClass *VecTRC = nullptr; 8380 8381 bool IsThumb1 = Subtarget->isThumb1Only(); 8382 bool IsThumb2 = Subtarget->isThumb2(); 8383 bool IsThumb = Subtarget->isThumb(); 8384 8385 if (Align & 1) { 8386 UnitSize = 1; 8387 } else if (Align & 2) { 8388 UnitSize = 2; 8389 } else { 8390 // Check whether we can use NEON instructions. 8391 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 8392 Subtarget->hasNEON()) { 8393 if ((Align % 16 == 0) && SizeVal >= 16) 8394 UnitSize = 16; 8395 else if ((Align % 8 == 0) && SizeVal >= 8) 8396 UnitSize = 8; 8397 } 8398 // Can't use NEON instructions. 8399 if (UnitSize == 0) 8400 UnitSize = 4; 8401 } 8402 8403 // Select the correct opcode and register class for unit size load/store 8404 bool IsNeon = UnitSize >= 8; 8405 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8406 if (IsNeon) 8407 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8408 : UnitSize == 8 ? &ARM::DPRRegClass 8409 : nullptr; 8410 8411 unsigned BytesLeft = SizeVal % UnitSize; 8412 unsigned LoopSize = SizeVal - BytesLeft; 8413 8414 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8415 // Use LDR and STR to copy. 8416 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8417 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8418 unsigned srcIn = src; 8419 unsigned destIn = dest; 8420 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8421 unsigned srcOut = MRI.createVirtualRegister(TRC); 8422 unsigned destOut = MRI.createVirtualRegister(TRC); 8423 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8424 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8425 IsThumb1, IsThumb2); 8426 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8427 IsThumb1, IsThumb2); 8428 srcIn = srcOut; 8429 destIn = destOut; 8430 } 8431 8432 // Handle the leftover bytes with LDRB and STRB. 8433 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8434 // [destOut] = STRB_POST(scratch, destIn, 1) 8435 for (unsigned i = 0; i < BytesLeft; i++) { 8436 unsigned srcOut = MRI.createVirtualRegister(TRC); 8437 unsigned destOut = MRI.createVirtualRegister(TRC); 8438 unsigned scratch = MRI.createVirtualRegister(TRC); 8439 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8440 IsThumb1, IsThumb2); 8441 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8442 IsThumb1, IsThumb2); 8443 srcIn = srcOut; 8444 destIn = destOut; 8445 } 8446 MI.eraseFromParent(); // The instruction is gone now. 8447 return BB; 8448 } 8449 8450 // Expand the pseudo op to a loop. 8451 // thisMBB: 8452 // ... 8453 // movw varEnd, # --> with thumb2 8454 // movt varEnd, # 8455 // ldrcp varEnd, idx --> without thumb2 8456 // fallthrough --> loopMBB 8457 // loopMBB: 8458 // PHI varPhi, varEnd, varLoop 8459 // PHI srcPhi, src, srcLoop 8460 // PHI destPhi, dst, destLoop 8461 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8462 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8463 // subs varLoop, varPhi, #UnitSize 8464 // bne loopMBB 8465 // fallthrough --> exitMBB 8466 // exitMBB: 8467 // epilogue to handle left-over bytes 8468 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8469 // [destOut] = STRB_POST(scratch, destLoop, 1) 8470 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8471 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8472 MF->insert(It, loopMBB); 8473 MF->insert(It, exitMBB); 8474 8475 // Transfer the remainder of BB and its successor edges to exitMBB. 8476 exitMBB->splice(exitMBB->begin(), BB, 8477 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8478 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8479 8480 // Load an immediate to varEnd. 8481 unsigned varEnd = MRI.createVirtualRegister(TRC); 8482 if (Subtarget->useMovt(*MF)) { 8483 unsigned Vtmp = varEnd; 8484 if ((LoopSize & 0xFFFF0000) != 0) 8485 Vtmp = MRI.createVirtualRegister(TRC); 8486 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 8487 .addImm(LoopSize & 0xFFFF) 8488 .add(predOps(ARMCC::AL)); 8489 8490 if ((LoopSize & 0xFFFF0000) != 0) 8491 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 8492 .addReg(Vtmp) 8493 .addImm(LoopSize >> 16) 8494 .add(predOps(ARMCC::AL)); 8495 } else { 8496 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8497 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8498 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8499 8500 // MachineConstantPool wants an explicit alignment. 8501 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8502 if (Align == 0) 8503 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8504 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8505 8506 if (IsThumb) 8507 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 8508 .addReg(varEnd, RegState::Define) 8509 .addConstantPoolIndex(Idx) 8510 .add(predOps(ARMCC::AL)); 8511 else 8512 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 8513 .addReg(varEnd, RegState::Define) 8514 .addConstantPoolIndex(Idx) 8515 .addImm(0) 8516 .add(predOps(ARMCC::AL)); 8517 } 8518 BB->addSuccessor(loopMBB); 8519 8520 // Generate the loop body: 8521 // varPhi = PHI(varLoop, varEnd) 8522 // srcPhi = PHI(srcLoop, src) 8523 // destPhi = PHI(destLoop, dst) 8524 MachineBasicBlock *entryBB = BB; 8525 BB = loopMBB; 8526 unsigned varLoop = MRI.createVirtualRegister(TRC); 8527 unsigned varPhi = MRI.createVirtualRegister(TRC); 8528 unsigned srcLoop = MRI.createVirtualRegister(TRC); 8529 unsigned srcPhi = MRI.createVirtualRegister(TRC); 8530 unsigned destLoop = MRI.createVirtualRegister(TRC); 8531 unsigned destPhi = MRI.createVirtualRegister(TRC); 8532 8533 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 8534 .addReg(varLoop).addMBB(loopMBB) 8535 .addReg(varEnd).addMBB(entryBB); 8536 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 8537 .addReg(srcLoop).addMBB(loopMBB) 8538 .addReg(src).addMBB(entryBB); 8539 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 8540 .addReg(destLoop).addMBB(loopMBB) 8541 .addReg(dest).addMBB(entryBB); 8542 8543 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8544 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 8545 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8546 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 8547 IsThumb1, IsThumb2); 8548 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 8549 IsThumb1, IsThumb2); 8550 8551 // Decrement loop variable by UnitSize. 8552 if (IsThumb1) { 8553 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 8554 .add(t1CondCodeOp()) 8555 .addReg(varPhi) 8556 .addImm(UnitSize) 8557 .add(predOps(ARMCC::AL)); 8558 } else { 8559 MachineInstrBuilder MIB = 8560 BuildMI(*BB, BB->end(), dl, 8561 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 8562 MIB.addReg(varPhi) 8563 .addImm(UnitSize) 8564 .add(predOps(ARMCC::AL)) 8565 .add(condCodeOp()); 8566 MIB->getOperand(5).setReg(ARM::CPSR); 8567 MIB->getOperand(5).setIsDef(true); 8568 } 8569 BuildMI(*BB, BB->end(), dl, 8570 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8571 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 8572 8573 // loopMBB can loop back to loopMBB or fall through to exitMBB. 8574 BB->addSuccessor(loopMBB); 8575 BB->addSuccessor(exitMBB); 8576 8577 // Add epilogue to handle BytesLeft. 8578 BB = exitMBB; 8579 auto StartOfExit = exitMBB->begin(); 8580 8581 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8582 // [destOut] = STRB_POST(scratch, destLoop, 1) 8583 unsigned srcIn = srcLoop; 8584 unsigned destIn = destLoop; 8585 for (unsigned i = 0; i < BytesLeft; i++) { 8586 unsigned srcOut = MRI.createVirtualRegister(TRC); 8587 unsigned destOut = MRI.createVirtualRegister(TRC); 8588 unsigned scratch = MRI.createVirtualRegister(TRC); 8589 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 8590 IsThumb1, IsThumb2); 8591 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8592 IsThumb1, IsThumb2); 8593 srcIn = srcOut; 8594 destIn = destOut; 8595 } 8596 8597 MI.eraseFromParent(); // The instruction is gone now. 8598 return BB; 8599 } 8600 8601 MachineBasicBlock * 8602 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 8603 MachineBasicBlock *MBB) const { 8604 const TargetMachine &TM = getTargetMachine(); 8605 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8606 DebugLoc DL = MI.getDebugLoc(); 8607 8608 assert(Subtarget->isTargetWindows() && 8609 "__chkstk is only supported on Windows"); 8610 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8611 8612 // __chkstk takes the number of words to allocate on the stack in R4, and 8613 // returns the stack adjustment in number of bytes in R4. This will not 8614 // clober any other registers (other than the obvious lr). 8615 // 8616 // Although, technically, IP should be considered a register which may be 8617 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8618 // thumb-2 environment, so there is no interworking required. As a result, we 8619 // do not expect a veneer to be emitted by the linker, clobbering IP. 8620 // 8621 // Each module receives its own copy of __chkstk, so no import thunk is 8622 // required, again, ensuring that IP is not clobbered. 8623 // 8624 // Finally, although some linkers may theoretically provide a trampoline for 8625 // out of range calls (which is quite common due to a 32M range limitation of 8626 // branches for Thumb), we can generate the long-call version via 8627 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8628 // IP. 8629 8630 switch (TM.getCodeModel()) { 8631 case CodeModel::Small: 8632 case CodeModel::Medium: 8633 case CodeModel::Default: 8634 case CodeModel::Kernel: 8635 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8636 .add(predOps(ARMCC::AL)) 8637 .addExternalSymbol("__chkstk") 8638 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8639 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8640 .addReg(ARM::R12, 8641 RegState::Implicit | RegState::Define | RegState::Dead); 8642 break; 8643 case CodeModel::Large: 8644 case CodeModel::JITDefault: { 8645 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8646 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8647 8648 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8649 .addExternalSymbol("__chkstk"); 8650 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8651 .add(predOps(ARMCC::AL)) 8652 .addReg(Reg, RegState::Kill) 8653 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8654 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8655 .addReg(ARM::R12, 8656 RegState::Implicit | RegState::Define | RegState::Dead); 8657 break; 8658 } 8659 } 8660 8661 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 8662 .addReg(ARM::SP, RegState::Kill) 8663 .addReg(ARM::R4, RegState::Kill) 8664 .setMIFlags(MachineInstr::FrameSetup) 8665 .add(predOps(ARMCC::AL)) 8666 .add(condCodeOp()); 8667 8668 MI.eraseFromParent(); 8669 return MBB; 8670 } 8671 8672 MachineBasicBlock * 8673 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 8674 MachineBasicBlock *MBB) const { 8675 DebugLoc DL = MI.getDebugLoc(); 8676 MachineFunction *MF = MBB->getParent(); 8677 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8678 8679 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8680 MF->insert(++MBB->getIterator(), ContBB); 8681 ContBB->splice(ContBB->begin(), MBB, 8682 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8683 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8684 MBB->addSuccessor(ContBB); 8685 8686 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8687 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 8688 MF->push_back(TrapBB); 8689 MBB->addSuccessor(TrapBB); 8690 8691 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 8692 .addReg(MI.getOperand(0).getReg()) 8693 .addImm(0) 8694 .add(predOps(ARMCC::AL)); 8695 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 8696 .addMBB(TrapBB) 8697 .addImm(ARMCC::EQ) 8698 .addReg(ARM::CPSR); 8699 8700 MI.eraseFromParent(); 8701 return ContBB; 8702 } 8703 8704 MachineBasicBlock * 8705 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8706 MachineBasicBlock *BB) const { 8707 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8708 DebugLoc dl = MI.getDebugLoc(); 8709 bool isThumb2 = Subtarget->isThumb2(); 8710 switch (MI.getOpcode()) { 8711 default: { 8712 MI.print(errs()); 8713 llvm_unreachable("Unexpected instr type to insert"); 8714 } 8715 8716 // Thumb1 post-indexed loads are really just single-register LDMs. 8717 case ARM::tLDR_postidx: { 8718 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 8719 .add(MI.getOperand(1)) // Rn_wb 8720 .add(MI.getOperand(2)) // Rn 8721 .add(MI.getOperand(3)) // PredImm 8722 .add(MI.getOperand(4)) // PredReg 8723 .add(MI.getOperand(0)); // Rt 8724 MI.eraseFromParent(); 8725 return BB; 8726 } 8727 8728 // The Thumb2 pre-indexed stores have the same MI operands, they just 8729 // define them differently in the .td files from the isel patterns, so 8730 // they need pseudos. 8731 case ARM::t2STR_preidx: 8732 MI.setDesc(TII->get(ARM::t2STR_PRE)); 8733 return BB; 8734 case ARM::t2STRB_preidx: 8735 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 8736 return BB; 8737 case ARM::t2STRH_preidx: 8738 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 8739 return BB; 8740 8741 case ARM::STRi_preidx: 8742 case ARM::STRBi_preidx: { 8743 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 8744 : ARM::STRB_PRE_IMM; 8745 // Decode the offset. 8746 unsigned Offset = MI.getOperand(4).getImm(); 8747 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8748 Offset = ARM_AM::getAM2Offset(Offset); 8749 if (isSub) 8750 Offset = -Offset; 8751 8752 MachineMemOperand *MMO = *MI.memoperands_begin(); 8753 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8754 .add(MI.getOperand(0)) // Rn_wb 8755 .add(MI.getOperand(1)) // Rt 8756 .add(MI.getOperand(2)) // Rn 8757 .addImm(Offset) // offset (skip GPR==zero_reg) 8758 .add(MI.getOperand(5)) // pred 8759 .add(MI.getOperand(6)) 8760 .addMemOperand(MMO); 8761 MI.eraseFromParent(); 8762 return BB; 8763 } 8764 case ARM::STRr_preidx: 8765 case ARM::STRBr_preidx: 8766 case ARM::STRH_preidx: { 8767 unsigned NewOpc; 8768 switch (MI.getOpcode()) { 8769 default: llvm_unreachable("unexpected opcode!"); 8770 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8771 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8772 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8773 } 8774 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8775 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 8776 MIB.add(MI.getOperand(i)); 8777 MI.eraseFromParent(); 8778 return BB; 8779 } 8780 8781 case ARM::tMOVCCr_pseudo: { 8782 // To "insert" a SELECT_CC instruction, we actually have to insert the 8783 // diamond control-flow pattern. The incoming instruction knows the 8784 // destination vreg to set, the condition code register to branch on, the 8785 // true/false values to select between, and a branch opcode to use. 8786 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8787 MachineFunction::iterator It = ++BB->getIterator(); 8788 8789 // thisMBB: 8790 // ... 8791 // TrueVal = ... 8792 // cmpTY ccX, r1, r2 8793 // bCC copy1MBB 8794 // fallthrough --> copy0MBB 8795 MachineBasicBlock *thisMBB = BB; 8796 MachineFunction *F = BB->getParent(); 8797 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8798 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8799 F->insert(It, copy0MBB); 8800 F->insert(It, sinkMBB); 8801 8802 // Transfer the remainder of BB and its successor edges to sinkMBB. 8803 sinkMBB->splice(sinkMBB->begin(), BB, 8804 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8805 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8806 8807 BB->addSuccessor(copy0MBB); 8808 BB->addSuccessor(sinkMBB); 8809 8810 BuildMI(BB, dl, TII->get(ARM::tBcc)) 8811 .addMBB(sinkMBB) 8812 .addImm(MI.getOperand(3).getImm()) 8813 .addReg(MI.getOperand(4).getReg()); 8814 8815 // copy0MBB: 8816 // %FalseValue = ... 8817 // # fallthrough to sinkMBB 8818 BB = copy0MBB; 8819 8820 // Update machine-CFG edges 8821 BB->addSuccessor(sinkMBB); 8822 8823 // sinkMBB: 8824 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8825 // ... 8826 BB = sinkMBB; 8827 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 8828 .addReg(MI.getOperand(1).getReg()) 8829 .addMBB(copy0MBB) 8830 .addReg(MI.getOperand(2).getReg()) 8831 .addMBB(thisMBB); 8832 8833 MI.eraseFromParent(); // The pseudo instruction is gone now. 8834 return BB; 8835 } 8836 8837 case ARM::BCCi64: 8838 case ARM::BCCZi64: { 8839 // If there is an unconditional branch to the other successor, remove it. 8840 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8841 8842 // Compare both parts that make up the double comparison separately for 8843 // equality. 8844 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 8845 8846 unsigned LHS1 = MI.getOperand(1).getReg(); 8847 unsigned LHS2 = MI.getOperand(2).getReg(); 8848 if (RHSisZero) { 8849 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8850 .addReg(LHS1) 8851 .addImm(0) 8852 .add(predOps(ARMCC::AL)); 8853 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8854 .addReg(LHS2).addImm(0) 8855 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8856 } else { 8857 unsigned RHS1 = MI.getOperand(3).getReg(); 8858 unsigned RHS2 = MI.getOperand(4).getReg(); 8859 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8860 .addReg(LHS1) 8861 .addReg(RHS1) 8862 .add(predOps(ARMCC::AL)); 8863 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8864 .addReg(LHS2).addReg(RHS2) 8865 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8866 } 8867 8868 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 8869 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8870 if (MI.getOperand(0).getImm() == ARMCC::NE) 8871 std::swap(destMBB, exitMBB); 8872 8873 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8874 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8875 if (isThumb2) 8876 BuildMI(BB, dl, TII->get(ARM::t2B)) 8877 .addMBB(exitMBB) 8878 .add(predOps(ARMCC::AL)); 8879 else 8880 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8881 8882 MI.eraseFromParent(); // The pseudo instruction is gone now. 8883 return BB; 8884 } 8885 8886 case ARM::Int_eh_sjlj_setjmp: 8887 case ARM::Int_eh_sjlj_setjmp_nofp: 8888 case ARM::tInt_eh_sjlj_setjmp: 8889 case ARM::t2Int_eh_sjlj_setjmp: 8890 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8891 return BB; 8892 8893 case ARM::Int_eh_sjlj_setup_dispatch: 8894 EmitSjLjDispatchBlock(MI, BB); 8895 return BB; 8896 8897 case ARM::ABS: 8898 case ARM::t2ABS: { 8899 // To insert an ABS instruction, we have to insert the 8900 // diamond control-flow pattern. The incoming instruction knows the 8901 // source vreg to test against 0, the destination vreg to set, 8902 // the condition code register to branch on, the 8903 // true/false values to select between, and a branch opcode to use. 8904 // It transforms 8905 // V1 = ABS V0 8906 // into 8907 // V2 = MOVS V0 8908 // BCC (branch to SinkBB if V0 >= 0) 8909 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8910 // SinkBB: V1 = PHI(V2, V3) 8911 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8912 MachineFunction::iterator BBI = ++BB->getIterator(); 8913 MachineFunction *Fn = BB->getParent(); 8914 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8915 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8916 Fn->insert(BBI, RSBBB); 8917 Fn->insert(BBI, SinkBB); 8918 8919 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 8920 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 8921 bool ABSSrcKIll = MI.getOperand(1).isKill(); 8922 bool isThumb2 = Subtarget->isThumb2(); 8923 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8924 // In Thumb mode S must not be specified if source register is the SP or 8925 // PC and if destination register is the SP, so restrict register class 8926 unsigned NewRsbDstReg = 8927 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8928 8929 // Transfer the remainder of BB and its successor edges to sinkMBB. 8930 SinkBB->splice(SinkBB->begin(), BB, 8931 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8932 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8933 8934 BB->addSuccessor(RSBBB); 8935 BB->addSuccessor(SinkBB); 8936 8937 // fall through to SinkMBB 8938 RSBBB->addSuccessor(SinkBB); 8939 8940 // insert a cmp at the end of BB 8941 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8942 .addReg(ABSSrcReg) 8943 .addImm(0) 8944 .add(predOps(ARMCC::AL)); 8945 8946 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8947 BuildMI(BB, dl, 8948 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8949 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8950 8951 // insert rsbri in RSBBB 8952 // Note: BCC and rsbri will be converted into predicated rsbmi 8953 // by if-conversion pass 8954 BuildMI(*RSBBB, RSBBB->begin(), dl, 8955 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8956 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8957 .addImm(0) 8958 .add(predOps(ARMCC::AL)) 8959 .add(condCodeOp()); 8960 8961 // insert PHI in SinkBB, 8962 // reuse ABSDstReg to not change uses of ABS instruction 8963 BuildMI(*SinkBB, SinkBB->begin(), dl, 8964 TII->get(ARM::PHI), ABSDstReg) 8965 .addReg(NewRsbDstReg).addMBB(RSBBB) 8966 .addReg(ABSSrcReg).addMBB(BB); 8967 8968 // remove ABS instruction 8969 MI.eraseFromParent(); 8970 8971 // return last added BB 8972 return SinkBB; 8973 } 8974 case ARM::COPY_STRUCT_BYVAL_I32: 8975 ++NumLoopByVals; 8976 return EmitStructByval(MI, BB); 8977 case ARM::WIN__CHKSTK: 8978 return EmitLowered__chkstk(MI, BB); 8979 case ARM::WIN__DBZCHK: 8980 return EmitLowered__dbzchk(MI, BB); 8981 } 8982 } 8983 8984 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 8985 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 8986 /// instead of as a custom inserter because we need the use list from the SDNode. 8987 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 8988 MachineInstr &MI, const SDNode *Node) { 8989 bool isThumb1 = Subtarget->isThumb1Only(); 8990 8991 DebugLoc DL = MI.getDebugLoc(); 8992 MachineFunction *MF = MI.getParent()->getParent(); 8993 MachineRegisterInfo &MRI = MF->getRegInfo(); 8994 MachineInstrBuilder MIB(*MF, MI); 8995 8996 // If the new dst/src is unused mark it as dead. 8997 if (!Node->hasAnyUseOfValue(0)) { 8998 MI.getOperand(0).setIsDead(true); 8999 } 9000 if (!Node->hasAnyUseOfValue(1)) { 9001 MI.getOperand(1).setIsDead(true); 9002 } 9003 9004 // The MEMCPY both defines and kills the scratch registers. 9005 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9006 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9007 : &ARM::GPRRegClass); 9008 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9009 } 9010 } 9011 9012 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9013 SDNode *Node) const { 9014 if (MI.getOpcode() == ARM::MEMCPY) { 9015 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9016 return; 9017 } 9018 9019 const MCInstrDesc *MCID = &MI.getDesc(); 9020 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9021 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9022 // operand is still set to noreg. If needed, set the optional operand's 9023 // register to CPSR, and remove the redundant implicit def. 9024 // 9025 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 9026 9027 // Rename pseudo opcodes. 9028 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9029 if (NewOpc) { 9030 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9031 MCID = &TII->get(NewOpc); 9032 9033 assert(MCID->getNumOperands() == MI.getDesc().getNumOperands() + 1 && 9034 "converted opcode should be the same except for cc_out"); 9035 9036 MI.setDesc(*MCID); 9037 9038 // Add the optional cc_out operand 9039 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9040 } 9041 unsigned ccOutIdx = MCID->getNumOperands() - 1; 9042 9043 // Any ARM instruction that sets the 's' bit should specify an optional 9044 // "cc_out" operand in the last operand position. 9045 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9046 assert(!NewOpc && "Optional cc_out operand required"); 9047 return; 9048 } 9049 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9050 // since we already have an optional CPSR def. 9051 bool definesCPSR = false; 9052 bool deadCPSR = false; 9053 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9054 ++i) { 9055 const MachineOperand &MO = MI.getOperand(i); 9056 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9057 definesCPSR = true; 9058 if (MO.isDead()) 9059 deadCPSR = true; 9060 MI.RemoveOperand(i); 9061 break; 9062 } 9063 } 9064 if (!definesCPSR) { 9065 assert(!NewOpc && "Optional cc_out operand required"); 9066 return; 9067 } 9068 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9069 if (deadCPSR) { 9070 assert(!MI.getOperand(ccOutIdx).getReg() && 9071 "expect uninitialized optional cc_out operand"); 9072 return; 9073 } 9074 9075 // If this instruction was defined with an optional CPSR def and its dag node 9076 // had a live implicit CPSR def, then activate the optional CPSR def. 9077 MachineOperand &MO = MI.getOperand(ccOutIdx); 9078 MO.setReg(ARM::CPSR); 9079 MO.setIsDef(true); 9080 } 9081 9082 //===----------------------------------------------------------------------===// 9083 // ARM Optimization Hooks 9084 //===----------------------------------------------------------------------===// 9085 9086 // Helper function that checks if N is a null or all ones constant. 9087 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9088 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9089 } 9090 9091 // Return true if N is conditionally 0 or all ones. 9092 // Detects these expressions where cc is an i1 value: 9093 // 9094 // (select cc 0, y) [AllOnes=0] 9095 // (select cc y, 0) [AllOnes=0] 9096 // (zext cc) [AllOnes=0] 9097 // (sext cc) [AllOnes=0/1] 9098 // (select cc -1, y) [AllOnes=1] 9099 // (select cc y, -1) [AllOnes=1] 9100 // 9101 // Invert is set when N is the null/all ones constant when CC is false. 9102 // OtherOp is set to the alternative value of N. 9103 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9104 SDValue &CC, bool &Invert, 9105 SDValue &OtherOp, 9106 SelectionDAG &DAG) { 9107 switch (N->getOpcode()) { 9108 default: return false; 9109 case ISD::SELECT: { 9110 CC = N->getOperand(0); 9111 SDValue N1 = N->getOperand(1); 9112 SDValue N2 = N->getOperand(2); 9113 if (isZeroOrAllOnes(N1, AllOnes)) { 9114 Invert = false; 9115 OtherOp = N2; 9116 return true; 9117 } 9118 if (isZeroOrAllOnes(N2, AllOnes)) { 9119 Invert = true; 9120 OtherOp = N1; 9121 return true; 9122 } 9123 return false; 9124 } 9125 case ISD::ZERO_EXTEND: 9126 // (zext cc) can never be the all ones value. 9127 if (AllOnes) 9128 return false; 9129 LLVM_FALLTHROUGH; 9130 case ISD::SIGN_EXTEND: { 9131 SDLoc dl(N); 9132 EVT VT = N->getValueType(0); 9133 CC = N->getOperand(0); 9134 if (CC.getValueType() != MVT::i1) 9135 return false; 9136 Invert = !AllOnes; 9137 if (AllOnes) 9138 // When looking for an AllOnes constant, N is an sext, and the 'other' 9139 // value is 0. 9140 OtherOp = DAG.getConstant(0, dl, VT); 9141 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9142 // When looking for a 0 constant, N can be zext or sext. 9143 OtherOp = DAG.getConstant(1, dl, VT); 9144 else 9145 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9146 VT); 9147 return true; 9148 } 9149 } 9150 } 9151 9152 // Combine a constant select operand into its use: 9153 // 9154 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9155 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9156 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9157 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9158 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9159 // 9160 // The transform is rejected if the select doesn't have a constant operand that 9161 // is null, or all ones when AllOnes is set. 9162 // 9163 // Also recognize sext/zext from i1: 9164 // 9165 // (add (zext cc), x) -> (select cc (add x, 1), x) 9166 // (add (sext cc), x) -> (select cc (add x, -1), x) 9167 // 9168 // These transformations eventually create predicated instructions. 9169 // 9170 // @param N The node to transform. 9171 // @param Slct The N operand that is a select. 9172 // @param OtherOp The other N operand (x above). 9173 // @param DCI Context. 9174 // @param AllOnes Require the select constant to be all ones instead of null. 9175 // @returns The new node, or SDValue() on failure. 9176 static 9177 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9178 TargetLowering::DAGCombinerInfo &DCI, 9179 bool AllOnes = false) { 9180 SelectionDAG &DAG = DCI.DAG; 9181 EVT VT = N->getValueType(0); 9182 SDValue NonConstantVal; 9183 SDValue CCOp; 9184 bool SwapSelectOps; 9185 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9186 NonConstantVal, DAG)) 9187 return SDValue(); 9188 9189 // Slct is now know to be the desired identity constant when CC is true. 9190 SDValue TrueVal = OtherOp; 9191 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9192 OtherOp, NonConstantVal); 9193 // Unless SwapSelectOps says CC should be false. 9194 if (SwapSelectOps) 9195 std::swap(TrueVal, FalseVal); 9196 9197 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9198 CCOp, TrueVal, FalseVal); 9199 } 9200 9201 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9202 static 9203 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9204 TargetLowering::DAGCombinerInfo &DCI) { 9205 SDValue N0 = N->getOperand(0); 9206 SDValue N1 = N->getOperand(1); 9207 if (N0.getNode()->hasOneUse()) 9208 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9209 return Result; 9210 if (N1.getNode()->hasOneUse()) 9211 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9212 return Result; 9213 return SDValue(); 9214 } 9215 9216 static bool IsVUZPShuffleNode(SDNode *N) { 9217 // VUZP shuffle node. 9218 if (N->getOpcode() == ARMISD::VUZP) 9219 return true; 9220 9221 // "VUZP" on i32 is an alias for VTRN. 9222 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9223 return true; 9224 9225 return false; 9226 } 9227 9228 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9229 TargetLowering::DAGCombinerInfo &DCI, 9230 const ARMSubtarget *Subtarget) { 9231 // Look for ADD(VUZP.0, VUZP.1). 9232 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9233 N0 == N1) 9234 return SDValue(); 9235 9236 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9237 if (!N->getValueType(0).is64BitVector()) 9238 return SDValue(); 9239 9240 // Generate vpadd. 9241 SelectionDAG &DAG = DCI.DAG; 9242 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9243 SDLoc dl(N); 9244 SDNode *Unzip = N0.getNode(); 9245 EVT VT = N->getValueType(0); 9246 9247 SmallVector<SDValue, 8> Ops; 9248 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9249 TLI.getPointerTy(DAG.getDataLayout()))); 9250 Ops.push_back(Unzip->getOperand(0)); 9251 Ops.push_back(Unzip->getOperand(1)); 9252 9253 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9254 } 9255 9256 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9257 TargetLowering::DAGCombinerInfo &DCI, 9258 const ARMSubtarget *Subtarget) { 9259 // Check for two extended operands. 9260 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9261 N1.getOpcode() == ISD::SIGN_EXTEND) && 9262 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9263 N1.getOpcode() == ISD::ZERO_EXTEND)) 9264 return SDValue(); 9265 9266 SDValue N00 = N0.getOperand(0); 9267 SDValue N10 = N1.getOperand(0); 9268 9269 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9270 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9271 N00 == N10) 9272 return SDValue(); 9273 9274 // We only recognize Q register paddl here; this can't be reached until 9275 // after type legalization. 9276 if (!N00.getValueType().is64BitVector() || 9277 !N0.getValueType().is128BitVector()) 9278 return SDValue(); 9279 9280 // Generate vpaddl. 9281 SelectionDAG &DAG = DCI.DAG; 9282 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9283 SDLoc dl(N); 9284 EVT VT = N->getValueType(0); 9285 9286 SmallVector<SDValue, 8> Ops; 9287 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9288 unsigned Opcode; 9289 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9290 Opcode = Intrinsic::arm_neon_vpaddls; 9291 else 9292 Opcode = Intrinsic::arm_neon_vpaddlu; 9293 Ops.push_back(DAG.getConstant(Opcode, dl, 9294 TLI.getPointerTy(DAG.getDataLayout()))); 9295 EVT ElemTy = N00.getValueType().getVectorElementType(); 9296 unsigned NumElts = VT.getVectorNumElements(); 9297 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9298 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9299 N00.getOperand(0), N00.getOperand(1)); 9300 Ops.push_back(Concat); 9301 9302 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9303 } 9304 9305 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9306 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9307 // much easier to match. 9308 static SDValue 9309 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9310 TargetLowering::DAGCombinerInfo &DCI, 9311 const ARMSubtarget *Subtarget) { 9312 // Only perform optimization if after legalize, and if NEON is available. We 9313 // also expected both operands to be BUILD_VECTORs. 9314 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9315 || N0.getOpcode() != ISD::BUILD_VECTOR 9316 || N1.getOpcode() != ISD::BUILD_VECTOR) 9317 return SDValue(); 9318 9319 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9320 EVT VT = N->getValueType(0); 9321 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9322 return SDValue(); 9323 9324 // Check that the vector operands are of the right form. 9325 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9326 // operands, where N is the size of the formed vector. 9327 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9328 // index such that we have a pair wise add pattern. 9329 9330 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9331 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9332 return SDValue(); 9333 SDValue Vec = N0->getOperand(0)->getOperand(0); 9334 SDNode *V = Vec.getNode(); 9335 unsigned nextIndex = 0; 9336 9337 // For each operands to the ADD which are BUILD_VECTORs, 9338 // check to see if each of their operands are an EXTRACT_VECTOR with 9339 // the same vector and appropriate index. 9340 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9341 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9342 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9343 9344 SDValue ExtVec0 = N0->getOperand(i); 9345 SDValue ExtVec1 = N1->getOperand(i); 9346 9347 // First operand is the vector, verify its the same. 9348 if (V != ExtVec0->getOperand(0).getNode() || 9349 V != ExtVec1->getOperand(0).getNode()) 9350 return SDValue(); 9351 9352 // Second is the constant, verify its correct. 9353 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9354 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9355 9356 // For the constant, we want to see all the even or all the odd. 9357 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9358 || C1->getZExtValue() != nextIndex+1) 9359 return SDValue(); 9360 9361 // Increment index. 9362 nextIndex+=2; 9363 } else 9364 return SDValue(); 9365 } 9366 9367 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. 9368 if (Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9369 return SDValue(); 9370 9371 // Create VPADDL node. 9372 SelectionDAG &DAG = DCI.DAG; 9373 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9374 9375 SDLoc dl(N); 9376 9377 // Build operand list. 9378 SmallVector<SDValue, 8> Ops; 9379 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9380 TLI.getPointerTy(DAG.getDataLayout()))); 9381 9382 // Input is the vector. 9383 Ops.push_back(Vec); 9384 9385 // Get widened type and narrowed type. 9386 MVT widenType; 9387 unsigned numElem = VT.getVectorNumElements(); 9388 9389 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9390 switch (inputLaneType.getSimpleVT().SimpleTy) { 9391 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9392 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9393 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9394 default: 9395 llvm_unreachable("Invalid vector element type for padd optimization."); 9396 } 9397 9398 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9399 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9400 return DAG.getNode(ExtOp, dl, VT, tmp); 9401 } 9402 9403 static SDValue findMUL_LOHI(SDValue V) { 9404 if (V->getOpcode() == ISD::UMUL_LOHI || 9405 V->getOpcode() == ISD::SMUL_LOHI) 9406 return V; 9407 return SDValue(); 9408 } 9409 9410 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 9411 TargetLowering::DAGCombinerInfo &DCI, 9412 const ARMSubtarget *Subtarget) { 9413 // Look for multiply add opportunities. 9414 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 9415 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 9416 // a glue link from the first add to the second add. 9417 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 9418 // a S/UMLAL instruction. 9419 // UMUL_LOHI 9420 // / :lo \ :hi 9421 // / \ [no multiline comment] 9422 // loAdd -> ADDE | 9423 // \ :glue / 9424 // \ / 9425 // ADDC <- hiAdd 9426 // 9427 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 9428 SDValue AddcOp0 = AddcNode->getOperand(0); 9429 SDValue AddcOp1 = AddcNode->getOperand(1); 9430 9431 // Check if the two operands are from the same mul_lohi node. 9432 if (AddcOp0.getNode() == AddcOp1.getNode()) 9433 return SDValue(); 9434 9435 assert(AddcNode->getNumValues() == 2 && 9436 AddcNode->getValueType(0) == MVT::i32 && 9437 "Expect ADDC with two result values. First: i32"); 9438 9439 // Check that we have a glued ADDC node. 9440 if (AddcNode->getValueType(1) != MVT::Glue) 9441 return SDValue(); 9442 9443 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 9444 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 9445 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 9446 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 9447 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 9448 return SDValue(); 9449 9450 // Look for the glued ADDE. 9451 SDNode* AddeNode = AddcNode->getGluedUser(); 9452 if (!AddeNode) 9453 return SDValue(); 9454 9455 // Make sure it is really an ADDE. 9456 if (AddeNode->getOpcode() != ISD::ADDE) 9457 return SDValue(); 9458 9459 assert(AddeNode->getNumOperands() == 3 && 9460 AddeNode->getOperand(2).getValueType() == MVT::Glue && 9461 "ADDE node has the wrong inputs"); 9462 9463 // Check for the triangle shape. 9464 SDValue AddeOp0 = AddeNode->getOperand(0); 9465 SDValue AddeOp1 = AddeNode->getOperand(1); 9466 9467 // Make sure that the ADDE operands are not coming from the same node. 9468 if (AddeOp0.getNode() == AddeOp1.getNode()) 9469 return SDValue(); 9470 9471 // Find the MUL_LOHI node walking up ADDE's operands. 9472 bool IsLeftOperandMUL = false; 9473 SDValue MULOp = findMUL_LOHI(AddeOp0); 9474 if (MULOp == SDValue()) 9475 MULOp = findMUL_LOHI(AddeOp1); 9476 else 9477 IsLeftOperandMUL = true; 9478 if (MULOp == SDValue()) 9479 return SDValue(); 9480 9481 // Figure out the right opcode. 9482 unsigned Opc = MULOp->getOpcode(); 9483 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 9484 9485 // Figure out the high and low input values to the MLAL node. 9486 SDValue* HiAdd = nullptr; 9487 SDValue* LoMul = nullptr; 9488 SDValue* LowAdd = nullptr; 9489 9490 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 9491 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 9492 return SDValue(); 9493 9494 if (IsLeftOperandMUL) 9495 HiAdd = &AddeOp1; 9496 else 9497 HiAdd = &AddeOp0; 9498 9499 9500 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 9501 // whose low result is fed to the ADDC we are checking. 9502 9503 if (AddcOp0 == MULOp.getValue(0)) { 9504 LoMul = &AddcOp0; 9505 LowAdd = &AddcOp1; 9506 } 9507 if (AddcOp1 == MULOp.getValue(0)) { 9508 LoMul = &AddcOp1; 9509 LowAdd = &AddcOp0; 9510 } 9511 9512 if (!LoMul) 9513 return SDValue(); 9514 9515 // Create the merged node. 9516 SelectionDAG &DAG = DCI.DAG; 9517 9518 // Build operand list. 9519 SmallVector<SDValue, 8> Ops; 9520 Ops.push_back(LoMul->getOperand(0)); 9521 Ops.push_back(LoMul->getOperand(1)); 9522 Ops.push_back(*LowAdd); 9523 Ops.push_back(*HiAdd); 9524 9525 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 9526 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9527 9528 // Replace the ADDs' nodes uses by the MLA node's values. 9529 SDValue HiMLALResult(MLALNode.getNode(), 1); 9530 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9531 9532 SDValue LoMLALResult(MLALNode.getNode(), 0); 9533 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9534 9535 // Return original node to notify the driver to stop replacing. 9536 SDValue resNode(AddcNode, 0); 9537 return resNode; 9538 } 9539 9540 static SDValue AddCombineTo64bitUMAAL(SDNode *AddcNode, 9541 TargetLowering::DAGCombinerInfo &DCI, 9542 const ARMSubtarget *Subtarget) { 9543 // UMAAL is similar to UMLAL except that it adds two unsigned values. 9544 // While trying to combine for the other MLAL nodes, first search for the 9545 // chance to use UMAAL. Check if Addc uses another addc node which can first 9546 // be combined into a UMLAL. The other pattern is AddcNode being combined 9547 // into an UMLAL and then using another addc is handled in ISelDAGToDAG. 9548 9549 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP() || 9550 (Subtarget->isThumb() && !Subtarget->hasThumb2())) 9551 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9552 9553 SDNode *PrevAddc = nullptr; 9554 if (AddcNode->getOperand(0).getOpcode() == ISD::ADDC) 9555 PrevAddc = AddcNode->getOperand(0).getNode(); 9556 else if (AddcNode->getOperand(1).getOpcode() == ISD::ADDC) 9557 PrevAddc = AddcNode->getOperand(1).getNode(); 9558 9559 // If there's no addc chains, just return a search for any MLAL. 9560 if (PrevAddc == nullptr) 9561 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9562 9563 // Try to convert the addc operand to an MLAL and if that fails try to 9564 // combine AddcNode. 9565 SDValue MLAL = AddCombineTo64bitMLAL(PrevAddc, DCI, Subtarget); 9566 if (MLAL != SDValue(PrevAddc, 0)) 9567 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9568 9569 // Find the converted UMAAL or quit if it doesn't exist. 9570 SDNode *UmlalNode = nullptr; 9571 SDValue AddHi; 9572 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 9573 UmlalNode = AddcNode->getOperand(0).getNode(); 9574 AddHi = AddcNode->getOperand(1); 9575 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 9576 UmlalNode = AddcNode->getOperand(1).getNode(); 9577 AddHi = AddcNode->getOperand(0); 9578 } else { 9579 return SDValue(); 9580 } 9581 9582 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 9583 // the ADDC as well as Zero. 9584 auto *Zero = dyn_cast<ConstantSDNode>(UmlalNode->getOperand(3)); 9585 9586 if (!Zero || Zero->getZExtValue() != 0) 9587 return SDValue(); 9588 9589 // Check that we have a glued ADDC node. 9590 if (AddcNode->getValueType(1) != MVT::Glue) 9591 return SDValue(); 9592 9593 // Look for the glued ADDE. 9594 SDNode* AddeNode = AddcNode->getGluedUser(); 9595 if (!AddeNode) 9596 return SDValue(); 9597 9598 if ((AddeNode->getOperand(0).getNode() == Zero && 9599 AddeNode->getOperand(1).getNode() == UmlalNode) || 9600 (AddeNode->getOperand(0).getNode() == UmlalNode && 9601 AddeNode->getOperand(1).getNode() == Zero)) { 9602 9603 SelectionDAG &DAG = DCI.DAG; 9604 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 9605 UmlalNode->getOperand(2), AddHi }; 9606 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 9607 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9608 9609 // Replace the ADDs' nodes uses by the UMAAL node's values. 9610 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 9611 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 9612 9613 // Return original node to notify the driver to stop replacing. 9614 return SDValue(AddcNode, 0); 9615 } 9616 return SDValue(); 9617 } 9618 9619 /// PerformADDCCombine - Target-specific dag combine transform from 9620 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL or 9621 /// ISD::ADDC, ISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 9622 static SDValue PerformADDCCombine(SDNode *N, 9623 TargetLowering::DAGCombinerInfo &DCI, 9624 const ARMSubtarget *Subtarget) { 9625 if (Subtarget->isThumb1Only()) return SDValue(); 9626 9627 // Only perform the checks after legalize when the pattern is available. 9628 if (DCI.isBeforeLegalize()) return SDValue(); 9629 9630 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 9631 } 9632 9633 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 9634 /// operands N0 and N1. This is a helper for PerformADDCombine that is 9635 /// called with the default operands, and if that fails, with commuted 9636 /// operands. 9637 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 9638 TargetLowering::DAGCombinerInfo &DCI, 9639 const ARMSubtarget *Subtarget){ 9640 // Attempt to create vpadd for this add. 9641 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 9642 return Result; 9643 9644 // Attempt to create vpaddl for this add. 9645 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 9646 return Result; 9647 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 9648 Subtarget)) 9649 return Result; 9650 9651 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9652 if (N0.getNode()->hasOneUse()) 9653 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 9654 return Result; 9655 return SDValue(); 9656 } 9657 9658 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 9659 /// 9660 static SDValue PerformADDCombine(SDNode *N, 9661 TargetLowering::DAGCombinerInfo &DCI, 9662 const ARMSubtarget *Subtarget) { 9663 SDValue N0 = N->getOperand(0); 9664 SDValue N1 = N->getOperand(1); 9665 9666 // First try with the default operand order. 9667 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 9668 return Result; 9669 9670 // If that didn't work, try again with the operands commuted. 9671 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 9672 } 9673 9674 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 9675 /// 9676 static SDValue PerformSUBCombine(SDNode *N, 9677 TargetLowering::DAGCombinerInfo &DCI) { 9678 SDValue N0 = N->getOperand(0); 9679 SDValue N1 = N->getOperand(1); 9680 9681 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9682 if (N1.getNode()->hasOneUse()) 9683 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 9684 return Result; 9685 9686 return SDValue(); 9687 } 9688 9689 /// PerformVMULCombine 9690 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 9691 /// special multiplier accumulator forwarding. 9692 /// vmul d3, d0, d2 9693 /// vmla d3, d1, d2 9694 /// is faster than 9695 /// vadd d3, d0, d1 9696 /// vmul d3, d3, d2 9697 // However, for (A + B) * (A + B), 9698 // vadd d2, d0, d1 9699 // vmul d3, d0, d2 9700 // vmla d3, d1, d2 9701 // is slower than 9702 // vadd d2, d0, d1 9703 // vmul d3, d2, d2 9704 static SDValue PerformVMULCombine(SDNode *N, 9705 TargetLowering::DAGCombinerInfo &DCI, 9706 const ARMSubtarget *Subtarget) { 9707 if (!Subtarget->hasVMLxForwarding()) 9708 return SDValue(); 9709 9710 SelectionDAG &DAG = DCI.DAG; 9711 SDValue N0 = N->getOperand(0); 9712 SDValue N1 = N->getOperand(1); 9713 unsigned Opcode = N0.getOpcode(); 9714 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9715 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 9716 Opcode = N1.getOpcode(); 9717 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9718 Opcode != ISD::FADD && Opcode != ISD::FSUB) 9719 return SDValue(); 9720 std::swap(N0, N1); 9721 } 9722 9723 if (N0 == N1) 9724 return SDValue(); 9725 9726 EVT VT = N->getValueType(0); 9727 SDLoc DL(N); 9728 SDValue N00 = N0->getOperand(0); 9729 SDValue N01 = N0->getOperand(1); 9730 return DAG.getNode(Opcode, DL, VT, 9731 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 9732 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 9733 } 9734 9735 static SDValue PerformMULCombine(SDNode *N, 9736 TargetLowering::DAGCombinerInfo &DCI, 9737 const ARMSubtarget *Subtarget) { 9738 SelectionDAG &DAG = DCI.DAG; 9739 9740 if (Subtarget->isThumb1Only()) 9741 return SDValue(); 9742 9743 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9744 return SDValue(); 9745 9746 EVT VT = N->getValueType(0); 9747 if (VT.is64BitVector() || VT.is128BitVector()) 9748 return PerformVMULCombine(N, DCI, Subtarget); 9749 if (VT != MVT::i32) 9750 return SDValue(); 9751 9752 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9753 if (!C) 9754 return SDValue(); 9755 9756 int64_t MulAmt = C->getSExtValue(); 9757 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 9758 9759 ShiftAmt = ShiftAmt & (32 - 1); 9760 SDValue V = N->getOperand(0); 9761 SDLoc DL(N); 9762 9763 SDValue Res; 9764 MulAmt >>= ShiftAmt; 9765 9766 if (MulAmt >= 0) { 9767 if (isPowerOf2_32(MulAmt - 1)) { 9768 // (mul x, 2^N + 1) => (add (shl x, N), x) 9769 Res = DAG.getNode(ISD::ADD, DL, VT, 9770 V, 9771 DAG.getNode(ISD::SHL, DL, VT, 9772 V, 9773 DAG.getConstant(Log2_32(MulAmt - 1), DL, 9774 MVT::i32))); 9775 } else if (isPowerOf2_32(MulAmt + 1)) { 9776 // (mul x, 2^N - 1) => (sub (shl x, N), x) 9777 Res = DAG.getNode(ISD::SUB, DL, VT, 9778 DAG.getNode(ISD::SHL, DL, VT, 9779 V, 9780 DAG.getConstant(Log2_32(MulAmt + 1), DL, 9781 MVT::i32)), 9782 V); 9783 } else 9784 return SDValue(); 9785 } else { 9786 uint64_t MulAmtAbs = -MulAmt; 9787 if (isPowerOf2_32(MulAmtAbs + 1)) { 9788 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 9789 Res = DAG.getNode(ISD::SUB, DL, VT, 9790 V, 9791 DAG.getNode(ISD::SHL, DL, VT, 9792 V, 9793 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 9794 MVT::i32))); 9795 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 9796 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 9797 Res = DAG.getNode(ISD::ADD, DL, VT, 9798 V, 9799 DAG.getNode(ISD::SHL, DL, VT, 9800 V, 9801 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 9802 MVT::i32))); 9803 Res = DAG.getNode(ISD::SUB, DL, VT, 9804 DAG.getConstant(0, DL, MVT::i32), Res); 9805 9806 } else 9807 return SDValue(); 9808 } 9809 9810 if (ShiftAmt != 0) 9811 Res = DAG.getNode(ISD::SHL, DL, VT, 9812 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 9813 9814 // Do not add new nodes to DAG combiner worklist. 9815 DCI.CombineTo(N, Res, false); 9816 return SDValue(); 9817 } 9818 9819 static SDValue PerformANDCombine(SDNode *N, 9820 TargetLowering::DAGCombinerInfo &DCI, 9821 const ARMSubtarget *Subtarget) { 9822 // Attempt to use immediate-form VBIC 9823 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9824 SDLoc dl(N); 9825 EVT VT = N->getValueType(0); 9826 SelectionDAG &DAG = DCI.DAG; 9827 9828 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9829 return SDValue(); 9830 9831 APInt SplatBits, SplatUndef; 9832 unsigned SplatBitSize; 9833 bool HasAnyUndefs; 9834 if (BVN && 9835 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9836 if (SplatBitSize <= 64) { 9837 EVT VbicVT; 9838 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 9839 SplatUndef.getZExtValue(), SplatBitSize, 9840 DAG, dl, VbicVT, VT.is128BitVector(), 9841 OtherModImm); 9842 if (Val.getNode()) { 9843 SDValue Input = 9844 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 9845 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 9846 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 9847 } 9848 } 9849 } 9850 9851 if (!Subtarget->isThumb1Only()) { 9852 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 9853 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 9854 return Result; 9855 } 9856 9857 return SDValue(); 9858 } 9859 9860 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 9861 static SDValue PerformORCombine(SDNode *N, 9862 TargetLowering::DAGCombinerInfo &DCI, 9863 const ARMSubtarget *Subtarget) { 9864 // Attempt to use immediate-form VORR 9865 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9866 SDLoc dl(N); 9867 EVT VT = N->getValueType(0); 9868 SelectionDAG &DAG = DCI.DAG; 9869 9870 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9871 return SDValue(); 9872 9873 APInt SplatBits, SplatUndef; 9874 unsigned SplatBitSize; 9875 bool HasAnyUndefs; 9876 if (BVN && Subtarget->hasNEON() && 9877 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9878 if (SplatBitSize <= 64) { 9879 EVT VorrVT; 9880 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 9881 SplatUndef.getZExtValue(), SplatBitSize, 9882 DAG, dl, VorrVT, VT.is128BitVector(), 9883 OtherModImm); 9884 if (Val.getNode()) { 9885 SDValue Input = 9886 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 9887 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 9888 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 9889 } 9890 } 9891 } 9892 9893 if (!Subtarget->isThumb1Only()) { 9894 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9895 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9896 return Result; 9897 } 9898 9899 // The code below optimizes (or (and X, Y), Z). 9900 // The AND operand needs to have a single user to make these optimizations 9901 // profitable. 9902 SDValue N0 = N->getOperand(0); 9903 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 9904 return SDValue(); 9905 SDValue N1 = N->getOperand(1); 9906 9907 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 9908 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 9909 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 9910 APInt SplatUndef; 9911 unsigned SplatBitSize; 9912 bool HasAnyUndefs; 9913 9914 APInt SplatBits0, SplatBits1; 9915 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 9916 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 9917 // Ensure that the second operand of both ands are constants 9918 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 9919 HasAnyUndefs) && !HasAnyUndefs) { 9920 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 9921 HasAnyUndefs) && !HasAnyUndefs) { 9922 // Ensure that the bit width of the constants are the same and that 9923 // the splat arguments are logical inverses as per the pattern we 9924 // are trying to simplify. 9925 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 9926 SplatBits0 == ~SplatBits1) { 9927 // Canonicalize the vector type to make instruction selection 9928 // simpler. 9929 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 9930 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 9931 N0->getOperand(1), 9932 N0->getOperand(0), 9933 N1->getOperand(0)); 9934 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9935 } 9936 } 9937 } 9938 } 9939 9940 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 9941 // reasonable. 9942 9943 // BFI is only available on V6T2+ 9944 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 9945 return SDValue(); 9946 9947 SDLoc DL(N); 9948 // 1) or (and A, mask), val => ARMbfi A, val, mask 9949 // iff (val & mask) == val 9950 // 9951 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9952 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 9953 // && mask == ~mask2 9954 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 9955 // && ~mask == mask2 9956 // (i.e., copy a bitfield value into another bitfield of the same width) 9957 9958 if (VT != MVT::i32) 9959 return SDValue(); 9960 9961 SDValue N00 = N0.getOperand(0); 9962 9963 // The value and the mask need to be constants so we can verify this is 9964 // actually a bitfield set. If the mask is 0xffff, we can do better 9965 // via a movt instruction, so don't use BFI in that case. 9966 SDValue MaskOp = N0.getOperand(1); 9967 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 9968 if (!MaskC) 9969 return SDValue(); 9970 unsigned Mask = MaskC->getZExtValue(); 9971 if (Mask == 0xffff) 9972 return SDValue(); 9973 SDValue Res; 9974 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 9975 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 9976 if (N1C) { 9977 unsigned Val = N1C->getZExtValue(); 9978 if ((Val & ~Mask) != Val) 9979 return SDValue(); 9980 9981 if (ARM::isBitFieldInvertedMask(Mask)) { 9982 Val >>= countTrailingZeros(~Mask); 9983 9984 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 9985 DAG.getConstant(Val, DL, MVT::i32), 9986 DAG.getConstant(Mask, DL, MVT::i32)); 9987 9988 // Do not add new nodes to DAG combiner worklist. 9989 DCI.CombineTo(N, Res, false); 9990 return SDValue(); 9991 } 9992 } else if (N1.getOpcode() == ISD::AND) { 9993 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9994 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 9995 if (!N11C) 9996 return SDValue(); 9997 unsigned Mask2 = N11C->getZExtValue(); 9998 9999 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10000 // as is to match. 10001 if (ARM::isBitFieldInvertedMask(Mask) && 10002 (Mask == ~Mask2)) { 10003 // The pack halfword instruction works better for masks that fit it, 10004 // so use that when it's available. 10005 if (Subtarget->hasT2ExtractPack() && 10006 (Mask == 0xffff || Mask == 0xffff0000)) 10007 return SDValue(); 10008 // 2a 10009 unsigned amt = countTrailingZeros(Mask2); 10010 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10011 DAG.getConstant(amt, DL, MVT::i32)); 10012 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10013 DAG.getConstant(Mask, DL, MVT::i32)); 10014 // Do not add new nodes to DAG combiner worklist. 10015 DCI.CombineTo(N, Res, false); 10016 return SDValue(); 10017 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10018 (~Mask == Mask2)) { 10019 // The pack halfword instruction works better for masks that fit it, 10020 // so use that when it's available. 10021 if (Subtarget->hasT2ExtractPack() && 10022 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10023 return SDValue(); 10024 // 2b 10025 unsigned lsb = countTrailingZeros(Mask); 10026 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10027 DAG.getConstant(lsb, DL, MVT::i32)); 10028 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10029 DAG.getConstant(Mask2, DL, MVT::i32)); 10030 // Do not add new nodes to DAG combiner worklist. 10031 DCI.CombineTo(N, Res, false); 10032 return SDValue(); 10033 } 10034 } 10035 10036 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10037 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10038 ARM::isBitFieldInvertedMask(~Mask)) { 10039 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10040 // where lsb(mask) == #shamt and masked bits of B are known zero. 10041 SDValue ShAmt = N00.getOperand(1); 10042 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10043 unsigned LSB = countTrailingZeros(Mask); 10044 if (ShAmtC != LSB) 10045 return SDValue(); 10046 10047 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10048 DAG.getConstant(~Mask, DL, MVT::i32)); 10049 10050 // Do not add new nodes to DAG combiner worklist. 10051 DCI.CombineTo(N, Res, false); 10052 } 10053 10054 return SDValue(); 10055 } 10056 10057 static SDValue PerformXORCombine(SDNode *N, 10058 TargetLowering::DAGCombinerInfo &DCI, 10059 const ARMSubtarget *Subtarget) { 10060 EVT VT = N->getValueType(0); 10061 SelectionDAG &DAG = DCI.DAG; 10062 10063 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10064 return SDValue(); 10065 10066 if (!Subtarget->isThumb1Only()) { 10067 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10068 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10069 return Result; 10070 } 10071 10072 return SDValue(); 10073 } 10074 10075 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 10076 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 10077 // their position in "to" (Rd). 10078 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 10079 assert(N->getOpcode() == ARMISD::BFI); 10080 10081 SDValue From = N->getOperand(1); 10082 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 10083 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 10084 10085 // If the Base came from a SHR #C, we can deduce that it is really testing bit 10086 // #C in the base of the SHR. 10087 if (From->getOpcode() == ISD::SRL && 10088 isa<ConstantSDNode>(From->getOperand(1))) { 10089 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 10090 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 10091 FromMask <<= Shift.getLimitedValue(31); 10092 From = From->getOperand(0); 10093 } 10094 10095 return From; 10096 } 10097 10098 // If A and B contain one contiguous set of bits, does A | B == A . B? 10099 // 10100 // Neither A nor B must be zero. 10101 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 10102 unsigned LastActiveBitInA = A.countTrailingZeros(); 10103 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 10104 return LastActiveBitInA - 1 == FirstActiveBitInB; 10105 } 10106 10107 static SDValue FindBFIToCombineWith(SDNode *N) { 10108 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 10109 // if one exists. 10110 APInt ToMask, FromMask; 10111 SDValue From = ParseBFI(N, ToMask, FromMask); 10112 SDValue To = N->getOperand(0); 10113 10114 // Now check for a compatible BFI to merge with. We can pass through BFIs that 10115 // aren't compatible, but not if they set the same bit in their destination as 10116 // we do (or that of any BFI we're going to combine with). 10117 SDValue V = To; 10118 APInt CombinedToMask = ToMask; 10119 while (V.getOpcode() == ARMISD::BFI) { 10120 APInt NewToMask, NewFromMask; 10121 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 10122 if (NewFrom != From) { 10123 // This BFI has a different base. Keep going. 10124 CombinedToMask |= NewToMask; 10125 V = V.getOperand(0); 10126 continue; 10127 } 10128 10129 // Do the written bits conflict with any we've seen so far? 10130 if ((NewToMask & CombinedToMask).getBoolValue()) 10131 // Conflicting bits - bail out because going further is unsafe. 10132 return SDValue(); 10133 10134 // Are the new bits contiguous when combined with the old bits? 10135 if (BitsProperlyConcatenate(ToMask, NewToMask) && 10136 BitsProperlyConcatenate(FromMask, NewFromMask)) 10137 return V; 10138 if (BitsProperlyConcatenate(NewToMask, ToMask) && 10139 BitsProperlyConcatenate(NewFromMask, FromMask)) 10140 return V; 10141 10142 // We've seen a write to some bits, so track it. 10143 CombinedToMask |= NewToMask; 10144 // Keep going... 10145 V = V.getOperand(0); 10146 } 10147 10148 return SDValue(); 10149 } 10150 10151 static SDValue PerformBFICombine(SDNode *N, 10152 TargetLowering::DAGCombinerInfo &DCI) { 10153 SDValue N1 = N->getOperand(1); 10154 if (N1.getOpcode() == ISD::AND) { 10155 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 10156 // the bits being cleared by the AND are not demanded by the BFI. 10157 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10158 if (!N11C) 10159 return SDValue(); 10160 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 10161 unsigned LSB = countTrailingZeros(~InvMask); 10162 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 10163 assert(Width < 10164 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 10165 "undefined behavior"); 10166 unsigned Mask = (1u << Width) - 1; 10167 unsigned Mask2 = N11C->getZExtValue(); 10168 if ((Mask & (~Mask2)) == 0) 10169 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 10170 N->getOperand(0), N1.getOperand(0), 10171 N->getOperand(2)); 10172 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 10173 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 10174 // Keep track of any consecutive bits set that all come from the same base 10175 // value. We can combine these together into a single BFI. 10176 SDValue CombineBFI = FindBFIToCombineWith(N); 10177 if (CombineBFI == SDValue()) 10178 return SDValue(); 10179 10180 // We've found a BFI. 10181 APInt ToMask1, FromMask1; 10182 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 10183 10184 APInt ToMask2, FromMask2; 10185 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 10186 assert(From1 == From2); 10187 (void)From2; 10188 10189 // First, unlink CombineBFI. 10190 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 10191 // Then create a new BFI, combining the two together. 10192 APInt NewFromMask = FromMask1 | FromMask2; 10193 APInt NewToMask = ToMask1 | ToMask2; 10194 10195 EVT VT = N->getValueType(0); 10196 SDLoc dl(N); 10197 10198 if (NewFromMask[0] == 0) 10199 From1 = DCI.DAG.getNode( 10200 ISD::SRL, dl, VT, From1, 10201 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 10202 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 10203 DCI.DAG.getConstant(~NewToMask, dl, VT)); 10204 } 10205 return SDValue(); 10206 } 10207 10208 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 10209 /// ARMISD::VMOVRRD. 10210 static SDValue PerformVMOVRRDCombine(SDNode *N, 10211 TargetLowering::DAGCombinerInfo &DCI, 10212 const ARMSubtarget *Subtarget) { 10213 // vmovrrd(vmovdrr x, y) -> x,y 10214 SDValue InDouble = N->getOperand(0); 10215 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 10216 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 10217 10218 // vmovrrd(load f64) -> (load i32), (load i32) 10219 SDNode *InNode = InDouble.getNode(); 10220 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 10221 InNode->getValueType(0) == MVT::f64 && 10222 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 10223 !cast<LoadSDNode>(InNode)->isVolatile()) { 10224 // TODO: Should this be done for non-FrameIndex operands? 10225 LoadSDNode *LD = cast<LoadSDNode>(InNode); 10226 10227 SelectionDAG &DAG = DCI.DAG; 10228 SDLoc DL(LD); 10229 SDValue BasePtr = LD->getBasePtr(); 10230 SDValue NewLD1 = 10231 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 10232 LD->getAlignment(), LD->getMemOperand()->getFlags()); 10233 10234 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10235 DAG.getConstant(4, DL, MVT::i32)); 10236 SDValue NewLD2 = DAG.getLoad( 10237 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 10238 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 10239 10240 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 10241 if (DCI.DAG.getDataLayout().isBigEndian()) 10242 std::swap (NewLD1, NewLD2); 10243 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 10244 return Result; 10245 } 10246 10247 return SDValue(); 10248 } 10249 10250 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 10251 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 10252 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 10253 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 10254 SDValue Op0 = N->getOperand(0); 10255 SDValue Op1 = N->getOperand(1); 10256 if (Op0.getOpcode() == ISD::BITCAST) 10257 Op0 = Op0.getOperand(0); 10258 if (Op1.getOpcode() == ISD::BITCAST) 10259 Op1 = Op1.getOperand(0); 10260 if (Op0.getOpcode() == ARMISD::VMOVRRD && 10261 Op0.getNode() == Op1.getNode() && 10262 Op0.getResNo() == 0 && Op1.getResNo() == 1) 10263 return DAG.getNode(ISD::BITCAST, SDLoc(N), 10264 N->getValueType(0), Op0.getOperand(0)); 10265 return SDValue(); 10266 } 10267 10268 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 10269 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 10270 /// i64 vector to have f64 elements, since the value can then be loaded 10271 /// directly into a VFP register. 10272 static bool hasNormalLoadOperand(SDNode *N) { 10273 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 10274 for (unsigned i = 0; i < NumElts; ++i) { 10275 SDNode *Elt = N->getOperand(i).getNode(); 10276 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 10277 return true; 10278 } 10279 return false; 10280 } 10281 10282 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 10283 /// ISD::BUILD_VECTOR. 10284 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 10285 TargetLowering::DAGCombinerInfo &DCI, 10286 const ARMSubtarget *Subtarget) { 10287 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 10288 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 10289 // into a pair of GPRs, which is fine when the value is used as a scalar, 10290 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 10291 SelectionDAG &DAG = DCI.DAG; 10292 if (N->getNumOperands() == 2) 10293 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 10294 return RV; 10295 10296 // Load i64 elements as f64 values so that type legalization does not split 10297 // them up into i32 values. 10298 EVT VT = N->getValueType(0); 10299 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 10300 return SDValue(); 10301 SDLoc dl(N); 10302 SmallVector<SDValue, 8> Ops; 10303 unsigned NumElts = VT.getVectorNumElements(); 10304 for (unsigned i = 0; i < NumElts; ++i) { 10305 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 10306 Ops.push_back(V); 10307 // Make the DAGCombiner fold the bitcast. 10308 DCI.AddToWorklist(V.getNode()); 10309 } 10310 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 10311 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 10312 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 10313 } 10314 10315 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 10316 static SDValue 10317 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10318 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 10319 // At that time, we may have inserted bitcasts from integer to float. 10320 // If these bitcasts have survived DAGCombine, change the lowering of this 10321 // BUILD_VECTOR in something more vector friendly, i.e., that does not 10322 // force to use floating point types. 10323 10324 // Make sure we can change the type of the vector. 10325 // This is possible iff: 10326 // 1. The vector is only used in a bitcast to a integer type. I.e., 10327 // 1.1. Vector is used only once. 10328 // 1.2. Use is a bit convert to an integer type. 10329 // 2. The size of its operands are 32-bits (64-bits are not legal). 10330 EVT VT = N->getValueType(0); 10331 EVT EltVT = VT.getVectorElementType(); 10332 10333 // Check 1.1. and 2. 10334 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 10335 return SDValue(); 10336 10337 // By construction, the input type must be float. 10338 assert(EltVT == MVT::f32 && "Unexpected type!"); 10339 10340 // Check 1.2. 10341 SDNode *Use = *N->use_begin(); 10342 if (Use->getOpcode() != ISD::BITCAST || 10343 Use->getValueType(0).isFloatingPoint()) 10344 return SDValue(); 10345 10346 // Check profitability. 10347 // Model is, if more than half of the relevant operands are bitcast from 10348 // i32, turn the build_vector into a sequence of insert_vector_elt. 10349 // Relevant operands are everything that is not statically 10350 // (i.e., at compile time) bitcasted. 10351 unsigned NumOfBitCastedElts = 0; 10352 unsigned NumElts = VT.getVectorNumElements(); 10353 unsigned NumOfRelevantElts = NumElts; 10354 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 10355 SDValue Elt = N->getOperand(Idx); 10356 if (Elt->getOpcode() == ISD::BITCAST) { 10357 // Assume only bit cast to i32 will go away. 10358 if (Elt->getOperand(0).getValueType() == MVT::i32) 10359 ++NumOfBitCastedElts; 10360 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 10361 // Constants are statically casted, thus do not count them as 10362 // relevant operands. 10363 --NumOfRelevantElts; 10364 } 10365 10366 // Check if more than half of the elements require a non-free bitcast. 10367 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 10368 return SDValue(); 10369 10370 SelectionDAG &DAG = DCI.DAG; 10371 // Create the new vector type. 10372 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 10373 // Check if the type is legal. 10374 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10375 if (!TLI.isTypeLegal(VecVT)) 10376 return SDValue(); 10377 10378 // Combine: 10379 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 10380 // => BITCAST INSERT_VECTOR_ELT 10381 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 10382 // (BITCAST EN), N. 10383 SDValue Vec = DAG.getUNDEF(VecVT); 10384 SDLoc dl(N); 10385 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 10386 SDValue V = N->getOperand(Idx); 10387 if (V.isUndef()) 10388 continue; 10389 if (V.getOpcode() == ISD::BITCAST && 10390 V->getOperand(0).getValueType() == MVT::i32) 10391 // Fold obvious case. 10392 V = V.getOperand(0); 10393 else { 10394 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 10395 // Make the DAGCombiner fold the bitcasts. 10396 DCI.AddToWorklist(V.getNode()); 10397 } 10398 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 10399 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 10400 } 10401 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 10402 // Make the DAGCombiner fold the bitcasts. 10403 DCI.AddToWorklist(Vec.getNode()); 10404 return Vec; 10405 } 10406 10407 /// PerformInsertEltCombine - Target-specific dag combine xforms for 10408 /// ISD::INSERT_VECTOR_ELT. 10409 static SDValue PerformInsertEltCombine(SDNode *N, 10410 TargetLowering::DAGCombinerInfo &DCI) { 10411 // Bitcast an i64 load inserted into a vector to f64. 10412 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10413 EVT VT = N->getValueType(0); 10414 SDNode *Elt = N->getOperand(1).getNode(); 10415 if (VT.getVectorElementType() != MVT::i64 || 10416 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 10417 return SDValue(); 10418 10419 SelectionDAG &DAG = DCI.DAG; 10420 SDLoc dl(N); 10421 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10422 VT.getVectorNumElements()); 10423 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 10424 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 10425 // Make the DAGCombiner fold the bitcasts. 10426 DCI.AddToWorklist(Vec.getNode()); 10427 DCI.AddToWorklist(V.getNode()); 10428 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 10429 Vec, V, N->getOperand(2)); 10430 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 10431 } 10432 10433 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 10434 /// ISD::VECTOR_SHUFFLE. 10435 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 10436 // The LLVM shufflevector instruction does not require the shuffle mask 10437 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 10438 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 10439 // operands do not match the mask length, they are extended by concatenating 10440 // them with undef vectors. That is probably the right thing for other 10441 // targets, but for NEON it is better to concatenate two double-register 10442 // size vector operands into a single quad-register size vector. Do that 10443 // transformation here: 10444 // shuffle(concat(v1, undef), concat(v2, undef)) -> 10445 // shuffle(concat(v1, v2), undef) 10446 SDValue Op0 = N->getOperand(0); 10447 SDValue Op1 = N->getOperand(1); 10448 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 10449 Op1.getOpcode() != ISD::CONCAT_VECTORS || 10450 Op0.getNumOperands() != 2 || 10451 Op1.getNumOperands() != 2) 10452 return SDValue(); 10453 SDValue Concat0Op1 = Op0.getOperand(1); 10454 SDValue Concat1Op1 = Op1.getOperand(1); 10455 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 10456 return SDValue(); 10457 // Skip the transformation if any of the types are illegal. 10458 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10459 EVT VT = N->getValueType(0); 10460 if (!TLI.isTypeLegal(VT) || 10461 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 10462 !TLI.isTypeLegal(Concat1Op1.getValueType())) 10463 return SDValue(); 10464 10465 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10466 Op0.getOperand(0), Op1.getOperand(0)); 10467 // Translate the shuffle mask. 10468 SmallVector<int, 16> NewMask; 10469 unsigned NumElts = VT.getVectorNumElements(); 10470 unsigned HalfElts = NumElts/2; 10471 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10472 for (unsigned n = 0; n < NumElts; ++n) { 10473 int MaskElt = SVN->getMaskElt(n); 10474 int NewElt = -1; 10475 if (MaskElt < (int)HalfElts) 10476 NewElt = MaskElt; 10477 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 10478 NewElt = HalfElts + MaskElt - NumElts; 10479 NewMask.push_back(NewElt); 10480 } 10481 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 10482 DAG.getUNDEF(VT), NewMask); 10483 } 10484 10485 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 10486 /// NEON load/store intrinsics, and generic vector load/stores, to merge 10487 /// base address updates. 10488 /// For generic load/stores, the memory type is assumed to be a vector. 10489 /// The caller is assumed to have checked legality. 10490 static SDValue CombineBaseUpdate(SDNode *N, 10491 TargetLowering::DAGCombinerInfo &DCI) { 10492 SelectionDAG &DAG = DCI.DAG; 10493 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 10494 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 10495 const bool isStore = N->getOpcode() == ISD::STORE; 10496 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 10497 SDValue Addr = N->getOperand(AddrOpIdx); 10498 MemSDNode *MemN = cast<MemSDNode>(N); 10499 SDLoc dl(N); 10500 10501 // Search for a use of the address operand that is an increment. 10502 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 10503 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 10504 SDNode *User = *UI; 10505 if (User->getOpcode() != ISD::ADD || 10506 UI.getUse().getResNo() != Addr.getResNo()) 10507 continue; 10508 10509 // Check that the add is independent of the load/store. Otherwise, folding 10510 // it would create a cycle. 10511 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 10512 continue; 10513 10514 // Find the new opcode for the updating load/store. 10515 bool isLoadOp = true; 10516 bool isLaneOp = false; 10517 unsigned NewOpc = 0; 10518 unsigned NumVecs = 0; 10519 if (isIntrinsic) { 10520 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10521 switch (IntNo) { 10522 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 10523 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 10524 NumVecs = 1; break; 10525 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 10526 NumVecs = 2; break; 10527 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 10528 NumVecs = 3; break; 10529 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 10530 NumVecs = 4; break; 10531 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 10532 NumVecs = 2; isLaneOp = true; break; 10533 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 10534 NumVecs = 3; isLaneOp = true; break; 10535 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 10536 NumVecs = 4; isLaneOp = true; break; 10537 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 10538 NumVecs = 1; isLoadOp = false; break; 10539 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 10540 NumVecs = 2; isLoadOp = false; break; 10541 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 10542 NumVecs = 3; isLoadOp = false; break; 10543 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 10544 NumVecs = 4; isLoadOp = false; break; 10545 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 10546 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 10547 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 10548 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 10549 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 10550 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 10551 } 10552 } else { 10553 isLaneOp = true; 10554 switch (N->getOpcode()) { 10555 default: llvm_unreachable("unexpected opcode for Neon base update"); 10556 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 10557 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 10558 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 10559 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 10560 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 10561 NumVecs = 1; isLaneOp = false; break; 10562 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 10563 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 10564 } 10565 } 10566 10567 // Find the size of memory referenced by the load/store. 10568 EVT VecTy; 10569 if (isLoadOp) { 10570 VecTy = N->getValueType(0); 10571 } else if (isIntrinsic) { 10572 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 10573 } else { 10574 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 10575 VecTy = N->getOperand(1).getValueType(); 10576 } 10577 10578 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 10579 if (isLaneOp) 10580 NumBytes /= VecTy.getVectorNumElements(); 10581 10582 // If the increment is a constant, it must match the memory ref size. 10583 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 10584 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 10585 uint64_t IncVal = CInc->getZExtValue(); 10586 if (IncVal != NumBytes) 10587 continue; 10588 } else if (NumBytes >= 3 * 16) { 10589 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 10590 // separate instructions that make it harder to use a non-constant update. 10591 continue; 10592 } 10593 10594 // OK, we found an ADD we can fold into the base update. 10595 // Now, create a _UPD node, taking care of not breaking alignment. 10596 10597 EVT AlignedVecTy = VecTy; 10598 unsigned Alignment = MemN->getAlignment(); 10599 10600 // If this is a less-than-standard-aligned load/store, change the type to 10601 // match the standard alignment. 10602 // The alignment is overlooked when selecting _UPD variants; and it's 10603 // easier to introduce bitcasts here than fix that. 10604 // There are 3 ways to get to this base-update combine: 10605 // - intrinsics: they are assumed to be properly aligned (to the standard 10606 // alignment of the memory type), so we don't need to do anything. 10607 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 10608 // intrinsics, so, likewise, there's nothing to do. 10609 // - generic load/store instructions: the alignment is specified as an 10610 // explicit operand, rather than implicitly as the standard alignment 10611 // of the memory type (like the intrisics). We need to change the 10612 // memory type to match the explicit alignment. That way, we don't 10613 // generate non-standard-aligned ARMISD::VLDx nodes. 10614 if (isa<LSBaseSDNode>(N)) { 10615 if (Alignment == 0) 10616 Alignment = 1; 10617 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 10618 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 10619 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 10620 assert(!isLaneOp && "Unexpected generic load/store lane."); 10621 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 10622 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 10623 } 10624 // Don't set an explicit alignment on regular load/stores that we want 10625 // to transform to VLD/VST 1_UPD nodes. 10626 // This matches the behavior of regular load/stores, which only get an 10627 // explicit alignment if the MMO alignment is larger than the standard 10628 // alignment of the memory type. 10629 // Intrinsics, however, always get an explicit alignment, set to the 10630 // alignment of the MMO. 10631 Alignment = 1; 10632 } 10633 10634 // Create the new updating load/store node. 10635 // First, create an SDVTList for the new updating node's results. 10636 EVT Tys[6]; 10637 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 10638 unsigned n; 10639 for (n = 0; n < NumResultVecs; ++n) 10640 Tys[n] = AlignedVecTy; 10641 Tys[n++] = MVT::i32; 10642 Tys[n] = MVT::Other; 10643 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 10644 10645 // Then, gather the new node's operands. 10646 SmallVector<SDValue, 8> Ops; 10647 Ops.push_back(N->getOperand(0)); // incoming chain 10648 Ops.push_back(N->getOperand(AddrOpIdx)); 10649 Ops.push_back(Inc); 10650 10651 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 10652 // Try to match the intrinsic's signature 10653 Ops.push_back(StN->getValue()); 10654 } else { 10655 // Loads (and of course intrinsics) match the intrinsics' signature, 10656 // so just add all but the alignment operand. 10657 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 10658 Ops.push_back(N->getOperand(i)); 10659 } 10660 10661 // For all node types, the alignment operand is always the last one. 10662 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 10663 10664 // If this is a non-standard-aligned STORE, the penultimate operand is the 10665 // stored value. Bitcast it to the aligned type. 10666 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 10667 SDValue &StVal = Ops[Ops.size()-2]; 10668 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 10669 } 10670 10671 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 10672 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 10673 MemN->getMemOperand()); 10674 10675 // Update the uses. 10676 SmallVector<SDValue, 5> NewResults; 10677 for (unsigned i = 0; i < NumResultVecs; ++i) 10678 NewResults.push_back(SDValue(UpdN.getNode(), i)); 10679 10680 // If this is an non-standard-aligned LOAD, the first result is the loaded 10681 // value. Bitcast it to the expected result type. 10682 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 10683 SDValue &LdVal = NewResults[0]; 10684 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 10685 } 10686 10687 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 10688 DCI.CombineTo(N, NewResults); 10689 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 10690 10691 break; 10692 } 10693 return SDValue(); 10694 } 10695 10696 static SDValue PerformVLDCombine(SDNode *N, 10697 TargetLowering::DAGCombinerInfo &DCI) { 10698 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10699 return SDValue(); 10700 10701 return CombineBaseUpdate(N, DCI); 10702 } 10703 10704 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 10705 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 10706 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 10707 /// return true. 10708 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10709 SelectionDAG &DAG = DCI.DAG; 10710 EVT VT = N->getValueType(0); 10711 // vldN-dup instructions only support 64-bit vectors for N > 1. 10712 if (!VT.is64BitVector()) 10713 return false; 10714 10715 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 10716 SDNode *VLD = N->getOperand(0).getNode(); 10717 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 10718 return false; 10719 unsigned NumVecs = 0; 10720 unsigned NewOpc = 0; 10721 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 10722 if (IntNo == Intrinsic::arm_neon_vld2lane) { 10723 NumVecs = 2; 10724 NewOpc = ARMISD::VLD2DUP; 10725 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 10726 NumVecs = 3; 10727 NewOpc = ARMISD::VLD3DUP; 10728 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 10729 NumVecs = 4; 10730 NewOpc = ARMISD::VLD4DUP; 10731 } else { 10732 return false; 10733 } 10734 10735 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 10736 // numbers match the load. 10737 unsigned VLDLaneNo = 10738 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 10739 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 10740 UI != UE; ++UI) { 10741 // Ignore uses of the chain result. 10742 if (UI.getUse().getResNo() == NumVecs) 10743 continue; 10744 SDNode *User = *UI; 10745 if (User->getOpcode() != ARMISD::VDUPLANE || 10746 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 10747 return false; 10748 } 10749 10750 // Create the vldN-dup node. 10751 EVT Tys[5]; 10752 unsigned n; 10753 for (n = 0; n < NumVecs; ++n) 10754 Tys[n] = VT; 10755 Tys[n] = MVT::Other; 10756 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 10757 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 10758 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 10759 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 10760 Ops, VLDMemInt->getMemoryVT(), 10761 VLDMemInt->getMemOperand()); 10762 10763 // Update the uses. 10764 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 10765 UI != UE; ++UI) { 10766 unsigned ResNo = UI.getUse().getResNo(); 10767 // Ignore uses of the chain result. 10768 if (ResNo == NumVecs) 10769 continue; 10770 SDNode *User = *UI; 10771 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 10772 } 10773 10774 // Now the vldN-lane intrinsic is dead except for its chain result. 10775 // Update uses of the chain. 10776 std::vector<SDValue> VLDDupResults; 10777 for (unsigned n = 0; n < NumVecs; ++n) 10778 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 10779 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 10780 DCI.CombineTo(VLD, VLDDupResults); 10781 10782 return true; 10783 } 10784 10785 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 10786 /// ARMISD::VDUPLANE. 10787 static SDValue PerformVDUPLANECombine(SDNode *N, 10788 TargetLowering::DAGCombinerInfo &DCI) { 10789 SDValue Op = N->getOperand(0); 10790 10791 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 10792 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 10793 if (CombineVLDDUP(N, DCI)) 10794 return SDValue(N, 0); 10795 10796 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 10797 // redundant. Ignore bit_converts for now; element sizes are checked below. 10798 while (Op.getOpcode() == ISD::BITCAST) 10799 Op = Op.getOperand(0); 10800 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 10801 return SDValue(); 10802 10803 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 10804 unsigned EltSize = Op.getScalarValueSizeInBits(); 10805 // The canonical VMOV for a zero vector uses a 32-bit element size. 10806 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10807 unsigned EltBits; 10808 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 10809 EltSize = 8; 10810 EVT VT = N->getValueType(0); 10811 if (EltSize > VT.getScalarSizeInBits()) 10812 return SDValue(); 10813 10814 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 10815 } 10816 10817 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 10818 static SDValue PerformVDUPCombine(SDNode *N, 10819 TargetLowering::DAGCombinerInfo &DCI) { 10820 SelectionDAG &DAG = DCI.DAG; 10821 SDValue Op = N->getOperand(0); 10822 10823 // Match VDUP(LOAD) -> VLD1DUP. 10824 // We match this pattern here rather than waiting for isel because the 10825 // transform is only legal for unindexed loads. 10826 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 10827 if (LD && Op.hasOneUse() && LD->isUnindexed() && 10828 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 10829 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 10830 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 10831 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 10832 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 10833 Ops, LD->getMemoryVT(), 10834 LD->getMemOperand()); 10835 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 10836 return VLDDup; 10837 } 10838 10839 return SDValue(); 10840 } 10841 10842 static SDValue PerformLOADCombine(SDNode *N, 10843 TargetLowering::DAGCombinerInfo &DCI) { 10844 EVT VT = N->getValueType(0); 10845 10846 // If this is a legal vector load, try to combine it into a VLD1_UPD. 10847 if (ISD::isNormalLoad(N) && VT.isVector() && 10848 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10849 return CombineBaseUpdate(N, DCI); 10850 10851 return SDValue(); 10852 } 10853 10854 /// PerformSTORECombine - Target-specific dag combine xforms for 10855 /// ISD::STORE. 10856 static SDValue PerformSTORECombine(SDNode *N, 10857 TargetLowering::DAGCombinerInfo &DCI) { 10858 StoreSDNode *St = cast<StoreSDNode>(N); 10859 if (St->isVolatile()) 10860 return SDValue(); 10861 10862 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 10863 // pack all of the elements in one place. Next, store to memory in fewer 10864 // chunks. 10865 SDValue StVal = St->getValue(); 10866 EVT VT = StVal.getValueType(); 10867 if (St->isTruncatingStore() && VT.isVector()) { 10868 SelectionDAG &DAG = DCI.DAG; 10869 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10870 EVT StVT = St->getMemoryVT(); 10871 unsigned NumElems = VT.getVectorNumElements(); 10872 assert(StVT != VT && "Cannot truncate to the same type"); 10873 unsigned FromEltSz = VT.getScalarSizeInBits(); 10874 unsigned ToEltSz = StVT.getScalarSizeInBits(); 10875 10876 // From, To sizes and ElemCount must be pow of two 10877 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 10878 10879 // We are going to use the original vector elt for storing. 10880 // Accumulated smaller vector elements must be a multiple of the store size. 10881 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 10882 10883 unsigned SizeRatio = FromEltSz / ToEltSz; 10884 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 10885 10886 // Create a type on which we perform the shuffle. 10887 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 10888 NumElems*SizeRatio); 10889 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 10890 10891 SDLoc DL(St); 10892 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 10893 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 10894 for (unsigned i = 0; i < NumElems; ++i) 10895 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 10896 ? (i + 1) * SizeRatio - 1 10897 : i * SizeRatio; 10898 10899 // Can't shuffle using an illegal type. 10900 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 10901 10902 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 10903 DAG.getUNDEF(WideVec.getValueType()), 10904 ShuffleVec); 10905 // At this point all of the data is stored at the bottom of the 10906 // register. We now need to save it to mem. 10907 10908 // Find the largest store unit 10909 MVT StoreType = MVT::i8; 10910 for (MVT Tp : MVT::integer_valuetypes()) { 10911 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 10912 StoreType = Tp; 10913 } 10914 // Didn't find a legal store type. 10915 if (!TLI.isTypeLegal(StoreType)) 10916 return SDValue(); 10917 10918 // Bitcast the original vector into a vector of store-size units 10919 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 10920 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 10921 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 10922 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 10923 SmallVector<SDValue, 8> Chains; 10924 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 10925 TLI.getPointerTy(DAG.getDataLayout())); 10926 SDValue BasePtr = St->getBasePtr(); 10927 10928 // Perform one or more big stores into memory. 10929 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 10930 for (unsigned I = 0; I < E; I++) { 10931 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 10932 StoreType, ShuffWide, 10933 DAG.getIntPtrConstant(I, DL)); 10934 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 10935 St->getPointerInfo(), St->getAlignment(), 10936 St->getMemOperand()->getFlags()); 10937 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 10938 Increment); 10939 Chains.push_back(Ch); 10940 } 10941 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10942 } 10943 10944 if (!ISD::isNormalStore(St)) 10945 return SDValue(); 10946 10947 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 10948 // ARM stores of arguments in the same cache line. 10949 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 10950 StVal.getNode()->hasOneUse()) { 10951 SelectionDAG &DAG = DCI.DAG; 10952 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 10953 SDLoc DL(St); 10954 SDValue BasePtr = St->getBasePtr(); 10955 SDValue NewST1 = DAG.getStore( 10956 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 10957 BasePtr, St->getPointerInfo(), St->getAlignment(), 10958 St->getMemOperand()->getFlags()); 10959 10960 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10961 DAG.getConstant(4, DL, MVT::i32)); 10962 return DAG.getStore(NewST1.getValue(0), DL, 10963 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 10964 OffsetPtr, St->getPointerInfo(), 10965 std::min(4U, St->getAlignment() / 2), 10966 St->getMemOperand()->getFlags()); 10967 } 10968 10969 if (StVal.getValueType() == MVT::i64 && 10970 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10971 10972 // Bitcast an i64 store extracted from a vector to f64. 10973 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10974 SelectionDAG &DAG = DCI.DAG; 10975 SDLoc dl(StVal); 10976 SDValue IntVec = StVal.getOperand(0); 10977 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10978 IntVec.getValueType().getVectorNumElements()); 10979 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 10980 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 10981 Vec, StVal.getOperand(1)); 10982 dl = SDLoc(N); 10983 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 10984 // Make the DAGCombiner fold the bitcasts. 10985 DCI.AddToWorklist(Vec.getNode()); 10986 DCI.AddToWorklist(ExtElt.getNode()); 10987 DCI.AddToWorklist(V.getNode()); 10988 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 10989 St->getPointerInfo(), St->getAlignment(), 10990 St->getMemOperand()->getFlags(), St->getAAInfo()); 10991 } 10992 10993 // If this is a legal vector store, try to combine it into a VST1_UPD. 10994 if (ISD::isNormalStore(N) && VT.isVector() && 10995 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10996 return CombineBaseUpdate(N, DCI); 10997 10998 return SDValue(); 10999 } 11000 11001 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11002 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11003 /// when the VMUL has a constant operand that is a power of 2. 11004 /// 11005 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11006 /// vmul.f32 d16, d17, d16 11007 /// vcvt.s32.f32 d16, d16 11008 /// becomes: 11009 /// vcvt.s32.f32 d16, d16, #3 11010 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11011 const ARMSubtarget *Subtarget) { 11012 if (!Subtarget->hasNEON()) 11013 return SDValue(); 11014 11015 SDValue Op = N->getOperand(0); 11016 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 11017 Op.getOpcode() != ISD::FMUL) 11018 return SDValue(); 11019 11020 SDValue ConstVec = Op->getOperand(1); 11021 if (!isa<BuildVectorSDNode>(ConstVec)) 11022 return SDValue(); 11023 11024 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 11025 uint32_t FloatBits = FloatTy.getSizeInBits(); 11026 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 11027 uint32_t IntBits = IntTy.getSizeInBits(); 11028 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11029 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11030 // These instructions only exist converting from f32 to i32. We can handle 11031 // smaller integers by generating an extra truncate, but larger ones would 11032 // be lossy. We also can't handle more then 4 lanes, since these intructions 11033 // only support v2i32/v4i32 types. 11034 return SDValue(); 11035 } 11036 11037 BitVector UndefElements; 11038 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11039 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11040 if (C == -1 || C == 0 || C > 32) 11041 return SDValue(); 11042 11043 SDLoc dl(N); 11044 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 11045 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 11046 Intrinsic::arm_neon_vcvtfp2fxu; 11047 SDValue FixConv = DAG.getNode( 11048 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11049 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 11050 DAG.getConstant(C, dl, MVT::i32)); 11051 11052 if (IntBits < FloatBits) 11053 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 11054 11055 return FixConv; 11056 } 11057 11058 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 11059 /// can replace combinations of VCVT (integer to floating-point) and VDIV 11060 /// when the VDIV has a constant operand that is a power of 2. 11061 /// 11062 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11063 /// vcvt.f32.s32 d16, d16 11064 /// vdiv.f32 d16, d17, d16 11065 /// becomes: 11066 /// vcvt.f32.s32 d16, d16, #3 11067 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 11068 const ARMSubtarget *Subtarget) { 11069 if (!Subtarget->hasNEON()) 11070 return SDValue(); 11071 11072 SDValue Op = N->getOperand(0); 11073 unsigned OpOpcode = Op.getNode()->getOpcode(); 11074 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 11075 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 11076 return SDValue(); 11077 11078 SDValue ConstVec = N->getOperand(1); 11079 if (!isa<BuildVectorSDNode>(ConstVec)) 11080 return SDValue(); 11081 11082 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 11083 uint32_t FloatBits = FloatTy.getSizeInBits(); 11084 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 11085 uint32_t IntBits = IntTy.getSizeInBits(); 11086 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11087 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11088 // These instructions only exist converting from i32 to f32. We can handle 11089 // smaller integers by generating an extra extend, but larger ones would 11090 // be lossy. We also can't handle more then 4 lanes, since these intructions 11091 // only support v2i32/v4i32 types. 11092 return SDValue(); 11093 } 11094 11095 BitVector UndefElements; 11096 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11097 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11098 if (C == -1 || C == 0 || C > 32) 11099 return SDValue(); 11100 11101 SDLoc dl(N); 11102 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 11103 SDValue ConvInput = Op.getOperand(0); 11104 if (IntBits < FloatBits) 11105 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 11106 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11107 ConvInput); 11108 11109 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 11110 Intrinsic::arm_neon_vcvtfxu2fp; 11111 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 11112 Op.getValueType(), 11113 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 11114 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 11115 } 11116 11117 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 11118 /// operand of a vector shift operation, where all the elements of the 11119 /// build_vector must have the same constant integer value. 11120 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 11121 // Ignore bit_converts. 11122 while (Op.getOpcode() == ISD::BITCAST) 11123 Op = Op.getOperand(0); 11124 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 11125 APInt SplatBits, SplatUndef; 11126 unsigned SplatBitSize; 11127 bool HasAnyUndefs; 11128 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 11129 HasAnyUndefs, ElementBits) || 11130 SplatBitSize > ElementBits) 11131 return false; 11132 Cnt = SplatBits.getSExtValue(); 11133 return true; 11134 } 11135 11136 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 11137 /// operand of a vector shift left operation. That value must be in the range: 11138 /// 0 <= Value < ElementBits for a left shift; or 11139 /// 0 <= Value <= ElementBits for a long left shift. 11140 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 11141 assert(VT.isVector() && "vector shift count is not a vector type"); 11142 int64_t ElementBits = VT.getScalarSizeInBits(); 11143 if (! getVShiftImm(Op, ElementBits, Cnt)) 11144 return false; 11145 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 11146 } 11147 11148 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 11149 /// operand of a vector shift right operation. For a shift opcode, the value 11150 /// is positive, but for an intrinsic the value count must be negative. The 11151 /// absolute value must be in the range: 11152 /// 1 <= |Value| <= ElementBits for a right shift; or 11153 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 11154 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 11155 int64_t &Cnt) { 11156 assert(VT.isVector() && "vector shift count is not a vector type"); 11157 int64_t ElementBits = VT.getScalarSizeInBits(); 11158 if (! getVShiftImm(Op, ElementBits, Cnt)) 11159 return false; 11160 if (!isIntrinsic) 11161 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 11162 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 11163 Cnt = -Cnt; 11164 return true; 11165 } 11166 return false; 11167 } 11168 11169 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 11170 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 11171 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 11172 switch (IntNo) { 11173 default: 11174 // Don't do anything for most intrinsics. 11175 break; 11176 11177 // Vector shifts: check for immediate versions and lower them. 11178 // Note: This is done during DAG combining instead of DAG legalizing because 11179 // the build_vectors for 64-bit vector element shift counts are generally 11180 // not legal, and it is hard to see their values after they get legalized to 11181 // loads from a constant pool. 11182 case Intrinsic::arm_neon_vshifts: 11183 case Intrinsic::arm_neon_vshiftu: 11184 case Intrinsic::arm_neon_vrshifts: 11185 case Intrinsic::arm_neon_vrshiftu: 11186 case Intrinsic::arm_neon_vrshiftn: 11187 case Intrinsic::arm_neon_vqshifts: 11188 case Intrinsic::arm_neon_vqshiftu: 11189 case Intrinsic::arm_neon_vqshiftsu: 11190 case Intrinsic::arm_neon_vqshiftns: 11191 case Intrinsic::arm_neon_vqshiftnu: 11192 case Intrinsic::arm_neon_vqshiftnsu: 11193 case Intrinsic::arm_neon_vqrshiftns: 11194 case Intrinsic::arm_neon_vqrshiftnu: 11195 case Intrinsic::arm_neon_vqrshiftnsu: { 11196 EVT VT = N->getOperand(1).getValueType(); 11197 int64_t Cnt; 11198 unsigned VShiftOpc = 0; 11199 11200 switch (IntNo) { 11201 case Intrinsic::arm_neon_vshifts: 11202 case Intrinsic::arm_neon_vshiftu: 11203 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 11204 VShiftOpc = ARMISD::VSHL; 11205 break; 11206 } 11207 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 11208 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 11209 ARMISD::VSHRs : ARMISD::VSHRu); 11210 break; 11211 } 11212 return SDValue(); 11213 11214 case Intrinsic::arm_neon_vrshifts: 11215 case Intrinsic::arm_neon_vrshiftu: 11216 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 11217 break; 11218 return SDValue(); 11219 11220 case Intrinsic::arm_neon_vqshifts: 11221 case Intrinsic::arm_neon_vqshiftu: 11222 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11223 break; 11224 return SDValue(); 11225 11226 case Intrinsic::arm_neon_vqshiftsu: 11227 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11228 break; 11229 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 11230 11231 case Intrinsic::arm_neon_vrshiftn: 11232 case Intrinsic::arm_neon_vqshiftns: 11233 case Intrinsic::arm_neon_vqshiftnu: 11234 case Intrinsic::arm_neon_vqshiftnsu: 11235 case Intrinsic::arm_neon_vqrshiftns: 11236 case Intrinsic::arm_neon_vqrshiftnu: 11237 case Intrinsic::arm_neon_vqrshiftnsu: 11238 // Narrowing shifts require an immediate right shift. 11239 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 11240 break; 11241 llvm_unreachable("invalid shift count for narrowing vector shift " 11242 "intrinsic"); 11243 11244 default: 11245 llvm_unreachable("unhandled vector shift"); 11246 } 11247 11248 switch (IntNo) { 11249 case Intrinsic::arm_neon_vshifts: 11250 case Intrinsic::arm_neon_vshiftu: 11251 // Opcode already set above. 11252 break; 11253 case Intrinsic::arm_neon_vrshifts: 11254 VShiftOpc = ARMISD::VRSHRs; break; 11255 case Intrinsic::arm_neon_vrshiftu: 11256 VShiftOpc = ARMISD::VRSHRu; break; 11257 case Intrinsic::arm_neon_vrshiftn: 11258 VShiftOpc = ARMISD::VRSHRN; break; 11259 case Intrinsic::arm_neon_vqshifts: 11260 VShiftOpc = ARMISD::VQSHLs; break; 11261 case Intrinsic::arm_neon_vqshiftu: 11262 VShiftOpc = ARMISD::VQSHLu; break; 11263 case Intrinsic::arm_neon_vqshiftsu: 11264 VShiftOpc = ARMISD::VQSHLsu; break; 11265 case Intrinsic::arm_neon_vqshiftns: 11266 VShiftOpc = ARMISD::VQSHRNs; break; 11267 case Intrinsic::arm_neon_vqshiftnu: 11268 VShiftOpc = ARMISD::VQSHRNu; break; 11269 case Intrinsic::arm_neon_vqshiftnsu: 11270 VShiftOpc = ARMISD::VQSHRNsu; break; 11271 case Intrinsic::arm_neon_vqrshiftns: 11272 VShiftOpc = ARMISD::VQRSHRNs; break; 11273 case Intrinsic::arm_neon_vqrshiftnu: 11274 VShiftOpc = ARMISD::VQRSHRNu; break; 11275 case Intrinsic::arm_neon_vqrshiftnsu: 11276 VShiftOpc = ARMISD::VQRSHRNsu; break; 11277 } 11278 11279 SDLoc dl(N); 11280 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11281 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 11282 } 11283 11284 case Intrinsic::arm_neon_vshiftins: { 11285 EVT VT = N->getOperand(1).getValueType(); 11286 int64_t Cnt; 11287 unsigned VShiftOpc = 0; 11288 11289 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 11290 VShiftOpc = ARMISD::VSLI; 11291 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 11292 VShiftOpc = ARMISD::VSRI; 11293 else { 11294 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 11295 } 11296 11297 SDLoc dl(N); 11298 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11299 N->getOperand(1), N->getOperand(2), 11300 DAG.getConstant(Cnt, dl, MVT::i32)); 11301 } 11302 11303 case Intrinsic::arm_neon_vqrshifts: 11304 case Intrinsic::arm_neon_vqrshiftu: 11305 // No immediate versions of these to check for. 11306 break; 11307 } 11308 11309 return SDValue(); 11310 } 11311 11312 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 11313 /// lowers them. As with the vector shift intrinsics, this is done during DAG 11314 /// combining instead of DAG legalizing because the build_vectors for 64-bit 11315 /// vector element shift counts are generally not legal, and it is hard to see 11316 /// their values after they get legalized to loads from a constant pool. 11317 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 11318 const ARMSubtarget *ST) { 11319 EVT VT = N->getValueType(0); 11320 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 11321 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 11322 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 11323 SDValue N1 = N->getOperand(1); 11324 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 11325 SDValue N0 = N->getOperand(0); 11326 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 11327 DAG.MaskedValueIsZero(N0.getOperand(0), 11328 APInt::getHighBitsSet(32, 16))) 11329 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 11330 } 11331 } 11332 11333 // Nothing to be done for scalar shifts. 11334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11335 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 11336 return SDValue(); 11337 11338 assert(ST->hasNEON() && "unexpected vector shift"); 11339 int64_t Cnt; 11340 11341 switch (N->getOpcode()) { 11342 default: llvm_unreachable("unexpected shift opcode"); 11343 11344 case ISD::SHL: 11345 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 11346 SDLoc dl(N); 11347 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 11348 DAG.getConstant(Cnt, dl, MVT::i32)); 11349 } 11350 break; 11351 11352 case ISD::SRA: 11353 case ISD::SRL: 11354 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 11355 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 11356 ARMISD::VSHRs : ARMISD::VSHRu); 11357 SDLoc dl(N); 11358 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 11359 DAG.getConstant(Cnt, dl, MVT::i32)); 11360 } 11361 } 11362 return SDValue(); 11363 } 11364 11365 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 11366 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 11367 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 11368 const ARMSubtarget *ST) { 11369 SDValue N0 = N->getOperand(0); 11370 11371 // Check for sign- and zero-extensions of vector extract operations of 8- 11372 // and 16-bit vector elements. NEON supports these directly. They are 11373 // handled during DAG combining because type legalization will promote them 11374 // to 32-bit types and it is messy to recognize the operations after that. 11375 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11376 SDValue Vec = N0.getOperand(0); 11377 SDValue Lane = N0.getOperand(1); 11378 EVT VT = N->getValueType(0); 11379 EVT EltVT = N0.getValueType(); 11380 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11381 11382 if (VT == MVT::i32 && 11383 (EltVT == MVT::i8 || EltVT == MVT::i16) && 11384 TLI.isTypeLegal(Vec.getValueType()) && 11385 isa<ConstantSDNode>(Lane)) { 11386 11387 unsigned Opc = 0; 11388 switch (N->getOpcode()) { 11389 default: llvm_unreachable("unexpected opcode"); 11390 case ISD::SIGN_EXTEND: 11391 Opc = ARMISD::VGETLANEs; 11392 break; 11393 case ISD::ZERO_EXTEND: 11394 case ISD::ANY_EXTEND: 11395 Opc = ARMISD::VGETLANEu; 11396 break; 11397 } 11398 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 11399 } 11400 } 11401 11402 return SDValue(); 11403 } 11404 11405 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 11406 APInt &KnownOne) { 11407 if (Op.getOpcode() == ARMISD::BFI) { 11408 // Conservatively, we can recurse down the first operand 11409 // and just mask out all affected bits. 11410 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 11411 11412 // The operand to BFI is already a mask suitable for removing the bits it 11413 // sets. 11414 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 11415 const APInt &Mask = CI->getAPIntValue(); 11416 KnownZero &= Mask; 11417 KnownOne &= Mask; 11418 return; 11419 } 11420 if (Op.getOpcode() == ARMISD::CMOV) { 11421 APInt KZ2(KnownZero.getBitWidth(), 0); 11422 APInt KO2(KnownOne.getBitWidth(), 0); 11423 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 11424 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 11425 11426 KnownZero &= KZ2; 11427 KnownOne &= KO2; 11428 return; 11429 } 11430 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 11431 } 11432 11433 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 11434 // If we have a CMOV, OR and AND combination such as: 11435 // if (x & CN) 11436 // y |= CM; 11437 // 11438 // And: 11439 // * CN is a single bit; 11440 // * All bits covered by CM are known zero in y 11441 // 11442 // Then we can convert this into a sequence of BFI instructions. This will 11443 // always be a win if CM is a single bit, will always be no worse than the 11444 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 11445 // three bits (due to the extra IT instruction). 11446 11447 SDValue Op0 = CMOV->getOperand(0); 11448 SDValue Op1 = CMOV->getOperand(1); 11449 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 11450 auto CC = CCNode->getAPIntValue().getLimitedValue(); 11451 SDValue CmpZ = CMOV->getOperand(4); 11452 11453 // The compare must be against zero. 11454 if (!isNullConstant(CmpZ->getOperand(1))) 11455 return SDValue(); 11456 11457 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 11458 SDValue And = CmpZ->getOperand(0); 11459 if (And->getOpcode() != ISD::AND) 11460 return SDValue(); 11461 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 11462 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 11463 return SDValue(); 11464 SDValue X = And->getOperand(0); 11465 11466 if (CC == ARMCC::EQ) { 11467 // We're performing an "equal to zero" compare. Swap the operands so we 11468 // canonicalize on a "not equal to zero" compare. 11469 std::swap(Op0, Op1); 11470 } else { 11471 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 11472 } 11473 11474 if (Op1->getOpcode() != ISD::OR) 11475 return SDValue(); 11476 11477 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 11478 if (!OrC) 11479 return SDValue(); 11480 SDValue Y = Op1->getOperand(0); 11481 11482 if (Op0 != Y) 11483 return SDValue(); 11484 11485 // Now, is it profitable to continue? 11486 APInt OrCI = OrC->getAPIntValue(); 11487 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 11488 if (OrCI.countPopulation() > Heuristic) 11489 return SDValue(); 11490 11491 // Lastly, can we determine that the bits defined by OrCI 11492 // are zero in Y? 11493 APInt KnownZero, KnownOne; 11494 computeKnownBits(DAG, Y, KnownZero, KnownOne); 11495 if ((OrCI & KnownZero) != OrCI) 11496 return SDValue(); 11497 11498 // OK, we can do the combine. 11499 SDValue V = Y; 11500 SDLoc dl(X); 11501 EVT VT = X.getValueType(); 11502 unsigned BitInX = AndC->getAPIntValue().logBase2(); 11503 11504 if (BitInX != 0) { 11505 // We must shift X first. 11506 X = DAG.getNode(ISD::SRL, dl, VT, X, 11507 DAG.getConstant(BitInX, dl, VT)); 11508 } 11509 11510 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 11511 BitInY < NumActiveBits; ++BitInY) { 11512 if (OrCI[BitInY] == 0) 11513 continue; 11514 APInt Mask(VT.getSizeInBits(), 0); 11515 Mask.setBit(BitInY); 11516 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 11517 // Confusingly, the operand is an *inverted* mask. 11518 DAG.getConstant(~Mask, dl, VT)); 11519 } 11520 11521 return V; 11522 } 11523 11524 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 11525 SDValue 11526 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 11527 SDValue Cmp = N->getOperand(4); 11528 if (Cmp.getOpcode() != ARMISD::CMPZ) 11529 // Only looking at NE cases. 11530 return SDValue(); 11531 11532 EVT VT = N->getValueType(0); 11533 SDLoc dl(N); 11534 SDValue LHS = Cmp.getOperand(0); 11535 SDValue RHS = Cmp.getOperand(1); 11536 SDValue Chain = N->getOperand(0); 11537 SDValue BB = N->getOperand(1); 11538 SDValue ARMcc = N->getOperand(2); 11539 ARMCC::CondCodes CC = 11540 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11541 11542 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 11543 // -> (brcond Chain BB CC CPSR Cmp) 11544 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 11545 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 11546 LHS->getOperand(0)->hasOneUse()) { 11547 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 11548 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 11549 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11550 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11551 if ((LHS00C && LHS00C->getZExtValue() == 0) && 11552 (LHS01C && LHS01C->getZExtValue() == 1) && 11553 (LHS1C && LHS1C->getZExtValue() == 1) && 11554 (RHSC && RHSC->getZExtValue() == 0)) { 11555 return DAG.getNode( 11556 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 11557 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 11558 } 11559 } 11560 11561 return SDValue(); 11562 } 11563 11564 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 11565 SDValue 11566 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 11567 SDValue Cmp = N->getOperand(4); 11568 if (Cmp.getOpcode() != ARMISD::CMPZ) 11569 // Only looking at EQ and NE cases. 11570 return SDValue(); 11571 11572 EVT VT = N->getValueType(0); 11573 SDLoc dl(N); 11574 SDValue LHS = Cmp.getOperand(0); 11575 SDValue RHS = Cmp.getOperand(1); 11576 SDValue FalseVal = N->getOperand(0); 11577 SDValue TrueVal = N->getOperand(1); 11578 SDValue ARMcc = N->getOperand(2); 11579 ARMCC::CondCodes CC = 11580 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11581 11582 // BFI is only available on V6T2+. 11583 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 11584 SDValue R = PerformCMOVToBFICombine(N, DAG); 11585 if (R) 11586 return R; 11587 } 11588 11589 // Simplify 11590 // mov r1, r0 11591 // cmp r1, x 11592 // mov r0, y 11593 // moveq r0, x 11594 // to 11595 // cmp r0, x 11596 // movne r0, y 11597 // 11598 // mov r1, r0 11599 // cmp r1, x 11600 // mov r0, x 11601 // movne r0, y 11602 // to 11603 // cmp r0, x 11604 // movne r0, y 11605 /// FIXME: Turn this into a target neutral optimization? 11606 SDValue Res; 11607 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 11608 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 11609 N->getOperand(3), Cmp); 11610 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 11611 SDValue ARMcc; 11612 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 11613 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 11614 N->getOperand(3), NewCmp); 11615 } 11616 11617 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 11618 // -> (cmov F T CC CPSR Cmp) 11619 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 11620 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 11621 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11622 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11623 if ((LHS0C && LHS0C->getZExtValue() == 0) && 11624 (LHS1C && LHS1C->getZExtValue() == 1) && 11625 (RHSC && RHSC->getZExtValue() == 0)) { 11626 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 11627 LHS->getOperand(2), LHS->getOperand(3), 11628 LHS->getOperand(4)); 11629 } 11630 } 11631 11632 if (Res.getNode()) { 11633 APInt KnownZero, KnownOne; 11634 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 11635 // Capture demanded bits information that would be otherwise lost. 11636 if (KnownZero == 0xfffffffe) 11637 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11638 DAG.getValueType(MVT::i1)); 11639 else if (KnownZero == 0xffffff00) 11640 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11641 DAG.getValueType(MVT::i8)); 11642 else if (KnownZero == 0xffff0000) 11643 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11644 DAG.getValueType(MVT::i16)); 11645 } 11646 11647 return Res; 11648 } 11649 11650 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 11651 DAGCombinerInfo &DCI) const { 11652 switch (N->getOpcode()) { 11653 default: break; 11654 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 11655 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 11656 case ISD::SUB: return PerformSUBCombine(N, DCI); 11657 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 11658 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 11659 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 11660 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 11661 case ARMISD::BFI: return PerformBFICombine(N, DCI); 11662 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 11663 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 11664 case ISD::STORE: return PerformSTORECombine(N, DCI); 11665 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 11666 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 11667 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 11668 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 11669 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 11670 case ISD::FP_TO_SINT: 11671 case ISD::FP_TO_UINT: 11672 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 11673 case ISD::FDIV: 11674 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 11675 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 11676 case ISD::SHL: 11677 case ISD::SRA: 11678 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 11679 case ISD::SIGN_EXTEND: 11680 case ISD::ZERO_EXTEND: 11681 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 11682 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 11683 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 11684 case ISD::LOAD: return PerformLOADCombine(N, DCI); 11685 case ARMISD::VLD1DUP: 11686 case ARMISD::VLD2DUP: 11687 case ARMISD::VLD3DUP: 11688 case ARMISD::VLD4DUP: 11689 return PerformVLDCombine(N, DCI); 11690 case ARMISD::BUILD_VECTOR: 11691 return PerformARMBUILD_VECTORCombine(N, DCI); 11692 case ISD::INTRINSIC_VOID: 11693 case ISD::INTRINSIC_W_CHAIN: 11694 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11695 case Intrinsic::arm_neon_vld1: 11696 case Intrinsic::arm_neon_vld2: 11697 case Intrinsic::arm_neon_vld3: 11698 case Intrinsic::arm_neon_vld4: 11699 case Intrinsic::arm_neon_vld2lane: 11700 case Intrinsic::arm_neon_vld3lane: 11701 case Intrinsic::arm_neon_vld4lane: 11702 case Intrinsic::arm_neon_vst1: 11703 case Intrinsic::arm_neon_vst2: 11704 case Intrinsic::arm_neon_vst3: 11705 case Intrinsic::arm_neon_vst4: 11706 case Intrinsic::arm_neon_vst2lane: 11707 case Intrinsic::arm_neon_vst3lane: 11708 case Intrinsic::arm_neon_vst4lane: 11709 return PerformVLDCombine(N, DCI); 11710 default: break; 11711 } 11712 break; 11713 } 11714 return SDValue(); 11715 } 11716 11717 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 11718 EVT VT) const { 11719 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 11720 } 11721 11722 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 11723 unsigned, 11724 unsigned, 11725 bool *Fast) const { 11726 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 11727 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 11728 11729 switch (VT.getSimpleVT().SimpleTy) { 11730 default: 11731 return false; 11732 case MVT::i8: 11733 case MVT::i16: 11734 case MVT::i32: { 11735 // Unaligned access can use (for example) LRDB, LRDH, LDR 11736 if (AllowsUnaligned) { 11737 if (Fast) 11738 *Fast = Subtarget->hasV7Ops(); 11739 return true; 11740 } 11741 return false; 11742 } 11743 case MVT::f64: 11744 case MVT::v2f64: { 11745 // For any little-endian targets with neon, we can support unaligned ld/st 11746 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 11747 // A big-endian target may also explicitly support unaligned accesses 11748 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 11749 if (Fast) 11750 *Fast = true; 11751 return true; 11752 } 11753 return false; 11754 } 11755 } 11756 } 11757 11758 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 11759 unsigned AlignCheck) { 11760 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 11761 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 11762 } 11763 11764 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 11765 unsigned DstAlign, unsigned SrcAlign, 11766 bool IsMemset, bool ZeroMemset, 11767 bool MemcpyStrSrc, 11768 MachineFunction &MF) const { 11769 const Function *F = MF.getFunction(); 11770 11771 // See if we can use NEON instructions for this... 11772 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 11773 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 11774 bool Fast; 11775 if (Size >= 16 && 11776 (memOpAlign(SrcAlign, DstAlign, 16) || 11777 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 11778 return MVT::v2f64; 11779 } else if (Size >= 8 && 11780 (memOpAlign(SrcAlign, DstAlign, 8) || 11781 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 11782 Fast))) { 11783 return MVT::f64; 11784 } 11785 } 11786 11787 // Lowering to i32/i16 if the size permits. 11788 if (Size >= 4) 11789 return MVT::i32; 11790 else if (Size >= 2) 11791 return MVT::i16; 11792 11793 // Let the target-independent logic figure it out. 11794 return MVT::Other; 11795 } 11796 11797 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 11798 if (Val.getOpcode() != ISD::LOAD) 11799 return false; 11800 11801 EVT VT1 = Val.getValueType(); 11802 if (!VT1.isSimple() || !VT1.isInteger() || 11803 !VT2.isSimple() || !VT2.isInteger()) 11804 return false; 11805 11806 switch (VT1.getSimpleVT().SimpleTy) { 11807 default: break; 11808 case MVT::i1: 11809 case MVT::i8: 11810 case MVT::i16: 11811 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 11812 return true; 11813 } 11814 11815 return false; 11816 } 11817 11818 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 11819 EVT VT = ExtVal.getValueType(); 11820 11821 if (!isTypeLegal(VT)) 11822 return false; 11823 11824 // Don't create a loadext if we can fold the extension into a wide/long 11825 // instruction. 11826 // If there's more than one user instruction, the loadext is desirable no 11827 // matter what. There can be two uses by the same instruction. 11828 if (ExtVal->use_empty() || 11829 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 11830 return true; 11831 11832 SDNode *U = *ExtVal->use_begin(); 11833 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 11834 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 11835 return false; 11836 11837 return true; 11838 } 11839 11840 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 11841 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 11842 return false; 11843 11844 if (!isTypeLegal(EVT::getEVT(Ty1))) 11845 return false; 11846 11847 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 11848 11849 // Assuming the caller doesn't have a zeroext or signext return parameter, 11850 // truncation all the way down to i1 is valid. 11851 return true; 11852 } 11853 11854 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 11855 const AddrMode &AM, Type *Ty, 11856 unsigned AS) const { 11857 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 11858 if (Subtarget->hasFPAO()) 11859 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 11860 return 0; 11861 } 11862 return -1; 11863 } 11864 11865 11866 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 11867 if (V < 0) 11868 return false; 11869 11870 unsigned Scale = 1; 11871 switch (VT.getSimpleVT().SimpleTy) { 11872 default: return false; 11873 case MVT::i1: 11874 case MVT::i8: 11875 // Scale == 1; 11876 break; 11877 case MVT::i16: 11878 // Scale == 2; 11879 Scale = 2; 11880 break; 11881 case MVT::i32: 11882 // Scale == 4; 11883 Scale = 4; 11884 break; 11885 } 11886 11887 if ((V & (Scale - 1)) != 0) 11888 return false; 11889 V /= Scale; 11890 return V == (V & ((1LL << 5) - 1)); 11891 } 11892 11893 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 11894 const ARMSubtarget *Subtarget) { 11895 bool isNeg = false; 11896 if (V < 0) { 11897 isNeg = true; 11898 V = - V; 11899 } 11900 11901 switch (VT.getSimpleVT().SimpleTy) { 11902 default: return false; 11903 case MVT::i1: 11904 case MVT::i8: 11905 case MVT::i16: 11906 case MVT::i32: 11907 // + imm12 or - imm8 11908 if (isNeg) 11909 return V == (V & ((1LL << 8) - 1)); 11910 return V == (V & ((1LL << 12) - 1)); 11911 case MVT::f32: 11912 case MVT::f64: 11913 // Same as ARM mode. FIXME: NEON? 11914 if (!Subtarget->hasVFP2()) 11915 return false; 11916 if ((V & 3) != 0) 11917 return false; 11918 V >>= 2; 11919 return V == (V & ((1LL << 8) - 1)); 11920 } 11921 } 11922 11923 /// isLegalAddressImmediate - Return true if the integer value can be used 11924 /// as the offset of the target addressing mode for load / store of the 11925 /// given type. 11926 static bool isLegalAddressImmediate(int64_t V, EVT VT, 11927 const ARMSubtarget *Subtarget) { 11928 if (V == 0) 11929 return true; 11930 11931 if (!VT.isSimple()) 11932 return false; 11933 11934 if (Subtarget->isThumb1Only()) 11935 return isLegalT1AddressImmediate(V, VT); 11936 else if (Subtarget->isThumb2()) 11937 return isLegalT2AddressImmediate(V, VT, Subtarget); 11938 11939 // ARM mode. 11940 if (V < 0) 11941 V = - V; 11942 switch (VT.getSimpleVT().SimpleTy) { 11943 default: return false; 11944 case MVT::i1: 11945 case MVT::i8: 11946 case MVT::i32: 11947 // +- imm12 11948 return V == (V & ((1LL << 12) - 1)); 11949 case MVT::i16: 11950 // +- imm8 11951 return V == (V & ((1LL << 8) - 1)); 11952 case MVT::f32: 11953 case MVT::f64: 11954 if (!Subtarget->hasVFP2()) // FIXME: NEON? 11955 return false; 11956 if ((V & 3) != 0) 11957 return false; 11958 V >>= 2; 11959 return V == (V & ((1LL << 8) - 1)); 11960 } 11961 } 11962 11963 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 11964 EVT VT) const { 11965 int Scale = AM.Scale; 11966 if (Scale < 0) 11967 return false; 11968 11969 switch (VT.getSimpleVT().SimpleTy) { 11970 default: return false; 11971 case MVT::i1: 11972 case MVT::i8: 11973 case MVT::i16: 11974 case MVT::i32: 11975 if (Scale == 1) 11976 return true; 11977 // r + r << imm 11978 Scale = Scale & ~1; 11979 return Scale == 2 || Scale == 4 || Scale == 8; 11980 case MVT::i64: 11981 // r + r 11982 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 11983 return true; 11984 return false; 11985 case MVT::isVoid: 11986 // Note, we allow "void" uses (basically, uses that aren't loads or 11987 // stores), because arm allows folding a scale into many arithmetic 11988 // operations. This should be made more precise and revisited later. 11989 11990 // Allow r << imm, but the imm has to be a multiple of two. 11991 if (Scale & 1) return false; 11992 return isPowerOf2_32(Scale); 11993 } 11994 } 11995 11996 /// isLegalAddressingMode - Return true if the addressing mode represented 11997 /// by AM is legal for this target, for a load/store of the specified type. 11998 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 11999 const AddrMode &AM, Type *Ty, 12000 unsigned AS) const { 12001 EVT VT = getValueType(DL, Ty, true); 12002 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 12003 return false; 12004 12005 // Can never fold addr of global into load/store. 12006 if (AM.BaseGV) 12007 return false; 12008 12009 switch (AM.Scale) { 12010 case 0: // no scale reg, must be "r+i" or "r", or "i". 12011 break; 12012 case 1: 12013 if (Subtarget->isThumb1Only()) 12014 return false; 12015 LLVM_FALLTHROUGH; 12016 default: 12017 // ARM doesn't support any R+R*scale+imm addr modes. 12018 if (AM.BaseOffs) 12019 return false; 12020 12021 if (!VT.isSimple()) 12022 return false; 12023 12024 if (Subtarget->isThumb2()) 12025 return isLegalT2ScaledAddressingMode(AM, VT); 12026 12027 int Scale = AM.Scale; 12028 switch (VT.getSimpleVT().SimpleTy) { 12029 default: return false; 12030 case MVT::i1: 12031 case MVT::i8: 12032 case MVT::i32: 12033 if (Scale < 0) Scale = -Scale; 12034 if (Scale == 1) 12035 return true; 12036 // r + r << imm 12037 return isPowerOf2_32(Scale & ~1); 12038 case MVT::i16: 12039 case MVT::i64: 12040 // r + r 12041 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 12042 return true; 12043 return false; 12044 12045 case MVT::isVoid: 12046 // Note, we allow "void" uses (basically, uses that aren't loads or 12047 // stores), because arm allows folding a scale into many arithmetic 12048 // operations. This should be made more precise and revisited later. 12049 12050 // Allow r << imm, but the imm has to be a multiple of two. 12051 if (Scale & 1) return false; 12052 return isPowerOf2_32(Scale); 12053 } 12054 } 12055 return true; 12056 } 12057 12058 /// isLegalICmpImmediate - Return true if the specified immediate is legal 12059 /// icmp immediate, that is the target has icmp instructions which can compare 12060 /// a register against the immediate without having to materialize the 12061 /// immediate into a register. 12062 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 12063 // Thumb2 and ARM modes can use cmn for negative immediates. 12064 if (!Subtarget->isThumb()) 12065 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 12066 if (Subtarget->isThumb2()) 12067 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 12068 // Thumb1 doesn't have cmn, and only 8-bit immediates. 12069 return Imm >= 0 && Imm <= 255; 12070 } 12071 12072 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 12073 /// *or sub* immediate, that is the target has add or sub instructions which can 12074 /// add a register with the immediate without having to materialize the 12075 /// immediate into a register. 12076 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 12077 // Same encoding for add/sub, just flip the sign. 12078 int64_t AbsImm = std::abs(Imm); 12079 if (!Subtarget->isThumb()) 12080 return ARM_AM::getSOImmVal(AbsImm) != -1; 12081 if (Subtarget->isThumb2()) 12082 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 12083 // Thumb1 only has 8-bit unsigned immediate. 12084 return AbsImm >= 0 && AbsImm <= 255; 12085 } 12086 12087 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 12088 bool isSEXTLoad, SDValue &Base, 12089 SDValue &Offset, bool &isInc, 12090 SelectionDAG &DAG) { 12091 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12092 return false; 12093 12094 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 12095 // AddressingMode 3 12096 Base = Ptr->getOperand(0); 12097 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12098 int RHSC = (int)RHS->getZExtValue(); 12099 if (RHSC < 0 && RHSC > -256) { 12100 assert(Ptr->getOpcode() == ISD::ADD); 12101 isInc = false; 12102 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12103 return true; 12104 } 12105 } 12106 isInc = (Ptr->getOpcode() == ISD::ADD); 12107 Offset = Ptr->getOperand(1); 12108 return true; 12109 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 12110 // AddressingMode 2 12111 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12112 int RHSC = (int)RHS->getZExtValue(); 12113 if (RHSC < 0 && RHSC > -0x1000) { 12114 assert(Ptr->getOpcode() == ISD::ADD); 12115 isInc = false; 12116 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12117 Base = Ptr->getOperand(0); 12118 return true; 12119 } 12120 } 12121 12122 if (Ptr->getOpcode() == ISD::ADD) { 12123 isInc = true; 12124 ARM_AM::ShiftOpc ShOpcVal= 12125 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 12126 if (ShOpcVal != ARM_AM::no_shift) { 12127 Base = Ptr->getOperand(1); 12128 Offset = Ptr->getOperand(0); 12129 } else { 12130 Base = Ptr->getOperand(0); 12131 Offset = Ptr->getOperand(1); 12132 } 12133 return true; 12134 } 12135 12136 isInc = (Ptr->getOpcode() == ISD::ADD); 12137 Base = Ptr->getOperand(0); 12138 Offset = Ptr->getOperand(1); 12139 return true; 12140 } 12141 12142 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 12143 return false; 12144 } 12145 12146 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 12147 bool isSEXTLoad, SDValue &Base, 12148 SDValue &Offset, bool &isInc, 12149 SelectionDAG &DAG) { 12150 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12151 return false; 12152 12153 Base = Ptr->getOperand(0); 12154 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12155 int RHSC = (int)RHS->getZExtValue(); 12156 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 12157 assert(Ptr->getOpcode() == ISD::ADD); 12158 isInc = false; 12159 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12160 return true; 12161 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 12162 isInc = Ptr->getOpcode() == ISD::ADD; 12163 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12164 return true; 12165 } 12166 } 12167 12168 return false; 12169 } 12170 12171 /// getPreIndexedAddressParts - returns true by value, base pointer and 12172 /// offset pointer and addressing mode by reference if the node's address 12173 /// can be legally represented as pre-indexed load / store address. 12174 bool 12175 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 12176 SDValue &Offset, 12177 ISD::MemIndexedMode &AM, 12178 SelectionDAG &DAG) const { 12179 if (Subtarget->isThumb1Only()) 12180 return false; 12181 12182 EVT VT; 12183 SDValue Ptr; 12184 bool isSEXTLoad = false; 12185 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12186 Ptr = LD->getBasePtr(); 12187 VT = LD->getMemoryVT(); 12188 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12189 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12190 Ptr = ST->getBasePtr(); 12191 VT = ST->getMemoryVT(); 12192 } else 12193 return false; 12194 12195 bool isInc; 12196 bool isLegal = false; 12197 if (Subtarget->isThumb2()) 12198 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12199 Offset, isInc, DAG); 12200 else 12201 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12202 Offset, isInc, DAG); 12203 if (!isLegal) 12204 return false; 12205 12206 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 12207 return true; 12208 } 12209 12210 /// getPostIndexedAddressParts - returns true by value, base pointer and 12211 /// offset pointer and addressing mode by reference if this node can be 12212 /// combined with a load / store to form a post-indexed load / store. 12213 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 12214 SDValue &Base, 12215 SDValue &Offset, 12216 ISD::MemIndexedMode &AM, 12217 SelectionDAG &DAG) const { 12218 EVT VT; 12219 SDValue Ptr; 12220 bool isSEXTLoad = false, isNonExt; 12221 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12222 VT = LD->getMemoryVT(); 12223 Ptr = LD->getBasePtr(); 12224 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12225 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 12226 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12227 VT = ST->getMemoryVT(); 12228 Ptr = ST->getBasePtr(); 12229 isNonExt = !ST->isTruncatingStore(); 12230 } else 12231 return false; 12232 12233 if (Subtarget->isThumb1Only()) { 12234 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 12235 // must be non-extending/truncating, i32, with an offset of 4. 12236 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 12237 if (Op->getOpcode() != ISD::ADD || !isNonExt) 12238 return false; 12239 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 12240 if (!RHS || RHS->getZExtValue() != 4) 12241 return false; 12242 12243 Offset = Op->getOperand(1); 12244 Base = Op->getOperand(0); 12245 AM = ISD::POST_INC; 12246 return true; 12247 } 12248 12249 bool isInc; 12250 bool isLegal = false; 12251 if (Subtarget->isThumb2()) 12252 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12253 isInc, DAG); 12254 else 12255 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12256 isInc, DAG); 12257 if (!isLegal) 12258 return false; 12259 12260 if (Ptr != Base) { 12261 // Swap base ptr and offset to catch more post-index load / store when 12262 // it's legal. In Thumb2 mode, offset must be an immediate. 12263 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 12264 !Subtarget->isThumb2()) 12265 std::swap(Base, Offset); 12266 12267 // Post-indexed load / store update the base pointer. 12268 if (Ptr != Base) 12269 return false; 12270 } 12271 12272 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 12273 return true; 12274 } 12275 12276 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12277 APInt &KnownZero, 12278 APInt &KnownOne, 12279 const SelectionDAG &DAG, 12280 unsigned Depth) const { 12281 unsigned BitWidth = KnownOne.getBitWidth(); 12282 KnownZero = KnownOne = APInt(BitWidth, 0); 12283 switch (Op.getOpcode()) { 12284 default: break; 12285 case ARMISD::ADDC: 12286 case ARMISD::ADDE: 12287 case ARMISD::SUBC: 12288 case ARMISD::SUBE: 12289 // These nodes' second result is a boolean 12290 if (Op.getResNo() == 0) 12291 break; 12292 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 12293 break; 12294 case ARMISD::CMOV: { 12295 // Bits are known zero/one if known on the LHS and RHS. 12296 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 12297 if (KnownZero == 0 && KnownOne == 0) return; 12298 12299 APInt KnownZeroRHS, KnownOneRHS; 12300 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 12301 KnownZero &= KnownZeroRHS; 12302 KnownOne &= KnownOneRHS; 12303 return; 12304 } 12305 case ISD::INTRINSIC_W_CHAIN: { 12306 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 12307 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 12308 switch (IntID) { 12309 default: return; 12310 case Intrinsic::arm_ldaex: 12311 case Intrinsic::arm_ldrex: { 12312 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 12313 unsigned MemBits = VT.getScalarSizeInBits(); 12314 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 12315 return; 12316 } 12317 } 12318 } 12319 } 12320 } 12321 12322 //===----------------------------------------------------------------------===// 12323 // ARM Inline Assembly Support 12324 //===----------------------------------------------------------------------===// 12325 12326 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 12327 // Looking for "rev" which is V6+. 12328 if (!Subtarget->hasV6Ops()) 12329 return false; 12330 12331 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 12332 std::string AsmStr = IA->getAsmString(); 12333 SmallVector<StringRef, 4> AsmPieces; 12334 SplitString(AsmStr, AsmPieces, ";\n"); 12335 12336 switch (AsmPieces.size()) { 12337 default: return false; 12338 case 1: 12339 AsmStr = AsmPieces[0]; 12340 AsmPieces.clear(); 12341 SplitString(AsmStr, AsmPieces, " \t,"); 12342 12343 // rev $0, $1 12344 if (AsmPieces.size() == 3 && 12345 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 12346 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 12347 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12348 if (Ty && Ty->getBitWidth() == 32) 12349 return IntrinsicLowering::LowerToByteSwap(CI); 12350 } 12351 break; 12352 } 12353 12354 return false; 12355 } 12356 12357 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 12358 // At this point, we have to lower this constraint to something else, so we 12359 // lower it to an "r" or "w". However, by doing this we will force the result 12360 // to be in register, while the X constraint is much more permissive. 12361 // 12362 // Although we are correct (we are free to emit anything, without 12363 // constraints), we might break use cases that would expect us to be more 12364 // efficient and emit something else. 12365 if (!Subtarget->hasVFP2()) 12366 return "r"; 12367 if (ConstraintVT.isFloatingPoint()) 12368 return "w"; 12369 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 12370 (ConstraintVT.getSizeInBits() == 64 || 12371 ConstraintVT.getSizeInBits() == 128)) 12372 return "w"; 12373 12374 return "r"; 12375 } 12376 12377 /// getConstraintType - Given a constraint letter, return the type of 12378 /// constraint it is for this target. 12379 ARMTargetLowering::ConstraintType 12380 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 12381 if (Constraint.size() == 1) { 12382 switch (Constraint[0]) { 12383 default: break; 12384 case 'l': return C_RegisterClass; 12385 case 'w': return C_RegisterClass; 12386 case 'h': return C_RegisterClass; 12387 case 'x': return C_RegisterClass; 12388 case 't': return C_RegisterClass; 12389 case 'j': return C_Other; // Constant for movw. 12390 // An address with a single base register. Due to the way we 12391 // currently handle addresses it is the same as an 'r' memory constraint. 12392 case 'Q': return C_Memory; 12393 } 12394 } else if (Constraint.size() == 2) { 12395 switch (Constraint[0]) { 12396 default: break; 12397 // All 'U+' constraints are addresses. 12398 case 'U': return C_Memory; 12399 } 12400 } 12401 return TargetLowering::getConstraintType(Constraint); 12402 } 12403 12404 /// Examine constraint type and operand type and determine a weight value. 12405 /// This object must already have been set up with the operand type 12406 /// and the current alternative constraint selected. 12407 TargetLowering::ConstraintWeight 12408 ARMTargetLowering::getSingleConstraintMatchWeight( 12409 AsmOperandInfo &info, const char *constraint) const { 12410 ConstraintWeight weight = CW_Invalid; 12411 Value *CallOperandVal = info.CallOperandVal; 12412 // If we don't have a value, we can't do a match, 12413 // but allow it at the lowest weight. 12414 if (!CallOperandVal) 12415 return CW_Default; 12416 Type *type = CallOperandVal->getType(); 12417 // Look at the constraint type. 12418 switch (*constraint) { 12419 default: 12420 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12421 break; 12422 case 'l': 12423 if (type->isIntegerTy()) { 12424 if (Subtarget->isThumb()) 12425 weight = CW_SpecificReg; 12426 else 12427 weight = CW_Register; 12428 } 12429 break; 12430 case 'w': 12431 if (type->isFloatingPointTy()) 12432 weight = CW_Register; 12433 break; 12434 } 12435 return weight; 12436 } 12437 12438 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 12439 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 12440 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 12441 if (Constraint.size() == 1) { 12442 // GCC ARM Constraint Letters 12443 switch (Constraint[0]) { 12444 case 'l': // Low regs or general regs. 12445 if (Subtarget->isThumb()) 12446 return RCPair(0U, &ARM::tGPRRegClass); 12447 return RCPair(0U, &ARM::GPRRegClass); 12448 case 'h': // High regs or no regs. 12449 if (Subtarget->isThumb()) 12450 return RCPair(0U, &ARM::hGPRRegClass); 12451 break; 12452 case 'r': 12453 if (Subtarget->isThumb1Only()) 12454 return RCPair(0U, &ARM::tGPRRegClass); 12455 return RCPair(0U, &ARM::GPRRegClass); 12456 case 'w': 12457 if (VT == MVT::Other) 12458 break; 12459 if (VT == MVT::f32) 12460 return RCPair(0U, &ARM::SPRRegClass); 12461 if (VT.getSizeInBits() == 64) 12462 return RCPair(0U, &ARM::DPRRegClass); 12463 if (VT.getSizeInBits() == 128) 12464 return RCPair(0U, &ARM::QPRRegClass); 12465 break; 12466 case 'x': 12467 if (VT == MVT::Other) 12468 break; 12469 if (VT == MVT::f32) 12470 return RCPair(0U, &ARM::SPR_8RegClass); 12471 if (VT.getSizeInBits() == 64) 12472 return RCPair(0U, &ARM::DPR_8RegClass); 12473 if (VT.getSizeInBits() == 128) 12474 return RCPair(0U, &ARM::QPR_8RegClass); 12475 break; 12476 case 't': 12477 if (VT == MVT::f32) 12478 return RCPair(0U, &ARM::SPRRegClass); 12479 break; 12480 } 12481 } 12482 if (StringRef("{cc}").equals_lower(Constraint)) 12483 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 12484 12485 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12486 } 12487 12488 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12489 /// vector. If it is invalid, don't add anything to Ops. 12490 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12491 std::string &Constraint, 12492 std::vector<SDValue>&Ops, 12493 SelectionDAG &DAG) const { 12494 SDValue Result; 12495 12496 // Currently only support length 1 constraints. 12497 if (Constraint.length() != 1) return; 12498 12499 char ConstraintLetter = Constraint[0]; 12500 switch (ConstraintLetter) { 12501 default: break; 12502 case 'j': 12503 case 'I': case 'J': case 'K': case 'L': 12504 case 'M': case 'N': case 'O': 12505 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 12506 if (!C) 12507 return; 12508 12509 int64_t CVal64 = C->getSExtValue(); 12510 int CVal = (int) CVal64; 12511 // None of these constraints allow values larger than 32 bits. Check 12512 // that the value fits in an int. 12513 if (CVal != CVal64) 12514 return; 12515 12516 switch (ConstraintLetter) { 12517 case 'j': 12518 // Constant suitable for movw, must be between 0 and 12519 // 65535. 12520 if (Subtarget->hasV6T2Ops()) 12521 if (CVal >= 0 && CVal <= 65535) 12522 break; 12523 return; 12524 case 'I': 12525 if (Subtarget->isThumb1Only()) { 12526 // This must be a constant between 0 and 255, for ADD 12527 // immediates. 12528 if (CVal >= 0 && CVal <= 255) 12529 break; 12530 } else if (Subtarget->isThumb2()) { 12531 // A constant that can be used as an immediate value in a 12532 // data-processing instruction. 12533 if (ARM_AM::getT2SOImmVal(CVal) != -1) 12534 break; 12535 } else { 12536 // A constant that can be used as an immediate value in a 12537 // data-processing instruction. 12538 if (ARM_AM::getSOImmVal(CVal) != -1) 12539 break; 12540 } 12541 return; 12542 12543 case 'J': 12544 if (Subtarget->isThumb1Only()) { 12545 // This must be a constant between -255 and -1, for negated ADD 12546 // immediates. This can be used in GCC with an "n" modifier that 12547 // prints the negated value, for use with SUB instructions. It is 12548 // not useful otherwise but is implemented for compatibility. 12549 if (CVal >= -255 && CVal <= -1) 12550 break; 12551 } else { 12552 // This must be a constant between -4095 and 4095. It is not clear 12553 // what this constraint is intended for. Implemented for 12554 // compatibility with GCC. 12555 if (CVal >= -4095 && CVal <= 4095) 12556 break; 12557 } 12558 return; 12559 12560 case 'K': 12561 if (Subtarget->isThumb1Only()) { 12562 // A 32-bit value where only one byte has a nonzero value. Exclude 12563 // zero to match GCC. This constraint is used by GCC internally for 12564 // constants that can be loaded with a move/shift combination. 12565 // It is not useful otherwise but is implemented for compatibility. 12566 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 12567 break; 12568 } else if (Subtarget->isThumb2()) { 12569 // A constant whose bitwise inverse can be used as an immediate 12570 // value in a data-processing instruction. This can be used in GCC 12571 // with a "B" modifier that prints the inverted value, for use with 12572 // BIC and MVN instructions. It is not useful otherwise but is 12573 // implemented for compatibility. 12574 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 12575 break; 12576 } else { 12577 // A constant whose bitwise inverse can be used as an immediate 12578 // value in a data-processing instruction. This can be used in GCC 12579 // with a "B" modifier that prints the inverted value, for use with 12580 // BIC and MVN instructions. It is not useful otherwise but is 12581 // implemented for compatibility. 12582 if (ARM_AM::getSOImmVal(~CVal) != -1) 12583 break; 12584 } 12585 return; 12586 12587 case 'L': 12588 if (Subtarget->isThumb1Only()) { 12589 // This must be a constant between -7 and 7, 12590 // for 3-operand ADD/SUB immediate instructions. 12591 if (CVal >= -7 && CVal < 7) 12592 break; 12593 } else if (Subtarget->isThumb2()) { 12594 // A constant whose negation can be used as an immediate value in a 12595 // data-processing instruction. This can be used in GCC with an "n" 12596 // modifier that prints the negated value, for use with SUB 12597 // instructions. It is not useful otherwise but is implemented for 12598 // compatibility. 12599 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 12600 break; 12601 } else { 12602 // A constant whose negation can be used as an immediate value in a 12603 // data-processing instruction. This can be used in GCC with an "n" 12604 // modifier that prints the negated value, for use with SUB 12605 // instructions. It is not useful otherwise but is implemented for 12606 // compatibility. 12607 if (ARM_AM::getSOImmVal(-CVal) != -1) 12608 break; 12609 } 12610 return; 12611 12612 case 'M': 12613 if (Subtarget->isThumb1Only()) { 12614 // This must be a multiple of 4 between 0 and 1020, for 12615 // ADD sp + immediate. 12616 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 12617 break; 12618 } else { 12619 // A power of two or a constant between 0 and 32. This is used in 12620 // GCC for the shift amount on shifted register operands, but it is 12621 // useful in general for any shift amounts. 12622 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 12623 break; 12624 } 12625 return; 12626 12627 case 'N': 12628 if (Subtarget->isThumb()) { // FIXME thumb2 12629 // This must be a constant between 0 and 31, for shift amounts. 12630 if (CVal >= 0 && CVal <= 31) 12631 break; 12632 } 12633 return; 12634 12635 case 'O': 12636 if (Subtarget->isThumb()) { // FIXME thumb2 12637 // This must be a multiple of 4 between -508 and 508, for 12638 // ADD/SUB sp = sp + immediate. 12639 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 12640 break; 12641 } 12642 return; 12643 } 12644 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 12645 break; 12646 } 12647 12648 if (Result.getNode()) { 12649 Ops.push_back(Result); 12650 return; 12651 } 12652 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12653 } 12654 12655 static RTLIB::Libcall getDivRemLibcall( 12656 const SDNode *N, MVT::SimpleValueType SVT) { 12657 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12658 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12659 "Unhandled Opcode in getDivRemLibcall"); 12660 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12661 N->getOpcode() == ISD::SREM; 12662 RTLIB::Libcall LC; 12663 switch (SVT) { 12664 default: llvm_unreachable("Unexpected request for libcall!"); 12665 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 12666 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 12667 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 12668 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 12669 } 12670 return LC; 12671 } 12672 12673 static TargetLowering::ArgListTy getDivRemArgList( 12674 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 12675 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12676 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12677 "Unhandled Opcode in getDivRemArgList"); 12678 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12679 N->getOpcode() == ISD::SREM; 12680 TargetLowering::ArgListTy Args; 12681 TargetLowering::ArgListEntry Entry; 12682 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12683 EVT ArgVT = N->getOperand(i).getValueType(); 12684 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 12685 Entry.Node = N->getOperand(i); 12686 Entry.Ty = ArgTy; 12687 Entry.isSExt = isSigned; 12688 Entry.isZExt = !isSigned; 12689 Args.push_back(Entry); 12690 } 12691 if (Subtarget->isTargetWindows() && Args.size() >= 2) 12692 std::swap(Args[0], Args[1]); 12693 return Args; 12694 } 12695 12696 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 12697 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 12698 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 12699 Subtarget->isTargetWindows()) && 12700 "Register-based DivRem lowering only"); 12701 unsigned Opcode = Op->getOpcode(); 12702 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 12703 "Invalid opcode for Div/Rem lowering"); 12704 bool isSigned = (Opcode == ISD::SDIVREM); 12705 EVT VT = Op->getValueType(0); 12706 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 12707 SDLoc dl(Op); 12708 12709 // If the target has hardware divide, use divide + multiply + subtract: 12710 // div = a / b 12711 // rem = a - b * div 12712 // return {div, rem} 12713 // This should be lowered into UDIV/SDIV + MLS later on. 12714 if (Subtarget->hasDivide() && Op->getValueType(0).isSimple() && 12715 Op->getSimpleValueType(0) == MVT::i32) { 12716 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 12717 const SDValue Dividend = Op->getOperand(0); 12718 const SDValue Divisor = Op->getOperand(1); 12719 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 12720 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 12721 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 12722 12723 SDValue Values[2] = {Div, Rem}; 12724 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 12725 } 12726 12727 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 12728 VT.getSimpleVT().SimpleTy); 12729 SDValue InChain = DAG.getEntryNode(); 12730 12731 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 12732 DAG.getContext(), 12733 Subtarget); 12734 12735 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 12736 getPointerTy(DAG.getDataLayout())); 12737 12738 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 12739 12740 if (Subtarget->isTargetWindows()) 12741 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 12742 12743 TargetLowering::CallLoweringInfo CLI(DAG); 12744 CLI.setDebugLoc(dl).setChain(InChain) 12745 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 12746 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 12747 12748 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 12749 return CallInfo.first; 12750 } 12751 12752 // Lowers REM using divmod helpers 12753 // see RTABI section 4.2/4.3 12754 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 12755 // Build return types (div and rem) 12756 std::vector<Type*> RetTyParams; 12757 Type *RetTyElement; 12758 12759 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 12760 default: llvm_unreachable("Unexpected request for libcall!"); 12761 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 12762 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 12763 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 12764 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 12765 } 12766 12767 RetTyParams.push_back(RetTyElement); 12768 RetTyParams.push_back(RetTyElement); 12769 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 12770 Type *RetTy = StructType::get(*DAG.getContext(), ret); 12771 12772 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 12773 SimpleTy); 12774 SDValue InChain = DAG.getEntryNode(); 12775 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 12776 Subtarget); 12777 bool isSigned = N->getOpcode() == ISD::SREM; 12778 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 12779 getPointerTy(DAG.getDataLayout())); 12780 12781 if (Subtarget->isTargetWindows()) 12782 InChain = WinDBZCheckDenominator(DAG, N, InChain); 12783 12784 // Lower call 12785 CallLoweringInfo CLI(DAG); 12786 CLI.setChain(InChain) 12787 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 12788 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 12789 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 12790 12791 // Return second (rem) result operand (first contains div) 12792 SDNode *ResNode = CallResult.first.getNode(); 12793 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 12794 return ResNode->getOperand(1); 12795 } 12796 12797 SDValue 12798 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 12799 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 12800 SDLoc DL(Op); 12801 12802 // Get the inputs. 12803 SDValue Chain = Op.getOperand(0); 12804 SDValue Size = Op.getOperand(1); 12805 12806 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 12807 DAG.getConstant(2, DL, MVT::i32)); 12808 12809 SDValue Flag; 12810 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 12811 Flag = Chain.getValue(1); 12812 12813 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 12814 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 12815 12816 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 12817 Chain = NewSP.getValue(1); 12818 12819 SDValue Ops[2] = { NewSP, Chain }; 12820 return DAG.getMergeValues(Ops, DL); 12821 } 12822 12823 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 12824 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 12825 "Unexpected type for custom-lowering FP_EXTEND"); 12826 12827 RTLIB::Libcall LC; 12828 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 12829 12830 SDValue SrcVal = Op.getOperand(0); 12831 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 12832 SDLoc(Op)).first; 12833 } 12834 12835 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 12836 assert(Op.getOperand(0).getValueType() == MVT::f64 && 12837 Subtarget->isFPOnlySP() && 12838 "Unexpected type for custom-lowering FP_ROUND"); 12839 12840 RTLIB::Libcall LC; 12841 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 12842 12843 SDValue SrcVal = Op.getOperand(0); 12844 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 12845 SDLoc(Op)).first; 12846 } 12847 12848 bool 12849 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 12850 // The ARM target isn't yet aware of offsets. 12851 return false; 12852 } 12853 12854 bool ARM::isBitFieldInvertedMask(unsigned v) { 12855 if (v == 0xffffffff) 12856 return false; 12857 12858 // there can be 1's on either or both "outsides", all the "inside" 12859 // bits must be 0's 12860 return isShiftedMask_32(~v); 12861 } 12862 12863 /// isFPImmLegal - Returns true if the target can instruction select the 12864 /// specified FP immediate natively. If false, the legalizer will 12865 /// materialize the FP immediate as a load from a constant pool. 12866 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 12867 if (!Subtarget->hasVFP3()) 12868 return false; 12869 if (VT == MVT::f32) 12870 return ARM_AM::getFP32Imm(Imm) != -1; 12871 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 12872 return ARM_AM::getFP64Imm(Imm) != -1; 12873 return false; 12874 } 12875 12876 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 12877 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 12878 /// specified in the intrinsic calls. 12879 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 12880 const CallInst &I, 12881 unsigned Intrinsic) const { 12882 switch (Intrinsic) { 12883 case Intrinsic::arm_neon_vld1: 12884 case Intrinsic::arm_neon_vld2: 12885 case Intrinsic::arm_neon_vld3: 12886 case Intrinsic::arm_neon_vld4: 12887 case Intrinsic::arm_neon_vld2lane: 12888 case Intrinsic::arm_neon_vld3lane: 12889 case Intrinsic::arm_neon_vld4lane: { 12890 Info.opc = ISD::INTRINSIC_W_CHAIN; 12891 // Conservatively set memVT to the entire set of vectors loaded. 12892 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12893 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 12894 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12895 Info.ptrVal = I.getArgOperand(0); 12896 Info.offset = 0; 12897 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12898 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12899 Info.vol = false; // volatile loads with NEON intrinsics not supported 12900 Info.readMem = true; 12901 Info.writeMem = false; 12902 return true; 12903 } 12904 case Intrinsic::arm_neon_vst1: 12905 case Intrinsic::arm_neon_vst2: 12906 case Intrinsic::arm_neon_vst3: 12907 case Intrinsic::arm_neon_vst4: 12908 case Intrinsic::arm_neon_vst2lane: 12909 case Intrinsic::arm_neon_vst3lane: 12910 case Intrinsic::arm_neon_vst4lane: { 12911 Info.opc = ISD::INTRINSIC_VOID; 12912 // Conservatively set memVT to the entire set of vectors stored. 12913 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12914 unsigned NumElts = 0; 12915 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 12916 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 12917 if (!ArgTy->isVectorTy()) 12918 break; 12919 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 12920 } 12921 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12922 Info.ptrVal = I.getArgOperand(0); 12923 Info.offset = 0; 12924 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12925 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12926 Info.vol = false; // volatile stores with NEON intrinsics not supported 12927 Info.readMem = false; 12928 Info.writeMem = true; 12929 return true; 12930 } 12931 case Intrinsic::arm_ldaex: 12932 case Intrinsic::arm_ldrex: { 12933 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12934 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 12935 Info.opc = ISD::INTRINSIC_W_CHAIN; 12936 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12937 Info.ptrVal = I.getArgOperand(0); 12938 Info.offset = 0; 12939 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12940 Info.vol = true; 12941 Info.readMem = true; 12942 Info.writeMem = false; 12943 return true; 12944 } 12945 case Intrinsic::arm_stlex: 12946 case Intrinsic::arm_strex: { 12947 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12948 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 12949 Info.opc = ISD::INTRINSIC_W_CHAIN; 12950 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12951 Info.ptrVal = I.getArgOperand(1); 12952 Info.offset = 0; 12953 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12954 Info.vol = true; 12955 Info.readMem = false; 12956 Info.writeMem = true; 12957 return true; 12958 } 12959 case Intrinsic::arm_stlexd: 12960 case Intrinsic::arm_strexd: 12961 Info.opc = ISD::INTRINSIC_W_CHAIN; 12962 Info.memVT = MVT::i64; 12963 Info.ptrVal = I.getArgOperand(2); 12964 Info.offset = 0; 12965 Info.align = 8; 12966 Info.vol = true; 12967 Info.readMem = false; 12968 Info.writeMem = true; 12969 return true; 12970 12971 case Intrinsic::arm_ldaexd: 12972 case Intrinsic::arm_ldrexd: 12973 Info.opc = ISD::INTRINSIC_W_CHAIN; 12974 Info.memVT = MVT::i64; 12975 Info.ptrVal = I.getArgOperand(0); 12976 Info.offset = 0; 12977 Info.align = 8; 12978 Info.vol = true; 12979 Info.readMem = true; 12980 Info.writeMem = false; 12981 return true; 12982 12983 default: 12984 break; 12985 } 12986 12987 return false; 12988 } 12989 12990 /// \brief Returns true if it is beneficial to convert a load of a constant 12991 /// to just the constant itself. 12992 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 12993 Type *Ty) const { 12994 assert(Ty->isIntegerTy()); 12995 12996 unsigned Bits = Ty->getPrimitiveSizeInBits(); 12997 if (Bits == 0 || Bits > 32) 12998 return false; 12999 return true; 13000 } 13001 13002 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, 13003 unsigned Index) const { 13004 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 13005 return false; 13006 13007 return (Index == 0 || Index == ResVT.getVectorNumElements()); 13008 } 13009 13010 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 13011 ARM_MB::MemBOpt Domain) const { 13012 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13013 13014 // First, if the target has no DMB, see what fallback we can use. 13015 if (!Subtarget->hasDataBarrier()) { 13016 // Some ARMv6 cpus can support data barriers with an mcr instruction. 13017 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 13018 // here. 13019 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 13020 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 13021 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 13022 Builder.getInt32(0), Builder.getInt32(7), 13023 Builder.getInt32(10), Builder.getInt32(5)}; 13024 return Builder.CreateCall(MCR, args); 13025 } else { 13026 // Instead of using barriers, atomic accesses on these subtargets use 13027 // libcalls. 13028 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 13029 } 13030 } else { 13031 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 13032 // Only a full system barrier exists in the M-class architectures. 13033 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 13034 Constant *CDomain = Builder.getInt32(Domain); 13035 return Builder.CreateCall(DMB, CDomain); 13036 } 13037 } 13038 13039 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 13040 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 13041 AtomicOrdering Ord, bool IsStore, 13042 bool IsLoad) const { 13043 switch (Ord) { 13044 case AtomicOrdering::NotAtomic: 13045 case AtomicOrdering::Unordered: 13046 llvm_unreachable("Invalid fence: unordered/non-atomic"); 13047 case AtomicOrdering::Monotonic: 13048 case AtomicOrdering::Acquire: 13049 return nullptr; // Nothing to do 13050 case AtomicOrdering::SequentiallyConsistent: 13051 if (!IsStore) 13052 return nullptr; // Nothing to do 13053 /*FALLTHROUGH*/ 13054 case AtomicOrdering::Release: 13055 case AtomicOrdering::AcquireRelease: 13056 if (Subtarget->preferISHSTBarriers()) 13057 return makeDMB(Builder, ARM_MB::ISHST); 13058 // FIXME: add a comment with a link to documentation justifying this. 13059 else 13060 return makeDMB(Builder, ARM_MB::ISH); 13061 } 13062 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 13063 } 13064 13065 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 13066 AtomicOrdering Ord, bool IsStore, 13067 bool IsLoad) const { 13068 switch (Ord) { 13069 case AtomicOrdering::NotAtomic: 13070 case AtomicOrdering::Unordered: 13071 llvm_unreachable("Invalid fence: unordered/not-atomic"); 13072 case AtomicOrdering::Monotonic: 13073 case AtomicOrdering::Release: 13074 return nullptr; // Nothing to do 13075 case AtomicOrdering::Acquire: 13076 case AtomicOrdering::AcquireRelease: 13077 case AtomicOrdering::SequentiallyConsistent: 13078 return makeDMB(Builder, ARM_MB::ISH); 13079 } 13080 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 13081 } 13082 13083 // Loads and stores less than 64-bits are already atomic; ones above that 13084 // are doomed anyway, so defer to the default libcall and blame the OS when 13085 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13086 // anything for those. 13087 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 13088 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 13089 return (Size == 64) && !Subtarget->isMClass(); 13090 } 13091 13092 // Loads and stores less than 64-bits are already atomic; ones above that 13093 // are doomed anyway, so defer to the default libcall and blame the OS when 13094 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13095 // anything for those. 13096 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 13097 // guarantee, see DDI0406C ARM architecture reference manual, 13098 // sections A8.8.72-74 LDRD) 13099 TargetLowering::AtomicExpansionKind 13100 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 13101 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 13102 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 13103 : AtomicExpansionKind::None; 13104 } 13105 13106 // For the real atomic operations, we have ldrex/strex up to 32 bits, 13107 // and up to 64 bits on the non-M profiles 13108 TargetLowering::AtomicExpansionKind 13109 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 13110 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 13111 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13112 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 13113 ? AtomicExpansionKind::LLSC 13114 : AtomicExpansionKind::None; 13115 } 13116 13117 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 13118 AtomicCmpXchgInst *AI) const { 13119 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 13120 // implement cmpxchg without spilling. If the address being exchanged is also 13121 // on the stack and close enough to the spill slot, this can lead to a 13122 // situation where the monitor always gets cleared and the atomic operation 13123 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 13124 bool hasAtomicCmpXchg = 13125 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13126 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 13127 } 13128 13129 bool ARMTargetLowering::shouldInsertFencesForAtomic( 13130 const Instruction *I) const { 13131 return InsertFencesForAtomic; 13132 } 13133 13134 // This has so far only been implemented for MachO. 13135 bool ARMTargetLowering::useLoadStackGuardNode() const { 13136 return Subtarget->isTargetMachO(); 13137 } 13138 13139 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 13140 unsigned &Cost) const { 13141 // If we do not have NEON, vector types are not natively supported. 13142 if (!Subtarget->hasNEON()) 13143 return false; 13144 13145 // Floating point values and vector values map to the same register file. 13146 // Therefore, although we could do a store extract of a vector type, this is 13147 // better to leave at float as we have more freedom in the addressing mode for 13148 // those. 13149 if (VectorTy->isFPOrFPVectorTy()) 13150 return false; 13151 13152 // If the index is unknown at compile time, this is very expensive to lower 13153 // and it is not possible to combine the store with the extract. 13154 if (!isa<ConstantInt>(Idx)) 13155 return false; 13156 13157 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 13158 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 13159 // We can do a store + vector extract on any vector that fits perfectly in a D 13160 // or Q register. 13161 if (BitWidth == 64 || BitWidth == 128) { 13162 Cost = 0; 13163 return true; 13164 } 13165 return false; 13166 } 13167 13168 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 13169 return Subtarget->hasV6T2Ops(); 13170 } 13171 13172 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 13173 return Subtarget->hasV6T2Ops(); 13174 } 13175 13176 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 13177 AtomicOrdering Ord) const { 13178 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13179 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 13180 bool IsAcquire = isAcquireOrStronger(Ord); 13181 13182 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 13183 // intrinsic must return {i32, i32} and we have to recombine them into a 13184 // single i64 here. 13185 if (ValTy->getPrimitiveSizeInBits() == 64) { 13186 Intrinsic::ID Int = 13187 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 13188 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 13189 13190 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13191 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 13192 13193 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 13194 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 13195 if (!Subtarget->isLittle()) 13196 std::swap (Lo, Hi); 13197 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 13198 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 13199 return Builder.CreateOr( 13200 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 13201 } 13202 13203 Type *Tys[] = { Addr->getType() }; 13204 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 13205 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 13206 13207 return Builder.CreateTruncOrBitCast( 13208 Builder.CreateCall(Ldrex, Addr), 13209 cast<PointerType>(Addr->getType())->getElementType()); 13210 } 13211 13212 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 13213 IRBuilder<> &Builder) const { 13214 if (!Subtarget->hasV7Ops()) 13215 return; 13216 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13217 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 13218 } 13219 13220 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 13221 Value *Addr, 13222 AtomicOrdering Ord) const { 13223 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13224 bool IsRelease = isReleaseOrStronger(Ord); 13225 13226 // Since the intrinsics must have legal type, the i64 intrinsics take two 13227 // parameters: "i32, i32". We must marshal Val into the appropriate form 13228 // before the call. 13229 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 13230 Intrinsic::ID Int = 13231 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 13232 Function *Strex = Intrinsic::getDeclaration(M, Int); 13233 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 13234 13235 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 13236 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 13237 if (!Subtarget->isLittle()) 13238 std::swap (Lo, Hi); 13239 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13240 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 13241 } 13242 13243 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 13244 Type *Tys[] = { Addr->getType() }; 13245 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 13246 13247 return Builder.CreateCall( 13248 Strex, {Builder.CreateZExtOrBitCast( 13249 Val, Strex->getFunctionType()->getParamType(0)), 13250 Addr}); 13251 } 13252 13253 /// \brief Lower an interleaved load into a vldN intrinsic. 13254 /// 13255 /// E.g. Lower an interleaved load (Factor = 2): 13256 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 13257 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 13258 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 13259 /// 13260 /// Into: 13261 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 13262 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 13263 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 13264 bool ARMTargetLowering::lowerInterleavedLoad( 13265 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 13266 ArrayRef<unsigned> Indices, unsigned Factor) const { 13267 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 13268 "Invalid interleave factor"); 13269 assert(!Shuffles.empty() && "Empty shufflevector input"); 13270 assert(Shuffles.size() == Indices.size() && 13271 "Unmatched number of shufflevectors and indices"); 13272 13273 VectorType *VecTy = Shuffles[0]->getType(); 13274 Type *EltTy = VecTy->getVectorElementType(); 13275 13276 const DataLayout &DL = LI->getModule()->getDataLayout(); 13277 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 13278 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 13279 13280 // Skip if we do not have NEON and skip illegal vector types and vector types 13281 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 13282 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 13283 return false; 13284 13285 // A pointer vector can not be the return type of the ldN intrinsics. Need to 13286 // load integer vectors first and then convert to pointer vectors. 13287 if (EltTy->isPointerTy()) 13288 VecTy = 13289 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 13290 13291 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 13292 Intrinsic::arm_neon_vld3, 13293 Intrinsic::arm_neon_vld4}; 13294 13295 IRBuilder<> Builder(LI); 13296 SmallVector<Value *, 2> Ops; 13297 13298 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 13299 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 13300 Ops.push_back(Builder.getInt32(LI->getAlignment())); 13301 13302 Type *Tys[] = { VecTy, Int8Ptr }; 13303 Function *VldnFunc = 13304 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 13305 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 13306 13307 // Replace uses of each shufflevector with the corresponding vector loaded 13308 // by ldN. 13309 for (unsigned i = 0; i < Shuffles.size(); i++) { 13310 ShuffleVectorInst *SV = Shuffles[i]; 13311 unsigned Index = Indices[i]; 13312 13313 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 13314 13315 // Convert the integer vector to pointer vector if the element is pointer. 13316 if (EltTy->isPointerTy()) 13317 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 13318 13319 SV->replaceAllUsesWith(SubVec); 13320 } 13321 13322 return true; 13323 } 13324 13325 /// \brief Lower an interleaved store into a vstN intrinsic. 13326 /// 13327 /// E.g. Lower an interleaved store (Factor = 3): 13328 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 13329 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 13330 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 13331 /// 13332 /// Into: 13333 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 13334 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 13335 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 13336 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 13337 /// 13338 /// Note that the new shufflevectors will be removed and we'll only generate one 13339 /// vst3 instruction in CodeGen. 13340 /// 13341 /// Example for a more general valid mask (Factor 3). Lower: 13342 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 13343 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 13344 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 13345 /// 13346 /// Into: 13347 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 13348 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 13349 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 13350 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 13351 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 13352 ShuffleVectorInst *SVI, 13353 unsigned Factor) const { 13354 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 13355 "Invalid interleave factor"); 13356 13357 VectorType *VecTy = SVI->getType(); 13358 assert(VecTy->getVectorNumElements() % Factor == 0 && 13359 "Invalid interleaved store"); 13360 13361 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 13362 Type *EltTy = VecTy->getVectorElementType(); 13363 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 13364 13365 const DataLayout &DL = SI->getModule()->getDataLayout(); 13366 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 13367 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 13368 13369 // Skip if we do not have NEON and skip illegal vector types and vector types 13370 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 13371 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 13372 EltIs64Bits) 13373 return false; 13374 13375 Value *Op0 = SVI->getOperand(0); 13376 Value *Op1 = SVI->getOperand(1); 13377 IRBuilder<> Builder(SI); 13378 13379 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 13380 // vectors to integer vectors. 13381 if (EltTy->isPointerTy()) { 13382 Type *IntTy = DL.getIntPtrType(EltTy); 13383 13384 // Convert to the corresponding integer vector. 13385 Type *IntVecTy = 13386 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 13387 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 13388 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 13389 13390 SubVecTy = VectorType::get(IntTy, LaneLen); 13391 } 13392 13393 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 13394 Intrinsic::arm_neon_vst3, 13395 Intrinsic::arm_neon_vst4}; 13396 SmallVector<Value *, 6> Ops; 13397 13398 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 13399 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 13400 13401 Type *Tys[] = { Int8Ptr, SubVecTy }; 13402 Function *VstNFunc = Intrinsic::getDeclaration( 13403 SI->getModule(), StoreInts[Factor - 2], Tys); 13404 13405 // Split the shufflevector operands into sub vectors for the new vstN call. 13406 auto Mask = SVI->getShuffleMask(); 13407 for (unsigned i = 0; i < Factor; i++) { 13408 if (Mask[i] >= 0) { 13409 Ops.push_back(Builder.CreateShuffleVector( 13410 Op0, Op1, createSequentialMask(Builder, Mask[i], LaneLen, 0))); 13411 } else { 13412 unsigned StartMask = 0; 13413 for (unsigned j = 1; j < LaneLen; j++) { 13414 if (Mask[j*Factor + i] >= 0) { 13415 StartMask = Mask[j*Factor + i] - j; 13416 break; 13417 } 13418 } 13419 // Note: If all elements in a chunk are undefs, StartMask=0! 13420 // Note: Filling undef gaps with random elements is ok, since 13421 // those elements were being written anyway (with undefs). 13422 // In the case of all undefs we're defaulting to using elems from 0 13423 // Note: StartMask cannot be negative, it's checked in isReInterleaveMask 13424 Ops.push_back(Builder.CreateShuffleVector( 13425 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 13426 } 13427 } 13428 13429 Ops.push_back(Builder.getInt32(SI->getAlignment())); 13430 Builder.CreateCall(VstNFunc, Ops); 13431 return true; 13432 } 13433 13434 enum HABaseType { 13435 HA_UNKNOWN = 0, 13436 HA_FLOAT, 13437 HA_DOUBLE, 13438 HA_VECT64, 13439 HA_VECT128 13440 }; 13441 13442 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 13443 uint64_t &Members) { 13444 if (auto *ST = dyn_cast<StructType>(Ty)) { 13445 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 13446 uint64_t SubMembers = 0; 13447 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 13448 return false; 13449 Members += SubMembers; 13450 } 13451 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 13452 uint64_t SubMembers = 0; 13453 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 13454 return false; 13455 Members += SubMembers * AT->getNumElements(); 13456 } else if (Ty->isFloatTy()) { 13457 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 13458 return false; 13459 Members = 1; 13460 Base = HA_FLOAT; 13461 } else if (Ty->isDoubleTy()) { 13462 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 13463 return false; 13464 Members = 1; 13465 Base = HA_DOUBLE; 13466 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 13467 Members = 1; 13468 switch (Base) { 13469 case HA_FLOAT: 13470 case HA_DOUBLE: 13471 return false; 13472 case HA_VECT64: 13473 return VT->getBitWidth() == 64; 13474 case HA_VECT128: 13475 return VT->getBitWidth() == 128; 13476 case HA_UNKNOWN: 13477 switch (VT->getBitWidth()) { 13478 case 64: 13479 Base = HA_VECT64; 13480 return true; 13481 case 128: 13482 Base = HA_VECT128; 13483 return true; 13484 default: 13485 return false; 13486 } 13487 } 13488 } 13489 13490 return (Members > 0 && Members <= 4); 13491 } 13492 13493 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 13494 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 13495 /// passing according to AAPCS rules. 13496 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 13497 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 13498 if (getEffectiveCallingConv(CallConv, isVarArg) != 13499 CallingConv::ARM_AAPCS_VFP) 13500 return false; 13501 13502 HABaseType Base = HA_UNKNOWN; 13503 uint64_t Members = 0; 13504 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 13505 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 13506 13507 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 13508 return IsHA || IsIntArray; 13509 } 13510 13511 unsigned ARMTargetLowering::getExceptionPointerRegister( 13512 const Constant *PersonalityFn) const { 13513 // Platforms which do not use SjLj EH may return values in these registers 13514 // via the personality function. 13515 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 13516 } 13517 13518 unsigned ARMTargetLowering::getExceptionSelectorRegister( 13519 const Constant *PersonalityFn) const { 13520 // Platforms which do not use SjLj EH may return values in these registers 13521 // via the personality function. 13522 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 13523 } 13524 13525 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13526 // Update IsSplitCSR in ARMFunctionInfo. 13527 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 13528 AFI->setIsSplitCSR(true); 13529 } 13530 13531 void ARMTargetLowering::insertCopiesSplitCSR( 13532 MachineBasicBlock *Entry, 13533 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13534 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 13535 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13536 if (!IStart) 13537 return; 13538 13539 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 13540 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13541 MachineBasicBlock::iterator MBBI = Entry->begin(); 13542 for (const MCPhysReg *I = IStart; *I; ++I) { 13543 const TargetRegisterClass *RC = nullptr; 13544 if (ARM::GPRRegClass.contains(*I)) 13545 RC = &ARM::GPRRegClass; 13546 else if (ARM::DPRRegClass.contains(*I)) 13547 RC = &ARM::DPRRegClass; 13548 else 13549 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13550 13551 unsigned NewVR = MRI->createVirtualRegister(RC); 13552 // Create copy from CSR to a virtual register. 13553 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13554 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13555 // nounwind. If we want to generalize this later, we may need to emit 13556 // CFI pseudo-instructions. 13557 assert(Entry->getParent()->getFunction()->hasFnAttribute( 13558 Attribute::NoUnwind) && 13559 "Function should be nounwind in insertCopiesSplitCSR!"); 13560 Entry->addLiveIn(*I); 13561 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13562 .addReg(*I); 13563 13564 // Insert the copy-back instructions right before the terminator. 13565 for (auto *Exit : Exits) 13566 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13567 TII->get(TargetOpcode::COPY), *I) 13568 .addReg(NewVR); 13569 } 13570 } 13571