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, bool &InvalidOnQNaN) { 1476 CondCode2 = ARMCC::AL; 1477 InvalidOnQNaN = true; 1478 switch (CC) { 1479 default: llvm_unreachable("Unknown FP condition!"); 1480 case ISD::SETEQ: 1481 case ISD::SETOEQ: 1482 CondCode = ARMCC::EQ; 1483 InvalidOnQNaN = false; 1484 break; 1485 case ISD::SETGT: 1486 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1487 case ISD::SETGE: 1488 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1489 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1490 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1491 case ISD::SETONE: 1492 CondCode = ARMCC::MI; 1493 CondCode2 = ARMCC::GT; 1494 InvalidOnQNaN = false; 1495 break; 1496 case ISD::SETO: CondCode = ARMCC::VC; break; 1497 case ISD::SETUO: CondCode = ARMCC::VS; break; 1498 case ISD::SETUEQ: 1499 CondCode = ARMCC::EQ; 1500 CondCode2 = ARMCC::VS; 1501 InvalidOnQNaN = false; 1502 break; 1503 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1504 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1505 case ISD::SETLT: 1506 case ISD::SETULT: CondCode = ARMCC::LT; break; 1507 case ISD::SETLE: 1508 case ISD::SETULE: CondCode = ARMCC::LE; break; 1509 case ISD::SETNE: 1510 case ISD::SETUNE: 1511 CondCode = ARMCC::NE; 1512 InvalidOnQNaN = false; 1513 break; 1514 } 1515 } 1516 1517 //===----------------------------------------------------------------------===// 1518 // Calling Convention Implementation 1519 //===----------------------------------------------------------------------===// 1520 1521 #include "ARMGenCallingConv.inc" 1522 1523 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1524 /// account presence of floating point hardware and calling convention 1525 /// limitations, such as support for variadic functions. 1526 CallingConv::ID 1527 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1528 bool isVarArg) const { 1529 switch (CC) { 1530 default: 1531 llvm_unreachable("Unsupported calling convention"); 1532 case CallingConv::ARM_AAPCS: 1533 case CallingConv::ARM_APCS: 1534 case CallingConv::GHC: 1535 return CC; 1536 case CallingConv::PreserveMost: 1537 return CallingConv::PreserveMost; 1538 case CallingConv::ARM_AAPCS_VFP: 1539 case CallingConv::Swift: 1540 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1541 case CallingConv::C: 1542 if (!Subtarget->isAAPCS_ABI()) 1543 return CallingConv::ARM_APCS; 1544 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1545 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1546 !isVarArg) 1547 return CallingConv::ARM_AAPCS_VFP; 1548 else 1549 return CallingConv::ARM_AAPCS; 1550 case CallingConv::Fast: 1551 case CallingConv::CXX_FAST_TLS: 1552 if (!Subtarget->isAAPCS_ABI()) { 1553 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1554 return CallingConv::Fast; 1555 return CallingConv::ARM_APCS; 1556 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1557 return CallingConv::ARM_AAPCS_VFP; 1558 else 1559 return CallingConv::ARM_AAPCS; 1560 } 1561 } 1562 1563 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1564 bool isVarArg) const { 1565 return CCAssignFnForNode(CC, false, isVarArg); 1566 } 1567 1568 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1569 bool isVarArg) const { 1570 return CCAssignFnForNode(CC, true, isVarArg); 1571 } 1572 1573 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1574 /// CallingConvention. 1575 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1576 bool Return, 1577 bool isVarArg) const { 1578 switch (getEffectiveCallingConv(CC, isVarArg)) { 1579 default: 1580 llvm_unreachable("Unsupported calling convention"); 1581 case CallingConv::ARM_APCS: 1582 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1583 case CallingConv::ARM_AAPCS: 1584 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1585 case CallingConv::ARM_AAPCS_VFP: 1586 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1587 case CallingConv::Fast: 1588 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1589 case CallingConv::GHC: 1590 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1591 case CallingConv::PreserveMost: 1592 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1593 } 1594 } 1595 1596 /// LowerCallResult - Lower the result values of a call into the 1597 /// appropriate copies out of appropriate physical registers. 1598 SDValue ARMTargetLowering::LowerCallResult( 1599 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1600 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1601 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1602 SDValue ThisVal) const { 1603 1604 // Assign locations to each value returned by this call. 1605 SmallVector<CCValAssign, 16> RVLocs; 1606 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1607 *DAG.getContext()); 1608 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1609 1610 // Copy all of the result registers out of their specified physreg. 1611 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1612 CCValAssign VA = RVLocs[i]; 1613 1614 // Pass 'this' value directly from the argument to return value, to avoid 1615 // reg unit interference 1616 if (i == 0 && isThisReturn) { 1617 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1618 "unexpected return calling convention register assignment"); 1619 InVals.push_back(ThisVal); 1620 continue; 1621 } 1622 1623 SDValue Val; 1624 if (VA.needsCustom()) { 1625 // Handle f64 or half of a v2f64. 1626 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1627 InFlag); 1628 Chain = Lo.getValue(1); 1629 InFlag = Lo.getValue(2); 1630 VA = RVLocs[++i]; // skip ahead to next loc 1631 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1632 InFlag); 1633 Chain = Hi.getValue(1); 1634 InFlag = Hi.getValue(2); 1635 if (!Subtarget->isLittle()) 1636 std::swap (Lo, Hi); 1637 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1638 1639 if (VA.getLocVT() == MVT::v2f64) { 1640 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1641 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1642 DAG.getConstant(0, dl, MVT::i32)); 1643 1644 VA = RVLocs[++i]; // skip ahead to next loc 1645 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1646 Chain = Lo.getValue(1); 1647 InFlag = Lo.getValue(2); 1648 VA = RVLocs[++i]; // skip ahead to next loc 1649 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1650 Chain = Hi.getValue(1); 1651 InFlag = Hi.getValue(2); 1652 if (!Subtarget->isLittle()) 1653 std::swap (Lo, Hi); 1654 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1655 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1656 DAG.getConstant(1, dl, MVT::i32)); 1657 } 1658 } else { 1659 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1660 InFlag); 1661 Chain = Val.getValue(1); 1662 InFlag = Val.getValue(2); 1663 } 1664 1665 switch (VA.getLocInfo()) { 1666 default: llvm_unreachable("Unknown loc info!"); 1667 case CCValAssign::Full: break; 1668 case CCValAssign::BCvt: 1669 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1670 break; 1671 } 1672 1673 InVals.push_back(Val); 1674 } 1675 1676 return Chain; 1677 } 1678 1679 /// LowerMemOpCallTo - Store the argument to the stack. 1680 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1681 SDValue Arg, const SDLoc &dl, 1682 SelectionDAG &DAG, 1683 const CCValAssign &VA, 1684 ISD::ArgFlagsTy Flags) const { 1685 unsigned LocMemOffset = VA.getLocMemOffset(); 1686 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1687 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1688 StackPtr, PtrOff); 1689 return DAG.getStore( 1690 Chain, dl, Arg, PtrOff, 1691 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1692 } 1693 1694 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1695 SDValue Chain, SDValue &Arg, 1696 RegsToPassVector &RegsToPass, 1697 CCValAssign &VA, CCValAssign &NextVA, 1698 SDValue &StackPtr, 1699 SmallVectorImpl<SDValue> &MemOpChains, 1700 ISD::ArgFlagsTy Flags) const { 1701 1702 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1703 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1704 unsigned id = Subtarget->isLittle() ? 0 : 1; 1705 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1706 1707 if (NextVA.isRegLoc()) 1708 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1709 else { 1710 assert(NextVA.isMemLoc()); 1711 if (!StackPtr.getNode()) 1712 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1713 getPointerTy(DAG.getDataLayout())); 1714 1715 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1716 dl, DAG, NextVA, 1717 Flags)); 1718 } 1719 } 1720 1721 /// LowerCall - Lowering a call into a callseq_start <- 1722 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1723 /// nodes. 1724 SDValue 1725 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1726 SmallVectorImpl<SDValue> &InVals) const { 1727 SelectionDAG &DAG = CLI.DAG; 1728 SDLoc &dl = CLI.DL; 1729 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1730 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1731 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1732 SDValue Chain = CLI.Chain; 1733 SDValue Callee = CLI.Callee; 1734 bool &isTailCall = CLI.IsTailCall; 1735 CallingConv::ID CallConv = CLI.CallConv; 1736 bool doesNotRet = CLI.DoesNotReturn; 1737 bool isVarArg = CLI.IsVarArg; 1738 1739 MachineFunction &MF = DAG.getMachineFunction(); 1740 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1741 bool isThisReturn = false; 1742 bool isSibCall = false; 1743 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls"); 1744 1745 // Disable tail calls if they're not supported. 1746 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1747 isTailCall = false; 1748 1749 if (isTailCall) { 1750 // Check if it's really possible to do a tail call. 1751 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1752 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1753 Outs, OutVals, Ins, DAG); 1754 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall()) 1755 report_fatal_error("failed to perform tail call elimination on a call " 1756 "site marked musttail"); 1757 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1758 // detected sibcalls. 1759 if (isTailCall) { 1760 ++NumTailCalls; 1761 isSibCall = true; 1762 } 1763 } 1764 1765 // Analyze operands of the call, assigning locations to each operand. 1766 SmallVector<CCValAssign, 16> ArgLocs; 1767 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1768 *DAG.getContext()); 1769 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1770 1771 // Get a count of how many bytes are to be pushed on the stack. 1772 unsigned NumBytes = CCInfo.getNextStackOffset(); 1773 1774 // For tail calls, memory operands are available in our caller's stack. 1775 if (isSibCall) 1776 NumBytes = 0; 1777 1778 // Adjust the stack pointer for the new arguments... 1779 // These operations are automatically eliminated by the prolog/epilog pass 1780 if (!isSibCall) 1781 Chain = DAG.getCALLSEQ_START(Chain, 1782 DAG.getIntPtrConstant(NumBytes, dl, true), dl); 1783 1784 SDValue StackPtr = 1785 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1786 1787 RegsToPassVector RegsToPass; 1788 SmallVector<SDValue, 8> MemOpChains; 1789 1790 // Walk the register/memloc assignments, inserting copies/loads. In the case 1791 // of tail call optimization, arguments are handled later. 1792 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1793 i != e; 1794 ++i, ++realArgIdx) { 1795 CCValAssign &VA = ArgLocs[i]; 1796 SDValue Arg = OutVals[realArgIdx]; 1797 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1798 bool isByVal = Flags.isByVal(); 1799 1800 // Promote the value if needed. 1801 switch (VA.getLocInfo()) { 1802 default: llvm_unreachable("Unknown loc info!"); 1803 case CCValAssign::Full: break; 1804 case CCValAssign::SExt: 1805 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1806 break; 1807 case CCValAssign::ZExt: 1808 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1809 break; 1810 case CCValAssign::AExt: 1811 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1812 break; 1813 case CCValAssign::BCvt: 1814 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1815 break; 1816 } 1817 1818 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1819 if (VA.needsCustom()) { 1820 if (VA.getLocVT() == MVT::v2f64) { 1821 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1822 DAG.getConstant(0, dl, MVT::i32)); 1823 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1824 DAG.getConstant(1, dl, MVT::i32)); 1825 1826 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1827 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1828 1829 VA = ArgLocs[++i]; // skip ahead to next loc 1830 if (VA.isRegLoc()) { 1831 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1832 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1833 } else { 1834 assert(VA.isMemLoc()); 1835 1836 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1837 dl, DAG, VA, Flags)); 1838 } 1839 } else { 1840 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1841 StackPtr, MemOpChains, Flags); 1842 } 1843 } else if (VA.isRegLoc()) { 1844 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1845 Outs[0].VT == MVT::i32) { 1846 assert(VA.getLocVT() == MVT::i32 && 1847 "unexpected calling convention register assignment"); 1848 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1849 "unexpected use of 'returned'"); 1850 isThisReturn = true; 1851 } 1852 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1853 } else if (isByVal) { 1854 assert(VA.isMemLoc()); 1855 unsigned offset = 0; 1856 1857 // True if this byval aggregate will be split between registers 1858 // and memory. 1859 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1860 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1861 1862 if (CurByValIdx < ByValArgsCount) { 1863 1864 unsigned RegBegin, RegEnd; 1865 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1866 1867 EVT PtrVT = 1868 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1869 unsigned int i, j; 1870 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1871 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1872 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1873 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1874 MachinePointerInfo(), 1875 DAG.InferPtrAlignment(AddArg)); 1876 MemOpChains.push_back(Load.getValue(1)); 1877 RegsToPass.push_back(std::make_pair(j, Load)); 1878 } 1879 1880 // If parameter size outsides register area, "offset" value 1881 // helps us to calculate stack slot for remained part properly. 1882 offset = RegEnd - RegBegin; 1883 1884 CCInfo.nextInRegsParam(); 1885 } 1886 1887 if (Flags.getByValSize() > 4*offset) { 1888 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1889 unsigned LocMemOffset = VA.getLocMemOffset(); 1890 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1891 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1892 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1893 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1894 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1895 MVT::i32); 1896 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1897 MVT::i32); 1898 1899 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1900 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1901 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1902 Ops)); 1903 } 1904 } else if (!isSibCall) { 1905 assert(VA.isMemLoc()); 1906 1907 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1908 dl, DAG, VA, Flags)); 1909 } 1910 } 1911 1912 if (!MemOpChains.empty()) 1913 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1914 1915 // Build a sequence of copy-to-reg nodes chained together with token chain 1916 // and flag operands which copy the outgoing args into the appropriate regs. 1917 SDValue InFlag; 1918 // Tail call byval lowering might overwrite argument registers so in case of 1919 // tail call optimization the copies to registers are lowered later. 1920 if (!isTailCall) 1921 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1922 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1923 RegsToPass[i].second, InFlag); 1924 InFlag = Chain.getValue(1); 1925 } 1926 1927 // For tail calls lower the arguments to the 'real' stack slot. 1928 if (isTailCall) { 1929 // Force all the incoming stack arguments to be loaded from the stack 1930 // before any new outgoing arguments are stored to the stack, because the 1931 // outgoing stack slots may alias the incoming argument stack slots, and 1932 // the alias isn't otherwise explicit. This is slightly more conservative 1933 // than necessary, because it means that each store effectively depends 1934 // on every argument instead of just those arguments it would clobber. 1935 1936 // Do not flag preceding copytoreg stuff together with the following stuff. 1937 InFlag = SDValue(); 1938 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1939 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1940 RegsToPass[i].second, InFlag); 1941 InFlag = Chain.getValue(1); 1942 } 1943 InFlag = SDValue(); 1944 } 1945 1946 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1947 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1948 // node so that legalize doesn't hack it. 1949 bool isDirect = false; 1950 1951 const TargetMachine &TM = getTargetMachine(); 1952 const Module *Mod = MF.getFunction()->getParent(); 1953 const GlobalValue *GV = nullptr; 1954 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1955 GV = G->getGlobal(); 1956 bool isStub = 1957 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 1958 1959 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1960 bool isLocalARMFunc = false; 1961 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1962 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1963 1964 if (Subtarget->genLongCalls()) { 1965 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 1966 "long-calls codegen is not position independent!"); 1967 // Handle a global address or an external symbol. If it's not one of 1968 // those, the target's already in a register, so we don't need to do 1969 // anything extra. 1970 if (isa<GlobalAddressSDNode>(Callee)) { 1971 // Create a constant pool entry for the callee address 1972 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1973 ARMConstantPoolValue *CPV = 1974 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1975 1976 // Get the address of the callee into a register 1977 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1978 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1979 Callee = DAG.getLoad( 1980 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1981 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 1982 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1983 const char *Sym = S->getSymbol(); 1984 1985 // Create a constant pool entry for the callee address 1986 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1987 ARMConstantPoolValue *CPV = 1988 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1989 ARMPCLabelIndex, 0); 1990 // Get the address of the callee into a register 1991 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 1992 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1993 Callee = DAG.getLoad( 1994 PtrVt, dl, DAG.getEntryNode(), CPAddr, 1995 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 1996 } 1997 } else if (isa<GlobalAddressSDNode>(Callee)) { 1998 // If we're optimizing for minimum size and the function is called three or 1999 // more times in this block, we can improve codesize by calling indirectly 2000 // as BLXr has a 16-bit encoding. 2001 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2002 auto *BB = CLI.CS->getParent(); 2003 bool PreferIndirect = 2004 Subtarget->isThumb() && MF.getFunction()->optForMinSize() && 2005 count_if(GV->users(), [&BB](const User *U) { 2006 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2007 }) > 2; 2008 2009 if (!PreferIndirect) { 2010 isDirect = true; 2011 bool isDef = GV->isStrongDefinitionForLinker(); 2012 2013 // ARM call to a local ARM function is predicable. 2014 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2015 // tBX takes a register source operand. 2016 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2017 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2018 Callee = DAG.getNode( 2019 ARMISD::WrapperPIC, dl, PtrVt, 2020 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2021 Callee = DAG.getLoad( 2022 PtrVt, dl, DAG.getEntryNode(), Callee, 2023 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2024 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2025 MachineMemOperand::MOInvariant); 2026 } else if (Subtarget->isTargetCOFF()) { 2027 assert(Subtarget->isTargetWindows() && 2028 "Windows is the only supported COFF target"); 2029 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2030 ? ARMII::MO_DLLIMPORT 2031 : ARMII::MO_NO_FLAG; 2032 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2033 TargetFlags); 2034 if (GV->hasDLLImportStorageClass()) 2035 Callee = 2036 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2037 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2038 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2039 } else { 2040 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2041 } 2042 } 2043 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2044 isDirect = true; 2045 // tBX takes a register source operand. 2046 const char *Sym = S->getSymbol(); 2047 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2048 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2049 ARMConstantPoolValue *CPV = 2050 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2051 ARMPCLabelIndex, 4); 2052 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2053 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2054 Callee = DAG.getLoad( 2055 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2056 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2057 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2058 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2059 } else { 2060 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2061 } 2062 } 2063 2064 // FIXME: handle tail calls differently. 2065 unsigned CallOpc; 2066 if (Subtarget->isThumb()) { 2067 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2068 CallOpc = ARMISD::CALL_NOLINK; 2069 else 2070 CallOpc = ARMISD::CALL; 2071 } else { 2072 if (!isDirect && !Subtarget->hasV5TOps()) 2073 CallOpc = ARMISD::CALL_NOLINK; 2074 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2075 // Emit regular call when code size is the priority 2076 !MF.getFunction()->optForMinSize()) 2077 // "mov lr, pc; b _foo" to avoid confusing the RSP 2078 CallOpc = ARMISD::CALL_NOLINK; 2079 else 2080 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2081 } 2082 2083 std::vector<SDValue> Ops; 2084 Ops.push_back(Chain); 2085 Ops.push_back(Callee); 2086 2087 // Add argument registers to the end of the list so that they are known live 2088 // into the call. 2089 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2090 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2091 RegsToPass[i].second.getValueType())); 2092 2093 // Add a register mask operand representing the call-preserved registers. 2094 if (!isTailCall) { 2095 const uint32_t *Mask; 2096 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2097 if (isThisReturn) { 2098 // For 'this' returns, use the R0-preserving mask if applicable 2099 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2100 if (!Mask) { 2101 // Set isThisReturn to false if the calling convention is not one that 2102 // allows 'returned' to be modeled in this way, so LowerCallResult does 2103 // not try to pass 'this' straight through 2104 isThisReturn = false; 2105 Mask = ARI->getCallPreservedMask(MF, CallConv); 2106 } 2107 } else 2108 Mask = ARI->getCallPreservedMask(MF, CallConv); 2109 2110 assert(Mask && "Missing call preserved mask for calling convention"); 2111 Ops.push_back(DAG.getRegisterMask(Mask)); 2112 } 2113 2114 if (InFlag.getNode()) 2115 Ops.push_back(InFlag); 2116 2117 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2118 if (isTailCall) { 2119 MF.getFrameInfo().setHasTailCall(); 2120 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2121 } 2122 2123 // Returns a chain and a flag for retval copy to use. 2124 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2125 InFlag = Chain.getValue(1); 2126 2127 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2128 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2129 if (!Ins.empty()) 2130 InFlag = Chain.getValue(1); 2131 2132 // Handle result values, copying them out of physregs into vregs that we 2133 // return. 2134 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2135 InVals, isThisReturn, 2136 isThisReturn ? OutVals[0] : SDValue()); 2137 } 2138 2139 /// HandleByVal - Every parameter *after* a byval parameter is passed 2140 /// on the stack. Remember the next parameter register to allocate, 2141 /// and then confiscate the rest of the parameter registers to insure 2142 /// this. 2143 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2144 unsigned Align) const { 2145 // Byval (as with any stack) slots are always at least 4 byte aligned. 2146 Align = std::max(Align, 4U); 2147 2148 unsigned Reg = State->AllocateReg(GPRArgRegs); 2149 if (!Reg) 2150 return; 2151 2152 unsigned AlignInRegs = Align / 4; 2153 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2154 for (unsigned i = 0; i < Waste; ++i) 2155 Reg = State->AllocateReg(GPRArgRegs); 2156 2157 if (!Reg) 2158 return; 2159 2160 unsigned Excess = 4 * (ARM::R4 - Reg); 2161 2162 // Special case when NSAA != SP and parameter size greater than size of 2163 // all remained GPR regs. In that case we can't split parameter, we must 2164 // send it to stack. We also must set NCRN to R4, so waste all 2165 // remained registers. 2166 const unsigned NSAAOffset = State->getNextStackOffset(); 2167 if (NSAAOffset != 0 && Size > Excess) { 2168 while (State->AllocateReg(GPRArgRegs)) 2169 ; 2170 return; 2171 } 2172 2173 // First register for byval parameter is the first register that wasn't 2174 // allocated before this method call, so it would be "reg". 2175 // If parameter is small enough to be saved in range [reg, r4), then 2176 // the end (first after last) register would be reg + param-size-in-regs, 2177 // else parameter would be splitted between registers and stack, 2178 // end register would be r4 in this case. 2179 unsigned ByValRegBegin = Reg; 2180 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2181 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2182 // Note, first register is allocated in the beginning of function already, 2183 // allocate remained amount of registers we need. 2184 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2185 State->AllocateReg(GPRArgRegs); 2186 // A byval parameter that is split between registers and memory needs its 2187 // size truncated here. 2188 // In the case where the entire structure fits in registers, we set the 2189 // size in memory to zero. 2190 Size = std::max<int>(Size - Excess, 0); 2191 } 2192 2193 /// MatchingStackOffset - Return true if the given stack call argument is 2194 /// already available in the same position (relatively) of the caller's 2195 /// incoming argument stack. 2196 static 2197 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2198 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2199 const TargetInstrInfo *TII) { 2200 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2201 int FI = std::numeric_limits<int>::max(); 2202 if (Arg.getOpcode() == ISD::CopyFromReg) { 2203 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2204 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2205 return false; 2206 MachineInstr *Def = MRI->getVRegDef(VR); 2207 if (!Def) 2208 return false; 2209 if (!Flags.isByVal()) { 2210 if (!TII->isLoadFromStackSlot(*Def, FI)) 2211 return false; 2212 } else { 2213 return false; 2214 } 2215 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2216 if (Flags.isByVal()) 2217 // ByVal argument is passed in as a pointer but it's now being 2218 // dereferenced. e.g. 2219 // define @foo(%struct.X* %A) { 2220 // tail call @bar(%struct.X* byval %A) 2221 // } 2222 return false; 2223 SDValue Ptr = Ld->getBasePtr(); 2224 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2225 if (!FINode) 2226 return false; 2227 FI = FINode->getIndex(); 2228 } else 2229 return false; 2230 2231 assert(FI != std::numeric_limits<int>::max()); 2232 if (!MFI.isFixedObjectIndex(FI)) 2233 return false; 2234 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2235 } 2236 2237 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2238 /// for tail call optimization. Targets which want to do tail call 2239 /// optimization should implement this function. 2240 bool 2241 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2242 CallingConv::ID CalleeCC, 2243 bool isVarArg, 2244 bool isCalleeStructRet, 2245 bool isCallerStructRet, 2246 const SmallVectorImpl<ISD::OutputArg> &Outs, 2247 const SmallVectorImpl<SDValue> &OutVals, 2248 const SmallVectorImpl<ISD::InputArg> &Ins, 2249 SelectionDAG& DAG) const { 2250 MachineFunction &MF = DAG.getMachineFunction(); 2251 const Function *CallerF = MF.getFunction(); 2252 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2253 2254 assert(Subtarget->supportsTailCall()); 2255 2256 // Look for obvious safe cases to perform tail call optimization that do not 2257 // require ABI changes. This is what gcc calls sibcall. 2258 2259 // Exception-handling functions need a special set of instructions to indicate 2260 // a return to the hardware. Tail-calling another function would probably 2261 // break this. 2262 if (CallerF->hasFnAttribute("interrupt")) 2263 return false; 2264 2265 // Also avoid sibcall optimization if either caller or callee uses struct 2266 // return semantics. 2267 if (isCalleeStructRet || isCallerStructRet) 2268 return false; 2269 2270 // Externally-defined functions with weak linkage should not be 2271 // tail-called on ARM when the OS does not support dynamic 2272 // pre-emption of symbols, as the AAELF spec requires normal calls 2273 // to undefined weak functions to be replaced with a NOP or jump to the 2274 // next instruction. The behaviour of branch instructions in this 2275 // situation (as used for tail calls) is implementation-defined, so we 2276 // cannot rely on the linker replacing the tail call with a return. 2277 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2278 const GlobalValue *GV = G->getGlobal(); 2279 const Triple &TT = getTargetMachine().getTargetTriple(); 2280 if (GV->hasExternalWeakLinkage() && 2281 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2282 return false; 2283 } 2284 2285 // Check that the call results are passed in the same way. 2286 LLVMContext &C = *DAG.getContext(); 2287 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2288 CCAssignFnForReturn(CalleeCC, isVarArg), 2289 CCAssignFnForReturn(CallerCC, isVarArg))) 2290 return false; 2291 // The callee has to preserve all registers the caller needs to preserve. 2292 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2293 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2294 if (CalleeCC != CallerCC) { 2295 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2296 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2297 return false; 2298 } 2299 2300 // If Caller's vararg or byval argument has been split between registers and 2301 // stack, do not perform tail call, since part of the argument is in caller's 2302 // local frame. 2303 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2304 if (AFI_Caller->getArgRegsSaveSize()) 2305 return false; 2306 2307 // If the callee takes no arguments then go on to check the results of the 2308 // call. 2309 if (!Outs.empty()) { 2310 // Check if stack adjustment is needed. For now, do not do this if any 2311 // argument is passed on the stack. 2312 SmallVector<CCValAssign, 16> ArgLocs; 2313 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2314 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2315 if (CCInfo.getNextStackOffset()) { 2316 // Check if the arguments are already laid out in the right way as 2317 // the caller's fixed stack objects. 2318 MachineFrameInfo &MFI = MF.getFrameInfo(); 2319 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2320 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2321 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2322 i != e; 2323 ++i, ++realArgIdx) { 2324 CCValAssign &VA = ArgLocs[i]; 2325 EVT RegVT = VA.getLocVT(); 2326 SDValue Arg = OutVals[realArgIdx]; 2327 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2328 if (VA.getLocInfo() == CCValAssign::Indirect) 2329 return false; 2330 if (VA.needsCustom()) { 2331 // f64 and vector types are split into multiple registers or 2332 // register/stack-slot combinations. The types will not match 2333 // the registers; give up on memory f64 refs until we figure 2334 // out what to do about this. 2335 if (!VA.isRegLoc()) 2336 return false; 2337 if (!ArgLocs[++i].isRegLoc()) 2338 return false; 2339 if (RegVT == MVT::v2f64) { 2340 if (!ArgLocs[++i].isRegLoc()) 2341 return false; 2342 if (!ArgLocs[++i].isRegLoc()) 2343 return false; 2344 } 2345 } else if (!VA.isRegLoc()) { 2346 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2347 MFI, MRI, TII)) 2348 return false; 2349 } 2350 } 2351 } 2352 2353 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2354 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2355 return false; 2356 } 2357 2358 return true; 2359 } 2360 2361 bool 2362 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2363 MachineFunction &MF, bool isVarArg, 2364 const SmallVectorImpl<ISD::OutputArg> &Outs, 2365 LLVMContext &Context) const { 2366 SmallVector<CCValAssign, 16> RVLocs; 2367 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2368 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2369 } 2370 2371 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2372 const SDLoc &DL, SelectionDAG &DAG) { 2373 const MachineFunction &MF = DAG.getMachineFunction(); 2374 const Function *F = MF.getFunction(); 2375 2376 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2377 2378 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2379 // version of the "preferred return address". These offsets affect the return 2380 // instruction if this is a return from PL1 without hypervisor extensions. 2381 // IRQ/FIQ: +4 "subs pc, lr, #4" 2382 // SWI: 0 "subs pc, lr, #0" 2383 // ABORT: +4 "subs pc, lr, #4" 2384 // UNDEF: +4/+2 "subs pc, lr, #0" 2385 // UNDEF varies depending on where the exception came from ARM or Thumb 2386 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2387 2388 int64_t LROffset; 2389 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2390 IntKind == "ABORT") 2391 LROffset = 4; 2392 else if (IntKind == "SWI" || IntKind == "UNDEF") 2393 LROffset = 0; 2394 else 2395 report_fatal_error("Unsupported interrupt attribute. If present, value " 2396 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2397 2398 RetOps.insert(RetOps.begin() + 1, 2399 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2400 2401 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2402 } 2403 2404 SDValue 2405 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2406 bool isVarArg, 2407 const SmallVectorImpl<ISD::OutputArg> &Outs, 2408 const SmallVectorImpl<SDValue> &OutVals, 2409 const SDLoc &dl, SelectionDAG &DAG) const { 2410 2411 // CCValAssign - represent the assignment of the return value to a location. 2412 SmallVector<CCValAssign, 16> RVLocs; 2413 2414 // CCState - Info about the registers and stack slots. 2415 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2416 *DAG.getContext()); 2417 2418 // Analyze outgoing return values. 2419 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2420 2421 SDValue Flag; 2422 SmallVector<SDValue, 4> RetOps; 2423 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2424 bool isLittleEndian = Subtarget->isLittle(); 2425 2426 MachineFunction &MF = DAG.getMachineFunction(); 2427 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2428 AFI->setReturnRegsCount(RVLocs.size()); 2429 2430 // Copy the result values into the output registers. 2431 for (unsigned i = 0, realRVLocIdx = 0; 2432 i != RVLocs.size(); 2433 ++i, ++realRVLocIdx) { 2434 CCValAssign &VA = RVLocs[i]; 2435 assert(VA.isRegLoc() && "Can only return in registers!"); 2436 2437 SDValue Arg = OutVals[realRVLocIdx]; 2438 2439 switch (VA.getLocInfo()) { 2440 default: llvm_unreachable("Unknown loc info!"); 2441 case CCValAssign::Full: break; 2442 case CCValAssign::BCvt: 2443 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2444 break; 2445 } 2446 2447 if (VA.needsCustom()) { 2448 if (VA.getLocVT() == MVT::v2f64) { 2449 // Extract the first half and return it in two registers. 2450 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2451 DAG.getConstant(0, dl, MVT::i32)); 2452 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2453 DAG.getVTList(MVT::i32, MVT::i32), Half); 2454 2455 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2456 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2457 Flag); 2458 Flag = Chain.getValue(1); 2459 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2460 VA = RVLocs[++i]; // skip ahead to next loc 2461 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2462 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2463 Flag); 2464 Flag = Chain.getValue(1); 2465 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2466 VA = RVLocs[++i]; // skip ahead to next loc 2467 2468 // Extract the 2nd half and fall through to handle it as an f64 value. 2469 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2470 DAG.getConstant(1, dl, MVT::i32)); 2471 } 2472 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2473 // available. 2474 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2475 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2476 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2477 fmrrd.getValue(isLittleEndian ? 0 : 1), 2478 Flag); 2479 Flag = Chain.getValue(1); 2480 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2481 VA = RVLocs[++i]; // skip ahead to next loc 2482 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2483 fmrrd.getValue(isLittleEndian ? 1 : 0), 2484 Flag); 2485 } else 2486 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2487 2488 // Guarantee that all emitted copies are 2489 // stuck together, avoiding something bad. 2490 Flag = Chain.getValue(1); 2491 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2492 } 2493 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2494 const MCPhysReg *I = 2495 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2496 if (I) { 2497 for (; *I; ++I) { 2498 if (ARM::GPRRegClass.contains(*I)) 2499 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2500 else if (ARM::DPRRegClass.contains(*I)) 2501 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2502 else 2503 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2504 } 2505 } 2506 2507 // Update chain and glue. 2508 RetOps[0] = Chain; 2509 if (Flag.getNode()) 2510 RetOps.push_back(Flag); 2511 2512 // CPUs which aren't M-class use a special sequence to return from 2513 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2514 // though we use "subs pc, lr, #N"). 2515 // 2516 // M-class CPUs actually use a normal return sequence with a special 2517 // (hardware-provided) value in LR, so the normal code path works. 2518 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2519 !Subtarget->isMClass()) { 2520 if (Subtarget->isThumb1Only()) 2521 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2522 return LowerInterruptReturn(RetOps, dl, DAG); 2523 } 2524 2525 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2526 } 2527 2528 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2529 if (N->getNumValues() != 1) 2530 return false; 2531 if (!N->hasNUsesOfValue(1, 0)) 2532 return false; 2533 2534 SDValue TCChain = Chain; 2535 SDNode *Copy = *N->use_begin(); 2536 if (Copy->getOpcode() == ISD::CopyToReg) { 2537 // If the copy has a glue operand, we conservatively assume it isn't safe to 2538 // perform a tail call. 2539 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2540 return false; 2541 TCChain = Copy->getOperand(0); 2542 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2543 SDNode *VMov = Copy; 2544 // f64 returned in a pair of GPRs. 2545 SmallPtrSet<SDNode*, 2> Copies; 2546 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2547 UI != UE; ++UI) { 2548 if (UI->getOpcode() != ISD::CopyToReg) 2549 return false; 2550 Copies.insert(*UI); 2551 } 2552 if (Copies.size() > 2) 2553 return false; 2554 2555 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2556 UI != UE; ++UI) { 2557 SDValue UseChain = UI->getOperand(0); 2558 if (Copies.count(UseChain.getNode())) 2559 // Second CopyToReg 2560 Copy = *UI; 2561 else { 2562 // We are at the top of this chain. 2563 // If the copy has a glue operand, we conservatively assume it 2564 // isn't safe to perform a tail call. 2565 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2566 return false; 2567 // First CopyToReg 2568 TCChain = UseChain; 2569 } 2570 } 2571 } else if (Copy->getOpcode() == ISD::BITCAST) { 2572 // f32 returned in a single GPR. 2573 if (!Copy->hasOneUse()) 2574 return false; 2575 Copy = *Copy->use_begin(); 2576 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2577 return false; 2578 // If the copy has a glue operand, we conservatively assume it isn't safe to 2579 // perform a tail call. 2580 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2581 return false; 2582 TCChain = Copy->getOperand(0); 2583 } else { 2584 return false; 2585 } 2586 2587 bool HasRet = false; 2588 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2589 UI != UE; ++UI) { 2590 if (UI->getOpcode() != ARMISD::RET_FLAG && 2591 UI->getOpcode() != ARMISD::INTRET_FLAG) 2592 return false; 2593 HasRet = true; 2594 } 2595 2596 if (!HasRet) 2597 return false; 2598 2599 Chain = TCChain; 2600 return true; 2601 } 2602 2603 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2604 if (!Subtarget->supportsTailCall()) 2605 return false; 2606 2607 auto Attr = 2608 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2609 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2610 return false; 2611 2612 return true; 2613 } 2614 2615 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2616 // and pass the lower and high parts through. 2617 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2618 SDLoc DL(Op); 2619 SDValue WriteValue = Op->getOperand(2); 2620 2621 // This function is only supposed to be called for i64 type argument. 2622 assert(WriteValue.getValueType() == MVT::i64 2623 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2624 2625 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2626 DAG.getConstant(0, DL, MVT::i32)); 2627 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2628 DAG.getConstant(1, DL, MVT::i32)); 2629 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2630 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2631 } 2632 2633 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2634 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2635 // one of the above mentioned nodes. It has to be wrapped because otherwise 2636 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2637 // be used to form addressing mode. These wrapped nodes will be selected 2638 // into MOVi. 2639 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2640 EVT PtrVT = Op.getValueType(); 2641 // FIXME there is no actual debug info here 2642 SDLoc dl(Op); 2643 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2644 SDValue Res; 2645 if (CP->isMachineConstantPoolEntry()) 2646 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2647 CP->getAlignment()); 2648 else 2649 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2650 CP->getAlignment()); 2651 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2652 } 2653 2654 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2655 return MachineJumpTableInfo::EK_Inline; 2656 } 2657 2658 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2659 SelectionDAG &DAG) const { 2660 MachineFunction &MF = DAG.getMachineFunction(); 2661 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2662 unsigned ARMPCLabelIndex = 0; 2663 SDLoc DL(Op); 2664 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2665 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2666 SDValue CPAddr; 2667 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2668 if (!IsPositionIndependent) { 2669 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2670 } else { 2671 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2672 ARMPCLabelIndex = AFI->createPICLabelUId(); 2673 ARMConstantPoolValue *CPV = 2674 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2675 ARMCP::CPBlockAddress, PCAdj); 2676 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2677 } 2678 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2679 SDValue Result = DAG.getLoad( 2680 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2681 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2682 if (!IsPositionIndependent) 2683 return Result; 2684 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2685 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2686 } 2687 2688 /// \brief Convert a TLS address reference into the correct sequence of loads 2689 /// and calls to compute the variable's address for Darwin, and return an 2690 /// SDValue containing the final node. 2691 2692 /// Darwin only has one TLS scheme which must be capable of dealing with the 2693 /// fully general situation, in the worst case. This means: 2694 /// + "extern __thread" declaration. 2695 /// + Defined in a possibly unknown dynamic library. 2696 /// 2697 /// The general system is that each __thread variable has a [3 x i32] descriptor 2698 /// which contains information used by the runtime to calculate the address. The 2699 /// only part of this the compiler needs to know about is the first word, which 2700 /// contains a function pointer that must be called with the address of the 2701 /// entire descriptor in "r0". 2702 /// 2703 /// Since this descriptor may be in a different unit, in general access must 2704 /// proceed along the usual ARM rules. A common sequence to produce is: 2705 /// 2706 /// movw rT1, :lower16:_var$non_lazy_ptr 2707 /// movt rT1, :upper16:_var$non_lazy_ptr 2708 /// ldr r0, [rT1] 2709 /// ldr rT2, [r0] 2710 /// blx rT2 2711 /// [...address now in r0...] 2712 SDValue 2713 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2714 SelectionDAG &DAG) const { 2715 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 2716 SDLoc DL(Op); 2717 2718 // First step is to get the address of the actua global symbol. This is where 2719 // the TLS descriptor lives. 2720 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2721 2722 // The first entry in the descriptor is a function pointer that we must call 2723 // to obtain the address of the variable. 2724 SDValue Chain = DAG.getEntryNode(); 2725 SDValue FuncTLVGet = DAG.getLoad( 2726 MVT::i32, DL, Chain, DescAddr, 2727 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2728 /* Alignment = */ 4, 2729 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2730 MachineMemOperand::MOInvariant); 2731 Chain = FuncTLVGet.getValue(1); 2732 2733 MachineFunction &F = DAG.getMachineFunction(); 2734 MachineFrameInfo &MFI = F.getFrameInfo(); 2735 MFI.setAdjustsStack(true); 2736 2737 // TLS calls preserve all registers except those that absolutely must be 2738 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2739 // silly). 2740 auto TRI = 2741 getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo(); 2742 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2743 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2744 2745 // Finally, we can make the call. This is just a degenerate version of a 2746 // normal AArch64 call node: r0 takes the address of the descriptor, and 2747 // returns the address of the variable in this thread. 2748 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2749 Chain = 2750 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2751 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2752 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2753 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2754 } 2755 2756 SDValue 2757 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2758 SelectionDAG &DAG) const { 2759 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2760 2761 SDValue Chain = DAG.getEntryNode(); 2762 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2763 SDLoc DL(Op); 2764 2765 // Load the current TEB (thread environment block) 2766 SDValue Ops[] = {Chain, 2767 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2768 DAG.getConstant(15, DL, MVT::i32), 2769 DAG.getConstant(0, DL, MVT::i32), 2770 DAG.getConstant(13, DL, MVT::i32), 2771 DAG.getConstant(0, DL, MVT::i32), 2772 DAG.getConstant(2, DL, MVT::i32)}; 2773 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2774 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2775 2776 SDValue TEB = CurrentTEB.getValue(0); 2777 Chain = CurrentTEB.getValue(1); 2778 2779 // Load the ThreadLocalStoragePointer from the TEB 2780 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2781 SDValue TLSArray = 2782 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2783 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2784 2785 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2786 // offset into the TLSArray. 2787 2788 // Load the TLS index from the C runtime 2789 SDValue TLSIndex = 2790 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2791 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2792 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2793 2794 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2795 DAG.getConstant(2, DL, MVT::i32)); 2796 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2797 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2798 MachinePointerInfo()); 2799 2800 // Get the offset of the start of the .tls section (section base) 2801 const auto *GA = cast<GlobalAddressSDNode>(Op); 2802 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2803 SDValue Offset = DAG.getLoad( 2804 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2805 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2806 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2807 2808 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2809 } 2810 2811 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2812 SDValue 2813 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2814 SelectionDAG &DAG) const { 2815 SDLoc dl(GA); 2816 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2817 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2818 MachineFunction &MF = DAG.getMachineFunction(); 2819 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2820 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2821 ARMConstantPoolValue *CPV = 2822 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2823 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2824 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2825 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2826 Argument = DAG.getLoad( 2827 PtrVT, dl, DAG.getEntryNode(), Argument, 2828 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2829 SDValue Chain = Argument.getValue(1); 2830 2831 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2832 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2833 2834 // call __tls_get_addr. 2835 ArgListTy Args; 2836 ArgListEntry Entry; 2837 Entry.Node = Argument; 2838 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2839 Args.push_back(Entry); 2840 2841 // FIXME: is there useful debug info available here? 2842 TargetLowering::CallLoweringInfo CLI(DAG); 2843 CLI.setDebugLoc(dl).setChain(Chain) 2844 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2845 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2846 2847 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2848 return CallResult.first; 2849 } 2850 2851 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2852 // "local exec" model. 2853 SDValue 2854 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2855 SelectionDAG &DAG, 2856 TLSModel::Model model) const { 2857 const GlobalValue *GV = GA->getGlobal(); 2858 SDLoc dl(GA); 2859 SDValue Offset; 2860 SDValue Chain = DAG.getEntryNode(); 2861 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2862 // Get the Thread Pointer 2863 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2864 2865 if (model == TLSModel::InitialExec) { 2866 MachineFunction &MF = DAG.getMachineFunction(); 2867 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2868 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2869 // Initial exec model. 2870 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2871 ARMConstantPoolValue *CPV = 2872 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2873 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2874 true); 2875 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2876 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2877 Offset = DAG.getLoad( 2878 PtrVT, dl, Chain, Offset, 2879 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2880 Chain = Offset.getValue(1); 2881 2882 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2883 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2884 2885 Offset = DAG.getLoad( 2886 PtrVT, dl, Chain, Offset, 2887 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2888 } else { 2889 // local exec model 2890 assert(model == TLSModel::LocalExec); 2891 ARMConstantPoolValue *CPV = 2892 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2893 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2894 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2895 Offset = DAG.getLoad( 2896 PtrVT, dl, Chain, Offset, 2897 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2898 } 2899 2900 // The address of the thread local variable is the add of the thread 2901 // pointer with the offset of the variable. 2902 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2903 } 2904 2905 SDValue 2906 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2907 if (Subtarget->isTargetDarwin()) 2908 return LowerGlobalTLSAddressDarwin(Op, DAG); 2909 2910 if (Subtarget->isTargetWindows()) 2911 return LowerGlobalTLSAddressWindows(Op, DAG); 2912 2913 // TODO: implement the "local dynamic" model 2914 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2915 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2916 if (DAG.getTarget().Options.EmulatedTLS) 2917 return LowerToTLSEmulatedModel(GA, DAG); 2918 2919 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2920 2921 switch (model) { 2922 case TLSModel::GeneralDynamic: 2923 case TLSModel::LocalDynamic: 2924 return LowerToTLSGeneralDynamicModel(GA, DAG); 2925 case TLSModel::InitialExec: 2926 case TLSModel::LocalExec: 2927 return LowerToTLSExecModels(GA, DAG, model); 2928 } 2929 llvm_unreachable("bogus TLS model"); 2930 } 2931 2932 /// Return true if all users of V are within function F, looking through 2933 /// ConstantExprs. 2934 static bool allUsersAreInFunction(const Value *V, const Function *F) { 2935 SmallVector<const User*,4> Worklist; 2936 for (auto *U : V->users()) 2937 Worklist.push_back(U); 2938 while (!Worklist.empty()) { 2939 auto *U = Worklist.pop_back_val(); 2940 if (isa<ConstantExpr>(U)) { 2941 for (auto *UU : U->users()) 2942 Worklist.push_back(UU); 2943 continue; 2944 } 2945 2946 auto *I = dyn_cast<Instruction>(U); 2947 if (!I || I->getParent()->getParent() != F) 2948 return false; 2949 } 2950 return true; 2951 } 2952 2953 /// Return true if all users of V are within some (any) function, looking through 2954 /// ConstantExprs. In other words, are there any global constant users? 2955 static bool allUsersAreInFunctions(const Value *V) { 2956 SmallVector<const User*,4> Worklist; 2957 for (auto *U : V->users()) 2958 Worklist.push_back(U); 2959 while (!Worklist.empty()) { 2960 auto *U = Worklist.pop_back_val(); 2961 if (isa<ConstantExpr>(U)) { 2962 for (auto *UU : U->users()) 2963 Worklist.push_back(UU); 2964 continue; 2965 } 2966 2967 if (!isa<Instruction>(U)) 2968 return false; 2969 } 2970 return true; 2971 } 2972 2973 // Return true if T is an integer, float or an array/vector of either. 2974 static bool isSimpleType(Type *T) { 2975 if (T->isIntegerTy() || T->isFloatingPointTy()) 2976 return true; 2977 Type *SubT = nullptr; 2978 if (T->isArrayTy()) 2979 SubT = T->getArrayElementType(); 2980 else if (T->isVectorTy()) 2981 SubT = T->getVectorElementType(); 2982 else 2983 return false; 2984 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 2985 } 2986 2987 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 2988 EVT PtrVT, const SDLoc &dl) { 2989 // If we're creating a pool entry for a constant global with unnamed address, 2990 // and the global is small enough, we can emit it inline into the constant pool 2991 // to save ourselves an indirection. 2992 // 2993 // This is a win if the constant is only used in one function (so it doesn't 2994 // need to be duplicated) or duplicating the constant wouldn't increase code 2995 // size (implying the constant is no larger than 4 bytes). 2996 const Function *F = DAG.getMachineFunction().getFunction(); 2997 2998 // We rely on this decision to inline being idemopotent and unrelated to the 2999 // use-site. We know that if we inline a variable at one use site, we'll 3000 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3001 // doesn't know about this optimization, so bail out if it's enabled else 3002 // we could decide to inline here (and thus never emit the GV) but require 3003 // the GV from fast-isel generated code. 3004 if (!EnableConstpoolPromotion || 3005 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3006 return SDValue(); 3007 3008 auto *GVar = dyn_cast<GlobalVariable>(GV); 3009 if (!GVar || !GVar->hasInitializer() || 3010 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3011 !GVar->hasLocalLinkage()) 3012 return SDValue(); 3013 3014 // Ensure that we don't try and inline any type that contains pointers. If 3015 // we inline a value that contains relocations, we move the relocations from 3016 // .data to .text which is not ideal. 3017 auto *Init = GVar->getInitializer(); 3018 if (!isSimpleType(Init->getType())) 3019 return SDValue(); 3020 3021 // The constant islands pass can only really deal with alignment requests 3022 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3023 // any type wanting greater alignment requirements than 4 bytes. We also 3024 // can only promote constants that are multiples of 4 bytes in size or 3025 // are paddable to a multiple of 4. Currently we only try and pad constants 3026 // that are strings for simplicity. 3027 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3028 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3029 unsigned Align = GVar->getAlignment(); 3030 unsigned RequiredPadding = 4 - (Size % 4); 3031 bool PaddingPossible = 3032 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3033 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize) 3034 return SDValue(); 3035 3036 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3037 MachineFunction &MF = DAG.getMachineFunction(); 3038 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3039 3040 // We can't bloat the constant pool too much, else the ConstantIslands pass 3041 // may fail to converge. If we haven't promoted this global yet (it may have 3042 // multiple uses), and promoting it would increase the constant pool size (Sz 3043 // > 4), ensure we have space to do so up to MaxTotal. 3044 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3045 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3046 ConstpoolPromotionMaxTotal) 3047 return SDValue(); 3048 3049 // This is only valid if all users are in a single function OR it has users 3050 // in multiple functions but it no larger than a pointer. We also check if 3051 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3052 // address taken. 3053 if (!allUsersAreInFunction(GVar, F) && 3054 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3055 return SDValue(); 3056 3057 // We're going to inline this global. Pad it out if needed. 3058 if (RequiredPadding != 4) { 3059 StringRef S = CDAInit->getAsString(); 3060 3061 SmallVector<uint8_t,16> V(S.size()); 3062 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3063 while (RequiredPadding--) 3064 V.push_back(0); 3065 Init = ConstantDataArray::get(*DAG.getContext(), V); 3066 } 3067 3068 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3069 SDValue CPAddr = 3070 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3071 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3072 AFI->markGlobalAsPromotedToConstantPool(GVar); 3073 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3074 PaddedSize - 4); 3075 } 3076 ++NumConstpoolPromoted; 3077 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3078 } 3079 3080 static bool isReadOnly(const GlobalValue *GV) { 3081 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3082 GV = GA->getBaseObject(); 3083 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3084 isa<Function>(GV); 3085 } 3086 3087 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3088 SelectionDAG &DAG) const { 3089 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3090 SDLoc dl(Op); 3091 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3092 const TargetMachine &TM = getTargetMachine(); 3093 bool IsRO = isReadOnly(GV); 3094 3095 // promoteToConstantPool only if not generating XO text section 3096 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3097 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3098 return V; 3099 3100 if (isPositionIndependent()) { 3101 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3102 3103 MachineFunction &MF = DAG.getMachineFunction(); 3104 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3105 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3106 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3107 SDLoc dl(Op); 3108 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 3109 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create( 3110 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj, 3111 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier, 3112 /*AddCurrentAddress=*/UseGOT_PREL); 3113 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3114 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3115 SDValue Result = DAG.getLoad( 3116 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3117 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3118 SDValue Chain = Result.getValue(1); 3119 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3120 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3121 if (UseGOT_PREL) 3122 Result = 3123 DAG.getLoad(PtrVT, dl, Chain, Result, 3124 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3125 return Result; 3126 } else if (Subtarget->isROPI() && IsRO) { 3127 // PC-relative. 3128 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3129 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3130 return Result; 3131 } else if (Subtarget->isRWPI() && !IsRO) { 3132 // SB-relative. 3133 SDValue RelAddr; 3134 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3135 ++NumMovwMovt; 3136 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3137 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3138 } else { // use literal pool for address constant 3139 ARMConstantPoolValue *CPV = 3140 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3141 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3142 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3143 RelAddr = DAG.getLoad( 3144 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3145 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3146 } 3147 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3148 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3149 return Result; 3150 } 3151 3152 // If we have T2 ops, we can materialize the address directly via movt/movw 3153 // pair. This is always cheaper. 3154 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3155 ++NumMovwMovt; 3156 // FIXME: Once remat is capable of dealing with instructions with register 3157 // operands, expand this into two nodes. 3158 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3159 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3160 } else { 3161 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3162 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3163 return DAG.getLoad( 3164 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3165 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3166 } 3167 } 3168 3169 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3170 SelectionDAG &DAG) const { 3171 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3172 "ROPI/RWPI not currently supported for Darwin"); 3173 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3174 SDLoc dl(Op); 3175 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3176 3177 if (Subtarget->useMovt(DAG.getMachineFunction())) 3178 ++NumMovwMovt; 3179 3180 // FIXME: Once remat is capable of dealing with instructions with register 3181 // operands, expand this into multiple nodes 3182 unsigned Wrapper = 3183 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3184 3185 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3186 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3187 3188 if (Subtarget->isGVIndirectSymbol(GV)) 3189 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3190 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3191 return Result; 3192 } 3193 3194 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3195 SelectionDAG &DAG) const { 3196 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3197 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3198 "Windows on ARM expects to use movw/movt"); 3199 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3200 "ROPI/RWPI not currently supported for Windows"); 3201 3202 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3203 const ARMII::TOF TargetFlags = 3204 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3205 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3206 SDValue Result; 3207 SDLoc DL(Op); 3208 3209 ++NumMovwMovt; 3210 3211 // FIXME: Once remat is capable of dealing with instructions with register 3212 // operands, expand this into two nodes. 3213 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3214 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3215 TargetFlags)); 3216 if (GV->hasDLLImportStorageClass()) 3217 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3218 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3219 return Result; 3220 } 3221 3222 SDValue 3223 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3224 SDLoc dl(Op); 3225 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3226 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3227 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3228 Op.getOperand(1), Val); 3229 } 3230 3231 SDValue 3232 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3233 SDLoc dl(Op); 3234 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3235 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3236 } 3237 3238 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3239 SelectionDAG &DAG) const { 3240 SDLoc dl(Op); 3241 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3242 Op.getOperand(0)); 3243 } 3244 3245 SDValue 3246 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3247 const ARMSubtarget *Subtarget) const { 3248 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3249 SDLoc dl(Op); 3250 switch (IntNo) { 3251 default: return SDValue(); // Don't custom lower most intrinsics. 3252 case Intrinsic::thread_pointer: { 3253 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3254 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3255 } 3256 case Intrinsic::eh_sjlj_lsda: { 3257 MachineFunction &MF = DAG.getMachineFunction(); 3258 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3259 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3260 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3261 SDValue CPAddr; 3262 bool IsPositionIndependent = isPositionIndependent(); 3263 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3264 ARMConstantPoolValue *CPV = 3265 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 3266 ARMCP::CPLSDA, PCAdj); 3267 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3268 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3269 SDValue Result = DAG.getLoad( 3270 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3271 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3272 3273 if (IsPositionIndependent) { 3274 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3275 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3276 } 3277 return Result; 3278 } 3279 case Intrinsic::arm_neon_vmulls: 3280 case Intrinsic::arm_neon_vmullu: { 3281 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3282 ? ARMISD::VMULLs : ARMISD::VMULLu; 3283 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3284 Op.getOperand(1), Op.getOperand(2)); 3285 } 3286 case Intrinsic::arm_neon_vminnm: 3287 case Intrinsic::arm_neon_vmaxnm: { 3288 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3289 ? ISD::FMINNUM : ISD::FMAXNUM; 3290 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3291 Op.getOperand(1), Op.getOperand(2)); 3292 } 3293 case Intrinsic::arm_neon_vminu: 3294 case Intrinsic::arm_neon_vmaxu: { 3295 if (Op.getValueType().isFloatingPoint()) 3296 return SDValue(); 3297 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3298 ? ISD::UMIN : ISD::UMAX; 3299 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3300 Op.getOperand(1), Op.getOperand(2)); 3301 } 3302 case Intrinsic::arm_neon_vmins: 3303 case Intrinsic::arm_neon_vmaxs: { 3304 // v{min,max}s is overloaded between signed integers and floats. 3305 if (!Op.getValueType().isFloatingPoint()) { 3306 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3307 ? ISD::SMIN : ISD::SMAX; 3308 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3309 Op.getOperand(1), Op.getOperand(2)); 3310 } 3311 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3312 ? ISD::FMINNAN : ISD::FMAXNAN; 3313 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3314 Op.getOperand(1), Op.getOperand(2)); 3315 } 3316 } 3317 } 3318 3319 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3320 const ARMSubtarget *Subtarget) { 3321 // FIXME: handle "fence singlethread" more efficiently. 3322 SDLoc dl(Op); 3323 if (!Subtarget->hasDataBarrier()) { 3324 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3325 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3326 // here. 3327 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3328 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3329 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3330 DAG.getConstant(0, dl, MVT::i32)); 3331 } 3332 3333 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3334 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3335 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3336 if (Subtarget->isMClass()) { 3337 // Only a full system barrier exists in the M-class architectures. 3338 Domain = ARM_MB::SY; 3339 } else if (Subtarget->preferISHSTBarriers() && 3340 Ord == AtomicOrdering::Release) { 3341 // Swift happens to implement ISHST barriers in a way that's compatible with 3342 // Release semantics but weaker than ISH so we'd be fools not to use 3343 // it. Beware: other processors probably don't! 3344 Domain = ARM_MB::ISHST; 3345 } 3346 3347 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3348 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3349 DAG.getConstant(Domain, dl, MVT::i32)); 3350 } 3351 3352 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3353 const ARMSubtarget *Subtarget) { 3354 // ARM pre v5TE and Thumb1 does not have preload instructions. 3355 if (!(Subtarget->isThumb2() || 3356 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3357 // Just preserve the chain. 3358 return Op.getOperand(0); 3359 3360 SDLoc dl(Op); 3361 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3362 if (!isRead && 3363 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3364 // ARMv7 with MP extension has PLDW. 3365 return Op.getOperand(0); 3366 3367 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3368 if (Subtarget->isThumb()) { 3369 // Invert the bits. 3370 isRead = ~isRead & 1; 3371 isData = ~isData & 1; 3372 } 3373 3374 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3375 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3376 DAG.getConstant(isData, dl, MVT::i32)); 3377 } 3378 3379 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3380 MachineFunction &MF = DAG.getMachineFunction(); 3381 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3382 3383 // vastart just stores the address of the VarArgsFrameIndex slot into the 3384 // memory location argument. 3385 SDLoc dl(Op); 3386 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3387 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3388 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3389 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3390 MachinePointerInfo(SV)); 3391 } 3392 3393 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3394 CCValAssign &NextVA, 3395 SDValue &Root, 3396 SelectionDAG &DAG, 3397 const SDLoc &dl) const { 3398 MachineFunction &MF = DAG.getMachineFunction(); 3399 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3400 3401 const TargetRegisterClass *RC; 3402 if (AFI->isThumb1OnlyFunction()) 3403 RC = &ARM::tGPRRegClass; 3404 else 3405 RC = &ARM::GPRRegClass; 3406 3407 // Transform the arguments stored in physical registers into virtual ones. 3408 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3409 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3410 3411 SDValue ArgValue2; 3412 if (NextVA.isMemLoc()) { 3413 MachineFrameInfo &MFI = MF.getFrameInfo(); 3414 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3415 3416 // Create load node to retrieve arguments from the stack. 3417 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3418 ArgValue2 = DAG.getLoad( 3419 MVT::i32, dl, Root, FIN, 3420 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3421 } else { 3422 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3423 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3424 } 3425 if (!Subtarget->isLittle()) 3426 std::swap (ArgValue, ArgValue2); 3427 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3428 } 3429 3430 // The remaining GPRs hold either the beginning of variable-argument 3431 // data, or the beginning of an aggregate passed by value (usually 3432 // byval). Either way, we allocate stack slots adjacent to the data 3433 // provided by our caller, and store the unallocated registers there. 3434 // If this is a variadic function, the va_list pointer will begin with 3435 // these values; otherwise, this reassembles a (byval) structure that 3436 // was split between registers and memory. 3437 // Return: The frame index registers were stored into. 3438 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3439 const SDLoc &dl, SDValue &Chain, 3440 const Value *OrigArg, 3441 unsigned InRegsParamRecordIdx, 3442 int ArgOffset, unsigned ArgSize) const { 3443 // Currently, two use-cases possible: 3444 // Case #1. Non-var-args function, and we meet first byval parameter. 3445 // Setup first unallocated register as first byval register; 3446 // eat all remained registers 3447 // (these two actions are performed by HandleByVal method). 3448 // Then, here, we initialize stack frame with 3449 // "store-reg" instructions. 3450 // Case #2. Var-args function, that doesn't contain byval parameters. 3451 // The same: eat all remained unallocated registers, 3452 // initialize stack frame. 3453 3454 MachineFunction &MF = DAG.getMachineFunction(); 3455 MachineFrameInfo &MFI = MF.getFrameInfo(); 3456 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3457 unsigned RBegin, REnd; 3458 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3459 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3460 } else { 3461 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3462 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3463 REnd = ARM::R4; 3464 } 3465 3466 if (REnd != RBegin) 3467 ArgOffset = -4 * (ARM::R4 - RBegin); 3468 3469 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3470 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3471 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3472 3473 SmallVector<SDValue, 4> MemOps; 3474 const TargetRegisterClass *RC = 3475 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3476 3477 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3478 unsigned VReg = MF.addLiveIn(Reg, RC); 3479 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3480 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3481 MachinePointerInfo(OrigArg, 4 * i)); 3482 MemOps.push_back(Store); 3483 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3484 } 3485 3486 if (!MemOps.empty()) 3487 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3488 return FrameIndex; 3489 } 3490 3491 // Setup stack frame, the va_list pointer will start from. 3492 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3493 const SDLoc &dl, SDValue &Chain, 3494 unsigned ArgOffset, 3495 unsigned TotalArgRegsSaveSize, 3496 bool ForceMutable) const { 3497 MachineFunction &MF = DAG.getMachineFunction(); 3498 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3499 3500 // Try to store any remaining integer argument regs 3501 // to their spots on the stack so that they may be loaded by dereferencing 3502 // the result of va_next. 3503 // If there is no regs to be stored, just point address after last 3504 // argument passed via stack. 3505 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3506 CCInfo.getInRegsParamsCount(), 3507 CCInfo.getNextStackOffset(), 4); 3508 AFI->setVarArgsFrameIndex(FrameIndex); 3509 } 3510 3511 SDValue ARMTargetLowering::LowerFormalArguments( 3512 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3513 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3514 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3515 MachineFunction &MF = DAG.getMachineFunction(); 3516 MachineFrameInfo &MFI = MF.getFrameInfo(); 3517 3518 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3519 3520 // Assign locations to all of the incoming arguments. 3521 SmallVector<CCValAssign, 16> ArgLocs; 3522 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3523 *DAG.getContext()); 3524 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3525 3526 SmallVector<SDValue, 16> ArgValues; 3527 SDValue ArgValue; 3528 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 3529 unsigned CurArgIdx = 0; 3530 3531 // Initially ArgRegsSaveSize is zero. 3532 // Then we increase this value each time we meet byval parameter. 3533 // We also increase this value in case of varargs function. 3534 AFI->setArgRegsSaveSize(0); 3535 3536 // Calculate the amount of stack space that we need to allocate to store 3537 // byval and variadic arguments that are passed in registers. 3538 // We need to know this before we allocate the first byval or variadic 3539 // argument, as they will be allocated a stack slot below the CFA (Canonical 3540 // Frame Address, the stack pointer at entry to the function). 3541 unsigned ArgRegBegin = ARM::R4; 3542 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3543 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3544 break; 3545 3546 CCValAssign &VA = ArgLocs[i]; 3547 unsigned Index = VA.getValNo(); 3548 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3549 if (!Flags.isByVal()) 3550 continue; 3551 3552 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3553 unsigned RBegin, REnd; 3554 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3555 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3556 3557 CCInfo.nextInRegsParam(); 3558 } 3559 CCInfo.rewindByValRegsInfo(); 3560 3561 int lastInsIndex = -1; 3562 if (isVarArg && MFI.hasVAStart()) { 3563 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3564 if (RegIdx != array_lengthof(GPRArgRegs)) 3565 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3566 } 3567 3568 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3569 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3570 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3571 3572 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3573 CCValAssign &VA = ArgLocs[i]; 3574 if (Ins[VA.getValNo()].isOrigArg()) { 3575 std::advance(CurOrigArg, 3576 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3577 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3578 } 3579 // Arguments stored in registers. 3580 if (VA.isRegLoc()) { 3581 EVT RegVT = VA.getLocVT(); 3582 3583 if (VA.needsCustom()) { 3584 // f64 and vector types are split up into multiple registers or 3585 // combinations of registers and stack slots. 3586 if (VA.getLocVT() == MVT::v2f64) { 3587 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3588 Chain, DAG, dl); 3589 VA = ArgLocs[++i]; // skip ahead to next loc 3590 SDValue ArgValue2; 3591 if (VA.isMemLoc()) { 3592 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3593 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3594 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3595 MachinePointerInfo::getFixedStack( 3596 DAG.getMachineFunction(), FI)); 3597 } else { 3598 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3599 Chain, DAG, dl); 3600 } 3601 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3602 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3603 ArgValue, ArgValue1, 3604 DAG.getIntPtrConstant(0, dl)); 3605 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3606 ArgValue, ArgValue2, 3607 DAG.getIntPtrConstant(1, dl)); 3608 } else 3609 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3610 3611 } else { 3612 const TargetRegisterClass *RC; 3613 3614 if (RegVT == MVT::f32) 3615 RC = &ARM::SPRRegClass; 3616 else if (RegVT == MVT::f64) 3617 RC = &ARM::DPRRegClass; 3618 else if (RegVT == MVT::v2f64) 3619 RC = &ARM::QPRRegClass; 3620 else if (RegVT == MVT::i32) 3621 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3622 : &ARM::GPRRegClass; 3623 else 3624 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3625 3626 // Transform the arguments in physical registers into virtual ones. 3627 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3628 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3629 } 3630 3631 // If this is an 8 or 16-bit value, it is really passed promoted 3632 // to 32 bits. Insert an assert[sz]ext to capture this, then 3633 // truncate to the right size. 3634 switch (VA.getLocInfo()) { 3635 default: llvm_unreachable("Unknown loc info!"); 3636 case CCValAssign::Full: break; 3637 case CCValAssign::BCvt: 3638 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3639 break; 3640 case CCValAssign::SExt: 3641 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3642 DAG.getValueType(VA.getValVT())); 3643 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3644 break; 3645 case CCValAssign::ZExt: 3646 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3647 DAG.getValueType(VA.getValVT())); 3648 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3649 break; 3650 } 3651 3652 InVals.push_back(ArgValue); 3653 3654 } else { // VA.isRegLoc() 3655 // sanity check 3656 assert(VA.isMemLoc()); 3657 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3658 3659 int index = VA.getValNo(); 3660 3661 // Some Ins[] entries become multiple ArgLoc[] entries. 3662 // Process them only once. 3663 if (index != lastInsIndex) 3664 { 3665 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3666 // FIXME: For now, all byval parameter objects are marked mutable. 3667 // This can be changed with more analysis. 3668 // In case of tail call optimization mark all arguments mutable. 3669 // Since they could be overwritten by lowering of arguments in case of 3670 // a tail call. 3671 if (Flags.isByVal()) { 3672 assert(Ins[index].isOrigArg() && 3673 "Byval arguments cannot be implicit"); 3674 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3675 3676 int FrameIndex = StoreByValRegs( 3677 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3678 VA.getLocMemOffset(), Flags.getByValSize()); 3679 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3680 CCInfo.nextInRegsParam(); 3681 } else { 3682 unsigned FIOffset = VA.getLocMemOffset(); 3683 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3684 FIOffset, true); 3685 3686 // Create load nodes to retrieve arguments from the stack. 3687 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3688 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3689 MachinePointerInfo::getFixedStack( 3690 DAG.getMachineFunction(), FI))); 3691 } 3692 lastInsIndex = index; 3693 } 3694 } 3695 } 3696 3697 // varargs 3698 if (isVarArg && MFI.hasVAStart()) 3699 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3700 CCInfo.getNextStackOffset(), 3701 TotalArgRegsSaveSize); 3702 3703 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3704 3705 return Chain; 3706 } 3707 3708 /// isFloatingPointZero - Return true if this is +0.0. 3709 static bool isFloatingPointZero(SDValue Op) { 3710 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3711 return CFP->getValueAPF().isPosZero(); 3712 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3713 // Maybe this has already been legalized into the constant pool? 3714 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3715 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3716 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3717 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3718 return CFP->getValueAPF().isPosZero(); 3719 } 3720 } else if (Op->getOpcode() == ISD::BITCAST && 3721 Op->getValueType(0) == MVT::f64) { 3722 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3723 // created by LowerConstantFP(). 3724 SDValue BitcastOp = Op->getOperand(0); 3725 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3726 isNullConstant(BitcastOp->getOperand(0))) 3727 return true; 3728 } 3729 return false; 3730 } 3731 3732 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3733 /// the given operands. 3734 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3735 SDValue &ARMcc, SelectionDAG &DAG, 3736 const SDLoc &dl) const { 3737 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3738 unsigned C = RHSC->getZExtValue(); 3739 if (!isLegalICmpImmediate(C)) { 3740 // Constant does not fit, try adjusting it by one? 3741 switch (CC) { 3742 default: break; 3743 case ISD::SETLT: 3744 case ISD::SETGE: 3745 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3746 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3747 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3748 } 3749 break; 3750 case ISD::SETULT: 3751 case ISD::SETUGE: 3752 if (C != 0 && isLegalICmpImmediate(C-1)) { 3753 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3754 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3755 } 3756 break; 3757 case ISD::SETLE: 3758 case ISD::SETGT: 3759 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3760 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3761 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3762 } 3763 break; 3764 case ISD::SETULE: 3765 case ISD::SETUGT: 3766 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3767 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3768 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3769 } 3770 break; 3771 } 3772 } 3773 } 3774 3775 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3776 ARMISD::NodeType CompareType; 3777 switch (CondCode) { 3778 default: 3779 CompareType = ARMISD::CMP; 3780 break; 3781 case ARMCC::EQ: 3782 case ARMCC::NE: 3783 // Uses only Z Flag 3784 CompareType = ARMISD::CMPZ; 3785 break; 3786 } 3787 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3788 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3789 } 3790 3791 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3792 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3793 SelectionDAG &DAG, const SDLoc &dl, 3794 bool InvalidOnQNaN) const { 3795 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3796 SDValue Cmp; 3797 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3798 if (!isFloatingPointZero(RHS)) 3799 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3800 else 3801 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3802 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3803 } 3804 3805 /// duplicateCmp - Glue values can have only one use, so this function 3806 /// duplicates a comparison node. 3807 SDValue 3808 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3809 unsigned Opc = Cmp.getOpcode(); 3810 SDLoc DL(Cmp); 3811 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3812 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3813 3814 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3815 Cmp = Cmp.getOperand(0); 3816 Opc = Cmp.getOpcode(); 3817 if (Opc == ARMISD::CMPFP) 3818 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3819 Cmp.getOperand(1), Cmp.getOperand(2)); 3820 else { 3821 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3822 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3823 Cmp.getOperand(1)); 3824 } 3825 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3826 } 3827 3828 std::pair<SDValue, SDValue> 3829 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3830 SDValue &ARMcc) const { 3831 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3832 3833 SDValue Value, OverflowCmp; 3834 SDValue LHS = Op.getOperand(0); 3835 SDValue RHS = Op.getOperand(1); 3836 SDLoc dl(Op); 3837 3838 // FIXME: We are currently always generating CMPs because we don't support 3839 // generating CMN through the backend. This is not as good as the natural 3840 // CMP case because it causes a register dependency and cannot be folded 3841 // later. 3842 3843 switch (Op.getOpcode()) { 3844 default: 3845 llvm_unreachable("Unknown overflow instruction!"); 3846 case ISD::SADDO: 3847 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3848 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3849 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3850 break; 3851 case ISD::UADDO: 3852 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3853 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3854 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3855 break; 3856 case ISD::SSUBO: 3857 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3858 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3859 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3860 break; 3861 case ISD::USUBO: 3862 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3863 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3864 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3865 break; 3866 } // switch (...) 3867 3868 return std::make_pair(Value, OverflowCmp); 3869 } 3870 3871 SDValue 3872 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 3873 // Let legalize expand this if it isn't a legal type yet. 3874 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3875 return SDValue(); 3876 3877 SDValue Value, OverflowCmp; 3878 SDValue ARMcc; 3879 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3880 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3881 SDLoc dl(Op); 3882 // We use 0 and 1 as false and true values. 3883 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3884 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3885 EVT VT = Op.getValueType(); 3886 3887 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3888 ARMcc, CCR, OverflowCmp); 3889 3890 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3891 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3892 } 3893 3894 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3895 SDValue Cond = Op.getOperand(0); 3896 SDValue SelectTrue = Op.getOperand(1); 3897 SDValue SelectFalse = Op.getOperand(2); 3898 SDLoc dl(Op); 3899 unsigned Opc = Cond.getOpcode(); 3900 3901 if (Cond.getResNo() == 1 && 3902 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3903 Opc == ISD::USUBO)) { 3904 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 3905 return SDValue(); 3906 3907 SDValue Value, OverflowCmp; 3908 SDValue ARMcc; 3909 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 3910 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3911 EVT VT = Op.getValueType(); 3912 3913 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 3914 OverflowCmp, DAG); 3915 } 3916 3917 // Convert: 3918 // 3919 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3920 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3921 // 3922 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3923 const ConstantSDNode *CMOVTrue = 3924 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3925 const ConstantSDNode *CMOVFalse = 3926 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3927 3928 if (CMOVTrue && CMOVFalse) { 3929 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3930 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3931 3932 SDValue True; 3933 SDValue False; 3934 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3935 True = SelectTrue; 3936 False = SelectFalse; 3937 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3938 True = SelectFalse; 3939 False = SelectTrue; 3940 } 3941 3942 if (True.getNode() && False.getNode()) { 3943 EVT VT = Op.getValueType(); 3944 SDValue ARMcc = Cond.getOperand(2); 3945 SDValue CCR = Cond.getOperand(3); 3946 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3947 assert(True.getValueType() == VT); 3948 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 3949 } 3950 } 3951 } 3952 3953 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3954 // undefined bits before doing a full-word comparison with zero. 3955 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3956 DAG.getConstant(1, dl, Cond.getValueType())); 3957 3958 return DAG.getSelectCC(dl, Cond, 3959 DAG.getConstant(0, dl, Cond.getValueType()), 3960 SelectTrue, SelectFalse, ISD::SETNE); 3961 } 3962 3963 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3964 bool &swpCmpOps, bool &swpVselOps) { 3965 // Start by selecting the GE condition code for opcodes that return true for 3966 // 'equality' 3967 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3968 CC == ISD::SETULE) 3969 CondCode = ARMCC::GE; 3970 3971 // and GT for opcodes that return false for 'equality'. 3972 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3973 CC == ISD::SETULT) 3974 CondCode = ARMCC::GT; 3975 3976 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3977 // to swap the compare operands. 3978 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3979 CC == ISD::SETULT) 3980 swpCmpOps = true; 3981 3982 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3983 // If we have an unordered opcode, we need to swap the operands to the VSEL 3984 // instruction (effectively negating the condition). 3985 // 3986 // This also has the effect of swapping which one of 'less' or 'greater' 3987 // returns true, so we also swap the compare operands. It also switches 3988 // whether we return true for 'equality', so we compensate by picking the 3989 // opposite condition code to our original choice. 3990 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3991 CC == ISD::SETUGT) { 3992 swpCmpOps = !swpCmpOps; 3993 swpVselOps = !swpVselOps; 3994 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3995 } 3996 3997 // 'ordered' is 'anything but unordered', so use the VS condition code and 3998 // swap the VSEL operands. 3999 if (CC == ISD::SETO) { 4000 CondCode = ARMCC::VS; 4001 swpVselOps = true; 4002 } 4003 4004 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4005 // code and swap the VSEL operands. 4006 if (CC == ISD::SETUNE) { 4007 CondCode = ARMCC::EQ; 4008 swpVselOps = true; 4009 } 4010 } 4011 4012 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4013 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4014 SDValue Cmp, SelectionDAG &DAG) const { 4015 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4016 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4017 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4018 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4019 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4020 4021 SDValue TrueLow = TrueVal.getValue(0); 4022 SDValue TrueHigh = TrueVal.getValue(1); 4023 SDValue FalseLow = FalseVal.getValue(0); 4024 SDValue FalseHigh = FalseVal.getValue(1); 4025 4026 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4027 ARMcc, CCR, Cmp); 4028 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4029 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4030 4031 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4032 } else { 4033 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4034 Cmp); 4035 } 4036 } 4037 4038 static bool isGTorGE(ISD::CondCode CC) { 4039 return CC == ISD::SETGT || CC == ISD::SETGE; 4040 } 4041 4042 static bool isLTorLE(ISD::CondCode CC) { 4043 return CC == ISD::SETLT || CC == ISD::SETLE; 4044 } 4045 4046 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4047 // All of these conditions (and their <= and >= counterparts) will do: 4048 // x < k ? k : x 4049 // x > k ? x : k 4050 // k < x ? x : k 4051 // k > x ? k : x 4052 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4053 const SDValue TrueVal, const SDValue FalseVal, 4054 const ISD::CondCode CC, const SDValue K) { 4055 return (isGTorGE(CC) && 4056 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4057 (isLTorLE(CC) && 4058 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4059 } 4060 4061 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4062 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4063 const SDValue TrueVal, const SDValue FalseVal, 4064 const ISD::CondCode CC, const SDValue K) { 4065 return (isGTorGE(CC) && 4066 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4067 (isLTorLE(CC) && 4068 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4069 } 4070 4071 // Check if two chained conditionals could be converted into SSAT. 4072 // 4073 // SSAT can replace a set of two conditional selectors that bound a number to an 4074 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4075 // 4076 // x < -k ? -k : (x > k ? k : x) 4077 // x < -k ? -k : (x < k ? x : k) 4078 // x > -k ? (x > k ? k : x) : -k 4079 // x < k ? (x < -k ? -k : x) : k 4080 // etc. 4081 // 4082 // It returns true if the conversion can be done, false otherwise. 4083 // Additionally, the variable is returned in parameter V and the constant in K. 4084 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4085 uint64_t &K) { 4086 SDValue LHS1 = Op.getOperand(0); 4087 SDValue RHS1 = Op.getOperand(1); 4088 SDValue TrueVal1 = Op.getOperand(2); 4089 SDValue FalseVal1 = Op.getOperand(3); 4090 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4091 4092 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4093 if (Op2.getOpcode() != ISD::SELECT_CC) 4094 return false; 4095 4096 SDValue LHS2 = Op2.getOperand(0); 4097 SDValue RHS2 = Op2.getOperand(1); 4098 SDValue TrueVal2 = Op2.getOperand(2); 4099 SDValue FalseVal2 = Op2.getOperand(3); 4100 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4101 4102 // Find out which are the constants and which are the variables 4103 // in each conditional 4104 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4105 ? &RHS1 4106 : nullptr; 4107 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4108 ? &RHS2 4109 : nullptr; 4110 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4111 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4112 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4113 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4114 4115 // We must detect cases where the original operations worked with 16- or 4116 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4117 // must work with sign-extended values but the select operations return 4118 // the original non-extended value. 4119 SDValue V2TmpReg = V2Tmp; 4120 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4121 V2TmpReg = V2Tmp->getOperand(0); 4122 4123 // Check that the registers and the constants have the correct values 4124 // in both conditionals 4125 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4126 V2TmpReg != V2) 4127 return false; 4128 4129 // Figure out which conditional is saturating the lower/upper bound. 4130 const SDValue *LowerCheckOp = 4131 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4132 ? &Op 4133 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4134 ? &Op2 4135 : nullptr; 4136 const SDValue *UpperCheckOp = 4137 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4138 ? &Op 4139 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4140 ? &Op2 4141 : nullptr; 4142 4143 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4144 return false; 4145 4146 // Check that the constant in the lower-bound check is 4147 // the opposite of the constant in the upper-bound check 4148 // in 1's complement. 4149 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4150 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4151 int64_t PosVal = std::max(Val1, Val2); 4152 4153 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4154 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4155 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) { 4156 4157 V = V2; 4158 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4159 return true; 4160 } 4161 4162 return false; 4163 } 4164 4165 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4166 EVT VT = Op.getValueType(); 4167 SDLoc dl(Op); 4168 4169 // Try to convert two saturating conditional selects into a single SSAT 4170 SDValue SatValue; 4171 uint64_t SatConstant; 4172 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4173 isSaturatingConditional(Op, SatValue, SatConstant)) 4174 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4175 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4176 4177 SDValue LHS = Op.getOperand(0); 4178 SDValue RHS = Op.getOperand(1); 4179 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4180 SDValue TrueVal = Op.getOperand(2); 4181 SDValue FalseVal = Op.getOperand(3); 4182 4183 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4184 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4185 dl); 4186 4187 // If softenSetCCOperands only returned one value, we should compare it to 4188 // zero. 4189 if (!RHS.getNode()) { 4190 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4191 CC = ISD::SETNE; 4192 } 4193 } 4194 4195 if (LHS.getValueType() == MVT::i32) { 4196 // Try to generate VSEL on ARMv8. 4197 // The VSEL instruction can't use all the usual ARM condition 4198 // codes: it only has two bits to select the condition code, so it's 4199 // constrained to use only GE, GT, VS and EQ. 4200 // 4201 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4202 // swap the operands of the previous compare instruction (effectively 4203 // inverting the compare condition, swapping 'less' and 'greater') and 4204 // sometimes need to swap the operands to the VSEL (which inverts the 4205 // condition in the sense of firing whenever the previous condition didn't) 4206 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4207 TrueVal.getValueType() == MVT::f64)) { 4208 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4209 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4210 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4211 CC = ISD::getSetCCInverse(CC, true); 4212 std::swap(TrueVal, FalseVal); 4213 } 4214 } 4215 4216 SDValue ARMcc; 4217 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4218 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4219 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4220 } 4221 4222 ARMCC::CondCodes CondCode, CondCode2; 4223 bool InvalidOnQNaN; 4224 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4225 4226 // Try to generate VMAXNM/VMINNM on ARMv8. 4227 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4228 TrueVal.getValueType() == MVT::f64)) { 4229 bool swpCmpOps = false; 4230 bool swpVselOps = false; 4231 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4232 4233 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4234 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4235 if (swpCmpOps) 4236 std::swap(LHS, RHS); 4237 if (swpVselOps) 4238 std::swap(TrueVal, FalseVal); 4239 } 4240 } 4241 4242 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4243 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4244 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4245 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4246 if (CondCode2 != ARMCC::AL) { 4247 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4248 // FIXME: Needs another CMP because flag can have but one use. 4249 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4250 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4251 } 4252 return Result; 4253 } 4254 4255 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4256 /// to morph to an integer compare sequence. 4257 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4258 const ARMSubtarget *Subtarget) { 4259 SDNode *N = Op.getNode(); 4260 if (!N->hasOneUse()) 4261 // Otherwise it requires moving the value from fp to integer registers. 4262 return false; 4263 if (!N->getNumValues()) 4264 return false; 4265 EVT VT = Op.getValueType(); 4266 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4267 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4268 // vmrs are very slow, e.g. cortex-a8. 4269 return false; 4270 4271 if (isFloatingPointZero(Op)) { 4272 SeenZero = true; 4273 return true; 4274 } 4275 return ISD::isNormalLoad(N); 4276 } 4277 4278 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4279 if (isFloatingPointZero(Op)) 4280 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4281 4282 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4283 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4284 Ld->getPointerInfo(), Ld->getAlignment(), 4285 Ld->getMemOperand()->getFlags()); 4286 4287 llvm_unreachable("Unknown VFP cmp argument!"); 4288 } 4289 4290 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4291 SDValue &RetVal1, SDValue &RetVal2) { 4292 SDLoc dl(Op); 4293 4294 if (isFloatingPointZero(Op)) { 4295 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4296 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4297 return; 4298 } 4299 4300 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4301 SDValue Ptr = Ld->getBasePtr(); 4302 RetVal1 = 4303 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4304 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4305 4306 EVT PtrType = Ptr.getValueType(); 4307 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4308 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4309 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4310 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4311 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4312 Ld->getMemOperand()->getFlags()); 4313 return; 4314 } 4315 4316 llvm_unreachable("Unknown VFP cmp argument!"); 4317 } 4318 4319 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4320 /// f32 and even f64 comparisons to integer ones. 4321 SDValue 4322 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4323 SDValue Chain = Op.getOperand(0); 4324 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4325 SDValue LHS = Op.getOperand(2); 4326 SDValue RHS = Op.getOperand(3); 4327 SDValue Dest = Op.getOperand(4); 4328 SDLoc dl(Op); 4329 4330 bool LHSSeenZero = false; 4331 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4332 bool RHSSeenZero = false; 4333 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4334 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4335 // If unsafe fp math optimization is enabled and there are no other uses of 4336 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4337 // to an integer comparison. 4338 if (CC == ISD::SETOEQ) 4339 CC = ISD::SETEQ; 4340 else if (CC == ISD::SETUNE) 4341 CC = ISD::SETNE; 4342 4343 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4344 SDValue ARMcc; 4345 if (LHS.getValueType() == MVT::f32) { 4346 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4347 bitcastf32Toi32(LHS, DAG), Mask); 4348 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4349 bitcastf32Toi32(RHS, DAG), Mask); 4350 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4351 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4352 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4353 Chain, Dest, ARMcc, CCR, Cmp); 4354 } 4355 4356 SDValue LHS1, LHS2; 4357 SDValue RHS1, RHS2; 4358 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4359 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4360 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4361 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4362 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4363 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4364 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4365 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4366 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4367 } 4368 4369 return SDValue(); 4370 } 4371 4372 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4373 SDValue Chain = Op.getOperand(0); 4374 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4375 SDValue LHS = Op.getOperand(2); 4376 SDValue RHS = Op.getOperand(3); 4377 SDValue Dest = Op.getOperand(4); 4378 SDLoc dl(Op); 4379 4380 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4381 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4382 dl); 4383 4384 // If softenSetCCOperands only returned one value, we should compare it to 4385 // zero. 4386 if (!RHS.getNode()) { 4387 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4388 CC = ISD::SETNE; 4389 } 4390 } 4391 4392 if (LHS.getValueType() == MVT::i32) { 4393 SDValue ARMcc; 4394 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4395 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4396 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4397 Chain, Dest, ARMcc, CCR, Cmp); 4398 } 4399 4400 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4401 4402 if (getTargetMachine().Options.UnsafeFPMath && 4403 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4404 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4405 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4406 return Result; 4407 } 4408 4409 ARMCC::CondCodes CondCode, CondCode2; 4410 bool InvalidOnQNaN; 4411 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4412 4413 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4414 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4415 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4416 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4417 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4418 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4419 if (CondCode2 != ARMCC::AL) { 4420 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4421 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4422 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4423 } 4424 return Res; 4425 } 4426 4427 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4428 SDValue Chain = Op.getOperand(0); 4429 SDValue Table = Op.getOperand(1); 4430 SDValue Index = Op.getOperand(2); 4431 SDLoc dl(Op); 4432 4433 EVT PTy = getPointerTy(DAG.getDataLayout()); 4434 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4435 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4436 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4437 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4438 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 4439 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4440 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4441 // which does another jump to the destination. This also makes it easier 4442 // to translate it to TBB / TBH later (Thumb2 only). 4443 // FIXME: This might not work if the function is extremely large. 4444 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4445 Addr, Op.getOperand(2), JTI); 4446 } 4447 if (isPositionIndependent() || Subtarget->isROPI()) { 4448 Addr = 4449 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4450 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4451 Chain = Addr.getValue(1); 4452 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 4453 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4454 } else { 4455 Addr = 4456 DAG.getLoad(PTy, dl, Chain, Addr, 4457 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4458 Chain = Addr.getValue(1); 4459 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4460 } 4461 } 4462 4463 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4464 EVT VT = Op.getValueType(); 4465 SDLoc dl(Op); 4466 4467 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4468 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4469 return Op; 4470 return DAG.UnrollVectorOp(Op.getNode()); 4471 } 4472 4473 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4474 "Invalid type for custom lowering!"); 4475 if (VT != MVT::v4i16) 4476 return DAG.UnrollVectorOp(Op.getNode()); 4477 4478 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4479 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4480 } 4481 4482 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4483 EVT VT = Op.getValueType(); 4484 if (VT.isVector()) 4485 return LowerVectorFP_TO_INT(Op, DAG); 4486 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4487 RTLIB::Libcall LC; 4488 if (Op.getOpcode() == ISD::FP_TO_SINT) 4489 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4490 Op.getValueType()); 4491 else 4492 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4493 Op.getValueType()); 4494 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4495 /*isSigned*/ false, SDLoc(Op)).first; 4496 } 4497 4498 return Op; 4499 } 4500 4501 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4502 EVT VT = Op.getValueType(); 4503 SDLoc dl(Op); 4504 4505 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4506 if (VT.getVectorElementType() == MVT::f32) 4507 return Op; 4508 return DAG.UnrollVectorOp(Op.getNode()); 4509 } 4510 4511 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4512 "Invalid type for custom lowering!"); 4513 if (VT != MVT::v4f32) 4514 return DAG.UnrollVectorOp(Op.getNode()); 4515 4516 unsigned CastOpc; 4517 unsigned Opc; 4518 switch (Op.getOpcode()) { 4519 default: llvm_unreachable("Invalid opcode!"); 4520 case ISD::SINT_TO_FP: 4521 CastOpc = ISD::SIGN_EXTEND; 4522 Opc = ISD::SINT_TO_FP; 4523 break; 4524 case ISD::UINT_TO_FP: 4525 CastOpc = ISD::ZERO_EXTEND; 4526 Opc = ISD::UINT_TO_FP; 4527 break; 4528 } 4529 4530 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4531 return DAG.getNode(Opc, dl, VT, Op); 4532 } 4533 4534 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4535 EVT VT = Op.getValueType(); 4536 if (VT.isVector()) 4537 return LowerVectorINT_TO_FP(Op, DAG); 4538 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4539 RTLIB::Libcall LC; 4540 if (Op.getOpcode() == ISD::SINT_TO_FP) 4541 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4542 Op.getValueType()); 4543 else 4544 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4545 Op.getValueType()); 4546 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4547 /*isSigned*/ false, SDLoc(Op)).first; 4548 } 4549 4550 return Op; 4551 } 4552 4553 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4554 // Implement fcopysign with a fabs and a conditional fneg. 4555 SDValue Tmp0 = Op.getOperand(0); 4556 SDValue Tmp1 = Op.getOperand(1); 4557 SDLoc dl(Op); 4558 EVT VT = Op.getValueType(); 4559 EVT SrcVT = Tmp1.getValueType(); 4560 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4561 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4562 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4563 4564 if (UseNEON) { 4565 // Use VBSL to copy the sign bit. 4566 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4567 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4568 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4569 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4570 if (VT == MVT::f64) 4571 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4572 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4573 DAG.getConstant(32, dl, MVT::i32)); 4574 else /*if (VT == MVT::f32)*/ 4575 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4576 if (SrcVT == MVT::f32) { 4577 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4578 if (VT == MVT::f64) 4579 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4580 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4581 DAG.getConstant(32, dl, MVT::i32)); 4582 } else if (VT == MVT::f32) 4583 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4584 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4585 DAG.getConstant(32, dl, MVT::i32)); 4586 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4587 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4588 4589 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4590 dl, MVT::i32); 4591 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4592 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4593 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4594 4595 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4596 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4597 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4598 if (VT == MVT::f32) { 4599 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4600 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4601 DAG.getConstant(0, dl, MVT::i32)); 4602 } else { 4603 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4604 } 4605 4606 return Res; 4607 } 4608 4609 // Bitcast operand 1 to i32. 4610 if (SrcVT == MVT::f64) 4611 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4612 Tmp1).getValue(1); 4613 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4614 4615 // Or in the signbit with integer operations. 4616 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4617 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4618 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4619 if (VT == MVT::f32) { 4620 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4621 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4622 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4623 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4624 } 4625 4626 // f64: Or the high part with signbit and then combine two parts. 4627 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4628 Tmp0); 4629 SDValue Lo = Tmp0.getValue(0); 4630 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4631 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4632 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4633 } 4634 4635 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4636 MachineFunction &MF = DAG.getMachineFunction(); 4637 MachineFrameInfo &MFI = MF.getFrameInfo(); 4638 MFI.setReturnAddressIsTaken(true); 4639 4640 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4641 return SDValue(); 4642 4643 EVT VT = Op.getValueType(); 4644 SDLoc dl(Op); 4645 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4646 if (Depth) { 4647 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4648 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4649 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4650 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4651 MachinePointerInfo()); 4652 } 4653 4654 // Return LR, which contains the return address. Mark it an implicit live-in. 4655 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4656 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4657 } 4658 4659 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4660 const ARMBaseRegisterInfo &ARI = 4661 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4662 MachineFunction &MF = DAG.getMachineFunction(); 4663 MachineFrameInfo &MFI = MF.getFrameInfo(); 4664 MFI.setFrameAddressIsTaken(true); 4665 4666 EVT VT = Op.getValueType(); 4667 SDLoc dl(Op); // FIXME probably not meaningful 4668 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4669 unsigned FrameReg = ARI.getFrameRegister(MF); 4670 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4671 while (Depth--) 4672 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4673 MachinePointerInfo()); 4674 return FrameAddr; 4675 } 4676 4677 // FIXME? Maybe this could be a TableGen attribute on some registers and 4678 // this table could be generated automatically from RegInfo. 4679 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4680 SelectionDAG &DAG) const { 4681 unsigned Reg = StringSwitch<unsigned>(RegName) 4682 .Case("sp", ARM::SP) 4683 .Default(0); 4684 if (Reg) 4685 return Reg; 4686 report_fatal_error(Twine("Invalid register name \"" 4687 + StringRef(RegName) + "\".")); 4688 } 4689 4690 // Result is 64 bit value so split into two 32 bit values and return as a 4691 // pair of values. 4692 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4693 SelectionDAG &DAG) { 4694 SDLoc DL(N); 4695 4696 // This function is only supposed to be called for i64 type destination. 4697 assert(N->getValueType(0) == MVT::i64 4698 && "ExpandREAD_REGISTER called for non-i64 type result."); 4699 4700 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4701 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4702 N->getOperand(0), 4703 N->getOperand(1)); 4704 4705 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4706 Read.getValue(1))); 4707 Results.push_back(Read.getOperand(0)); 4708 } 4709 4710 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4711 /// When \p DstVT, the destination type of \p BC, is on the vector 4712 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4713 /// it might be possible to combine them, such that everything stays on the 4714 /// vector register bank. 4715 /// \p return The node that would replace \p BT, if the combine 4716 /// is possible. 4717 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4718 SelectionDAG &DAG) { 4719 SDValue Op = BC->getOperand(0); 4720 EVT DstVT = BC->getValueType(0); 4721 4722 // The only vector instruction that can produce a scalar (remember, 4723 // since the bitcast was about to be turned into VMOVDRR, the source 4724 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4725 // Moreover, we can do this combine only if there is one use. 4726 // Finally, if the destination type is not a vector, there is not 4727 // much point on forcing everything on the vector bank. 4728 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4729 !Op.hasOneUse()) 4730 return SDValue(); 4731 4732 // If the index is not constant, we will introduce an additional 4733 // multiply that will stick. 4734 // Give up in that case. 4735 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4736 if (!Index) 4737 return SDValue(); 4738 unsigned DstNumElt = DstVT.getVectorNumElements(); 4739 4740 // Compute the new index. 4741 const APInt &APIntIndex = Index->getAPIntValue(); 4742 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4743 NewIndex *= APIntIndex; 4744 // Check if the new constant index fits into i32. 4745 if (NewIndex.getBitWidth() > 32) 4746 return SDValue(); 4747 4748 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4749 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4750 SDLoc dl(Op); 4751 SDValue ExtractSrc = Op.getOperand(0); 4752 EVT VecVT = EVT::getVectorVT( 4753 *DAG.getContext(), DstVT.getScalarType(), 4754 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4755 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4756 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4757 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4758 } 4759 4760 /// ExpandBITCAST - If the target supports VFP, this function is called to 4761 /// expand a bit convert where either the source or destination type is i64 to 4762 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4763 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4764 /// vectors), since the legalizer won't know what to do with that. 4765 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4766 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4767 SDLoc dl(N); 4768 SDValue Op = N->getOperand(0); 4769 4770 // This function is only supposed to be called for i64 types, either as the 4771 // source or destination of the bit convert. 4772 EVT SrcVT = Op.getValueType(); 4773 EVT DstVT = N->getValueType(0); 4774 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4775 "ExpandBITCAST called for non-i64 type"); 4776 4777 // Turn i64->f64 into VMOVDRR. 4778 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4779 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4780 // if we can combine the bitcast with its source. 4781 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4782 return Val; 4783 4784 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4785 DAG.getConstant(0, dl, MVT::i32)); 4786 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4787 DAG.getConstant(1, dl, MVT::i32)); 4788 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4789 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4790 } 4791 4792 // Turn f64->i64 into VMOVRRD. 4793 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4794 SDValue Cvt; 4795 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4796 SrcVT.getVectorNumElements() > 1) 4797 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4798 DAG.getVTList(MVT::i32, MVT::i32), 4799 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4800 else 4801 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4802 DAG.getVTList(MVT::i32, MVT::i32), Op); 4803 // Merge the pieces into a single i64 value. 4804 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4805 } 4806 4807 return SDValue(); 4808 } 4809 4810 /// getZeroVector - Returns a vector of specified type with all zero elements. 4811 /// Zero vectors are used to represent vector negation and in those cases 4812 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4813 /// not support i64 elements, so sometimes the zero vectors will need to be 4814 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4815 /// zero vector. 4816 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 4817 assert(VT.isVector() && "Expected a vector type"); 4818 // The canonical modified immediate encoding of a zero vector is....0! 4819 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4820 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4821 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4822 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4823 } 4824 4825 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4826 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4827 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4828 SelectionDAG &DAG) const { 4829 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4830 EVT VT = Op.getValueType(); 4831 unsigned VTBits = VT.getSizeInBits(); 4832 SDLoc dl(Op); 4833 SDValue ShOpLo = Op.getOperand(0); 4834 SDValue ShOpHi = Op.getOperand(1); 4835 SDValue ShAmt = Op.getOperand(2); 4836 SDValue ARMcc; 4837 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4838 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4839 4840 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4841 4842 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4843 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4844 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4845 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4846 DAG.getConstant(VTBits, dl, MVT::i32)); 4847 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4848 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4849 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4850 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4851 ISD::SETGE, ARMcc, DAG, dl); 4852 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 4853 ARMcc, CCR, CmpLo); 4854 4855 4856 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4857 SDValue HiBigShift = Opc == ISD::SRA 4858 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4859 DAG.getConstant(VTBits - 1, dl, VT)) 4860 : DAG.getConstant(0, dl, VT); 4861 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4862 ISD::SETGE, ARMcc, DAG, dl); 4863 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 4864 ARMcc, CCR, CmpHi); 4865 4866 SDValue Ops[2] = { Lo, Hi }; 4867 return DAG.getMergeValues(Ops, dl); 4868 } 4869 4870 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4871 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4872 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 4873 SelectionDAG &DAG) const { 4874 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4875 EVT VT = Op.getValueType(); 4876 unsigned VTBits = VT.getSizeInBits(); 4877 SDLoc dl(Op); 4878 SDValue ShOpLo = Op.getOperand(0); 4879 SDValue ShOpHi = Op.getOperand(1); 4880 SDValue ShAmt = Op.getOperand(2); 4881 SDValue ARMcc; 4882 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4883 4884 assert(Op.getOpcode() == ISD::SHL_PARTS); 4885 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4886 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4887 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4888 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4889 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4890 4891 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4892 DAG.getConstant(VTBits, dl, MVT::i32)); 4893 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4894 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4895 ISD::SETGE, ARMcc, DAG, dl); 4896 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 4897 ARMcc, CCR, CmpHi); 4898 4899 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4900 ISD::SETGE, ARMcc, DAG, dl); 4901 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4902 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 4903 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 4904 4905 SDValue Ops[2] = { Lo, Hi }; 4906 return DAG.getMergeValues(Ops, dl); 4907 } 4908 4909 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 4910 SelectionDAG &DAG) const { 4911 // The rounding mode is in bits 23:22 of the FPSCR. 4912 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 4913 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 4914 // so that the shift + and get folded into a bitfield extract. 4915 SDLoc dl(Op); 4916 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 4917 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, 4918 MVT::i32)); 4919 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 4920 DAG.getConstant(1U << 22, dl, MVT::i32)); 4921 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 4922 DAG.getConstant(22, dl, MVT::i32)); 4923 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 4924 DAG.getConstant(3, dl, MVT::i32)); 4925 } 4926 4927 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 4928 const ARMSubtarget *ST) { 4929 SDLoc dl(N); 4930 EVT VT = N->getValueType(0); 4931 if (VT.isVector()) { 4932 assert(ST->hasNEON()); 4933 4934 // Compute the least significant set bit: LSB = X & -X 4935 SDValue X = N->getOperand(0); 4936 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 4937 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 4938 4939 EVT ElemTy = VT.getVectorElementType(); 4940 4941 if (ElemTy == MVT::i8) { 4942 // Compute with: cttz(x) = ctpop(lsb - 1) 4943 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4944 DAG.getTargetConstant(1, dl, ElemTy)); 4945 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4946 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 4947 } 4948 4949 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 4950 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 4951 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 4952 unsigned NumBits = ElemTy.getSizeInBits(); 4953 SDValue WidthMinus1 = 4954 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4955 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 4956 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 4957 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 4958 } 4959 4960 // Compute with: cttz(x) = ctpop(lsb - 1) 4961 4962 // Since we can only compute the number of bits in a byte with vcnt.8, we 4963 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 4964 // and i64. 4965 4966 // Compute LSB - 1. 4967 SDValue Bits; 4968 if (ElemTy == MVT::i64) { 4969 // Load constant 0xffff'ffff'ffff'ffff to register. 4970 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4971 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 4972 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 4973 } else { 4974 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 4975 DAG.getTargetConstant(1, dl, ElemTy)); 4976 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 4977 } 4978 4979 // Count #bits with vcnt.8. 4980 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4981 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 4982 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 4983 4984 // Gather the #bits with vpaddl (pairwise add.) 4985 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4986 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 4987 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4988 Cnt8); 4989 if (ElemTy == MVT::i16) 4990 return Cnt16; 4991 4992 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 4993 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 4994 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 4995 Cnt16); 4996 if (ElemTy == MVT::i32) 4997 return Cnt32; 4998 4999 assert(ElemTy == MVT::i64); 5000 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5001 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5002 Cnt32); 5003 return Cnt64; 5004 } 5005 5006 if (!ST->hasV6T2Ops()) 5007 return SDValue(); 5008 5009 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5010 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5011 } 5012 5013 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 5014 /// for each 16-bit element from operand, repeated. The basic idea is to 5015 /// leverage vcnt to get the 8-bit counts, gather and add the results. 5016 /// 5017 /// Trace for v4i16: 5018 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5019 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 5020 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 5021 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 5022 /// [b0 b1 b2 b3 b4 b5 b6 b7] 5023 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 5024 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 5025 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 5026 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 5027 EVT VT = N->getValueType(0); 5028 SDLoc DL(N); 5029 5030 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5031 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5032 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5033 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5034 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5035 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5036 } 5037 5038 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5039 /// bit-count for each 16-bit element from the operand. We need slightly 5040 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5041 /// 64/128-bit registers. 5042 /// 5043 /// Trace for v4i16: 5044 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5045 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5046 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5047 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5048 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5049 EVT VT = N->getValueType(0); 5050 SDLoc DL(N); 5051 5052 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5053 if (VT.is64BitVector()) { 5054 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5055 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5056 DAG.getIntPtrConstant(0, DL)); 5057 } else { 5058 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5059 BitCounts, DAG.getIntPtrConstant(0, DL)); 5060 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5061 } 5062 } 5063 5064 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5065 /// bit-count for each 32-bit element from the operand. The idea here is 5066 /// to split the vector into 16-bit elements, leverage the 16-bit count 5067 /// routine, and then combine the results. 5068 /// 5069 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5070 /// input = [v0 v1 ] (vi: 32-bit elements) 5071 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5072 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5073 /// vrev: N0 = [k1 k0 k3 k2 ] 5074 /// [k0 k1 k2 k3 ] 5075 /// N1 =+[k1 k0 k3 k2 ] 5076 /// [k0 k2 k1 k3 ] 5077 /// N2 =+[k1 k3 k0 k2 ] 5078 /// [k0 k2 k1 k3 ] 5079 /// Extended =+[k1 k3 k0 k2 ] 5080 /// [k0 k2 ] 5081 /// Extracted=+[k1 k3 ] 5082 /// 5083 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5084 EVT VT = N->getValueType(0); 5085 SDLoc DL(N); 5086 5087 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5088 5089 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5090 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5091 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5092 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5093 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5094 5095 if (VT.is64BitVector()) { 5096 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5097 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5098 DAG.getIntPtrConstant(0, DL)); 5099 } else { 5100 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5101 DAG.getIntPtrConstant(0, DL)); 5102 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5103 } 5104 } 5105 5106 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5107 const ARMSubtarget *ST) { 5108 EVT VT = N->getValueType(0); 5109 5110 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5111 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5112 VT == MVT::v4i16 || VT == MVT::v8i16) && 5113 "Unexpected type for custom ctpop lowering"); 5114 5115 if (VT.getVectorElementType() == MVT::i32) 5116 return lowerCTPOP32BitElements(N, DAG); 5117 else 5118 return lowerCTPOP16BitElements(N, DAG); 5119 } 5120 5121 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5122 const ARMSubtarget *ST) { 5123 EVT VT = N->getValueType(0); 5124 SDLoc dl(N); 5125 5126 if (!VT.isVector()) 5127 return SDValue(); 5128 5129 // Lower vector shifts on NEON to use VSHL. 5130 assert(ST->hasNEON() && "unexpected vector shift"); 5131 5132 // Left shifts translate directly to the vshiftu intrinsic. 5133 if (N->getOpcode() == ISD::SHL) 5134 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5135 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5136 MVT::i32), 5137 N->getOperand(0), N->getOperand(1)); 5138 5139 assert((N->getOpcode() == ISD::SRA || 5140 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5141 5142 // NEON uses the same intrinsics for both left and right shifts. For 5143 // right shifts, the shift amounts are negative, so negate the vector of 5144 // shift amounts. 5145 EVT ShiftVT = N->getOperand(1).getValueType(); 5146 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5147 getZeroVector(ShiftVT, DAG, dl), 5148 N->getOperand(1)); 5149 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5150 Intrinsic::arm_neon_vshifts : 5151 Intrinsic::arm_neon_vshiftu); 5152 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5153 DAG.getConstant(vshiftInt, dl, MVT::i32), 5154 N->getOperand(0), NegatedCount); 5155 } 5156 5157 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5158 const ARMSubtarget *ST) { 5159 EVT VT = N->getValueType(0); 5160 SDLoc dl(N); 5161 5162 // We can get here for a node like i32 = ISD::SHL i32, i64 5163 if (VT != MVT::i64) 5164 return SDValue(); 5165 5166 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5167 "Unknown shift to lower!"); 5168 5169 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5170 if (!isOneConstant(N->getOperand(1))) 5171 return SDValue(); 5172 5173 // If we are in thumb mode, we don't have RRX. 5174 if (ST->isThumb1Only()) return SDValue(); 5175 5176 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5177 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5178 DAG.getConstant(0, dl, MVT::i32)); 5179 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5180 DAG.getConstant(1, dl, MVT::i32)); 5181 5182 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5183 // captures the result into a carry flag. 5184 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5185 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5186 5187 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5188 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5189 5190 // Merge the pieces into a single i64 value. 5191 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5192 } 5193 5194 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5195 SDValue TmpOp0, TmpOp1; 5196 bool Invert = false; 5197 bool Swap = false; 5198 unsigned Opc = 0; 5199 5200 SDValue Op0 = Op.getOperand(0); 5201 SDValue Op1 = Op.getOperand(1); 5202 SDValue CC = Op.getOperand(2); 5203 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5204 EVT VT = Op.getValueType(); 5205 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5206 SDLoc dl(Op); 5207 5208 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5209 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5210 // Special-case integer 64-bit equality comparisons. They aren't legal, 5211 // but they can be lowered with a few vector instructions. 5212 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5213 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5214 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5215 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5216 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5217 DAG.getCondCode(ISD::SETEQ)); 5218 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5219 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5220 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5221 if (SetCCOpcode == ISD::SETNE) 5222 Merged = DAG.getNOT(dl, Merged, CmpVT); 5223 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5224 return Merged; 5225 } 5226 5227 if (CmpVT.getVectorElementType() == MVT::i64) 5228 // 64-bit comparisons are not legal in general. 5229 return SDValue(); 5230 5231 if (Op1.getValueType().isFloatingPoint()) { 5232 switch (SetCCOpcode) { 5233 default: llvm_unreachable("Illegal FP comparison"); 5234 case ISD::SETUNE: 5235 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5236 case ISD::SETOEQ: 5237 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5238 case ISD::SETOLT: 5239 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5240 case ISD::SETOGT: 5241 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5242 case ISD::SETOLE: 5243 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5244 case ISD::SETOGE: 5245 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5246 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5247 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5248 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5249 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5250 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5251 case ISD::SETONE: 5252 // Expand this to (OLT | OGT). 5253 TmpOp0 = Op0; 5254 TmpOp1 = Op1; 5255 Opc = ISD::OR; 5256 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5257 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5258 break; 5259 case ISD::SETUO: 5260 Invert = true; 5261 LLVM_FALLTHROUGH; 5262 case ISD::SETO: 5263 // Expand this to (OLT | OGE). 5264 TmpOp0 = Op0; 5265 TmpOp1 = Op1; 5266 Opc = ISD::OR; 5267 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5268 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5269 break; 5270 } 5271 } else { 5272 // Integer comparisons. 5273 switch (SetCCOpcode) { 5274 default: llvm_unreachable("Illegal integer comparison"); 5275 case ISD::SETNE: Invert = true; 5276 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5277 case ISD::SETLT: Swap = true; 5278 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5279 case ISD::SETLE: Swap = true; 5280 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5281 case ISD::SETULT: Swap = true; 5282 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5283 case ISD::SETULE: Swap = true; 5284 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5285 } 5286 5287 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5288 if (Opc == ARMISD::VCEQ) { 5289 5290 SDValue AndOp; 5291 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5292 AndOp = Op0; 5293 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5294 AndOp = Op1; 5295 5296 // Ignore bitconvert. 5297 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5298 AndOp = AndOp.getOperand(0); 5299 5300 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5301 Opc = ARMISD::VTST; 5302 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5303 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5304 Invert = !Invert; 5305 } 5306 } 5307 } 5308 5309 if (Swap) 5310 std::swap(Op0, Op1); 5311 5312 // If one of the operands is a constant vector zero, attempt to fold the 5313 // comparison to a specialized compare-against-zero form. 5314 SDValue SingleOp; 5315 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5316 SingleOp = Op0; 5317 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5318 if (Opc == ARMISD::VCGE) 5319 Opc = ARMISD::VCLEZ; 5320 else if (Opc == ARMISD::VCGT) 5321 Opc = ARMISD::VCLTZ; 5322 SingleOp = Op1; 5323 } 5324 5325 SDValue Result; 5326 if (SingleOp.getNode()) { 5327 switch (Opc) { 5328 case ARMISD::VCEQ: 5329 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5330 case ARMISD::VCGE: 5331 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5332 case ARMISD::VCLEZ: 5333 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5334 case ARMISD::VCGT: 5335 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5336 case ARMISD::VCLTZ: 5337 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5338 default: 5339 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5340 } 5341 } else { 5342 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5343 } 5344 5345 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5346 5347 if (Invert) 5348 Result = DAG.getNOT(dl, Result, VT); 5349 5350 return Result; 5351 } 5352 5353 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5354 SDValue LHS = Op.getOperand(0); 5355 SDValue RHS = Op.getOperand(1); 5356 SDValue Carry = Op.getOperand(2); 5357 SDValue Cond = Op.getOperand(3); 5358 SDLoc DL(Op); 5359 5360 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5361 5362 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5363 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5364 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5365 5366 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5367 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5368 SDValue ARMcc = DAG.getConstant( 5369 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5370 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5371 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5372 Cmp.getValue(1), SDValue()); 5373 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5374 CCR, Chain.getValue(1)); 5375 } 5376 5377 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5378 /// valid vector constant for a NEON instruction with a "modified immediate" 5379 /// operand (e.g., VMOV). If so, return the encoded value. 5380 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5381 unsigned SplatBitSize, SelectionDAG &DAG, 5382 const SDLoc &dl, EVT &VT, bool is128Bits, 5383 NEONModImmType type) { 5384 unsigned OpCmode, Imm; 5385 5386 // SplatBitSize is set to the smallest size that splats the vector, so a 5387 // zero vector will always have SplatBitSize == 8. However, NEON modified 5388 // immediate instructions others than VMOV do not support the 8-bit encoding 5389 // of a zero vector, and the default encoding of zero is supposed to be the 5390 // 32-bit version. 5391 if (SplatBits == 0) 5392 SplatBitSize = 32; 5393 5394 switch (SplatBitSize) { 5395 case 8: 5396 if (type != VMOVModImm) 5397 return SDValue(); 5398 // Any 1-byte value is OK. Op=0, Cmode=1110. 5399 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5400 OpCmode = 0xe; 5401 Imm = SplatBits; 5402 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5403 break; 5404 5405 case 16: 5406 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5407 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5408 if ((SplatBits & ~0xff) == 0) { 5409 // Value = 0x00nn: Op=x, Cmode=100x. 5410 OpCmode = 0x8; 5411 Imm = SplatBits; 5412 break; 5413 } 5414 if ((SplatBits & ~0xff00) == 0) { 5415 // Value = 0xnn00: Op=x, Cmode=101x. 5416 OpCmode = 0xa; 5417 Imm = SplatBits >> 8; 5418 break; 5419 } 5420 return SDValue(); 5421 5422 case 32: 5423 // NEON's 32-bit VMOV supports splat values where: 5424 // * only one byte is nonzero, or 5425 // * the least significant byte is 0xff and the second byte is nonzero, or 5426 // * the least significant 2 bytes are 0xff and the third is nonzero. 5427 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5428 if ((SplatBits & ~0xff) == 0) { 5429 // Value = 0x000000nn: Op=x, Cmode=000x. 5430 OpCmode = 0; 5431 Imm = SplatBits; 5432 break; 5433 } 5434 if ((SplatBits & ~0xff00) == 0) { 5435 // Value = 0x0000nn00: Op=x, Cmode=001x. 5436 OpCmode = 0x2; 5437 Imm = SplatBits >> 8; 5438 break; 5439 } 5440 if ((SplatBits & ~0xff0000) == 0) { 5441 // Value = 0x00nn0000: Op=x, Cmode=010x. 5442 OpCmode = 0x4; 5443 Imm = SplatBits >> 16; 5444 break; 5445 } 5446 if ((SplatBits & ~0xff000000) == 0) { 5447 // Value = 0xnn000000: Op=x, Cmode=011x. 5448 OpCmode = 0x6; 5449 Imm = SplatBits >> 24; 5450 break; 5451 } 5452 5453 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5454 if (type == OtherModImm) return SDValue(); 5455 5456 if ((SplatBits & ~0xffff) == 0 && 5457 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5458 // Value = 0x0000nnff: Op=x, Cmode=1100. 5459 OpCmode = 0xc; 5460 Imm = SplatBits >> 8; 5461 break; 5462 } 5463 5464 if ((SplatBits & ~0xffffff) == 0 && 5465 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5466 // Value = 0x00nnffff: Op=x, Cmode=1101. 5467 OpCmode = 0xd; 5468 Imm = SplatBits >> 16; 5469 break; 5470 } 5471 5472 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5473 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5474 // VMOV.I32. A (very) minor optimization would be to replicate the value 5475 // and fall through here to test for a valid 64-bit splat. But, then the 5476 // caller would also need to check and handle the change in size. 5477 return SDValue(); 5478 5479 case 64: { 5480 if (type != VMOVModImm) 5481 return SDValue(); 5482 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5483 uint64_t BitMask = 0xff; 5484 uint64_t Val = 0; 5485 unsigned ImmMask = 1; 5486 Imm = 0; 5487 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5488 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5489 Val |= BitMask; 5490 Imm |= ImmMask; 5491 } else if ((SplatBits & BitMask) != 0) { 5492 return SDValue(); 5493 } 5494 BitMask <<= 8; 5495 ImmMask <<= 1; 5496 } 5497 5498 if (DAG.getDataLayout().isBigEndian()) 5499 // swap higher and lower 32 bit word 5500 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5501 5502 // Op=1, Cmode=1110. 5503 OpCmode = 0x1e; 5504 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5505 break; 5506 } 5507 5508 default: 5509 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5510 } 5511 5512 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5513 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5514 } 5515 5516 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5517 const ARMSubtarget *ST) const { 5518 bool IsDouble = Op.getValueType() == MVT::f64; 5519 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5520 const APFloat &FPVal = CFP->getValueAPF(); 5521 5522 // Prevent floating-point constants from using literal loads 5523 // when execute-only is enabled. 5524 if (ST->genExecuteOnly()) { 5525 APInt INTVal = FPVal.bitcastToAPInt(); 5526 SDLoc DL(CFP); 5527 if (IsDouble) { 5528 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5529 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5530 if (!ST->isLittle()) 5531 std::swap(Lo, Hi); 5532 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5533 } else { 5534 return DAG.getConstant(INTVal, DL, MVT::i32); 5535 } 5536 } 5537 5538 if (!ST->hasVFP3()) 5539 return SDValue(); 5540 5541 // Use the default (constant pool) lowering for double constants when we have 5542 // an SP-only FPU 5543 if (IsDouble && Subtarget->isFPOnlySP()) 5544 return SDValue(); 5545 5546 // Try splatting with a VMOV.f32... 5547 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5548 5549 if (ImmVal != -1) { 5550 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5551 // We have code in place to select a valid ConstantFP already, no need to 5552 // do any mangling. 5553 return Op; 5554 } 5555 5556 // It's a float and we are trying to use NEON operations where 5557 // possible. Lower it to a splat followed by an extract. 5558 SDLoc DL(Op); 5559 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5560 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5561 NewVal); 5562 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5563 DAG.getConstant(0, DL, MVT::i32)); 5564 } 5565 5566 // The rest of our options are NEON only, make sure that's allowed before 5567 // proceeding.. 5568 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5569 return SDValue(); 5570 5571 EVT VMovVT; 5572 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5573 5574 // It wouldn't really be worth bothering for doubles except for one very 5575 // important value, which does happen to match: 0.0. So make sure we don't do 5576 // anything stupid. 5577 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5578 return SDValue(); 5579 5580 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5581 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5582 VMovVT, false, VMOVModImm); 5583 if (NewVal != SDValue()) { 5584 SDLoc DL(Op); 5585 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5586 NewVal); 5587 if (IsDouble) 5588 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5589 5590 // It's a float: cast and extract a vector element. 5591 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5592 VecConstant); 5593 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5594 DAG.getConstant(0, DL, MVT::i32)); 5595 } 5596 5597 // Finally, try a VMVN.i32 5598 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5599 false, VMVNModImm); 5600 if (NewVal != SDValue()) { 5601 SDLoc DL(Op); 5602 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5603 5604 if (IsDouble) 5605 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5606 5607 // It's a float: cast and extract a vector element. 5608 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5609 VecConstant); 5610 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5611 DAG.getConstant(0, DL, MVT::i32)); 5612 } 5613 5614 return SDValue(); 5615 } 5616 5617 // check if an VEXT instruction can handle the shuffle mask when the 5618 // vector sources of the shuffle are the same. 5619 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5620 unsigned NumElts = VT.getVectorNumElements(); 5621 5622 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5623 if (M[0] < 0) 5624 return false; 5625 5626 Imm = M[0]; 5627 5628 // If this is a VEXT shuffle, the immediate value is the index of the first 5629 // element. The other shuffle indices must be the successive elements after 5630 // the first one. 5631 unsigned ExpectedElt = Imm; 5632 for (unsigned i = 1; i < NumElts; ++i) { 5633 // Increment the expected index. If it wraps around, just follow it 5634 // back to index zero and keep going. 5635 ++ExpectedElt; 5636 if (ExpectedElt == NumElts) 5637 ExpectedElt = 0; 5638 5639 if (M[i] < 0) continue; // ignore UNDEF indices 5640 if (ExpectedElt != static_cast<unsigned>(M[i])) 5641 return false; 5642 } 5643 5644 return true; 5645 } 5646 5647 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5648 bool &ReverseVEXT, unsigned &Imm) { 5649 unsigned NumElts = VT.getVectorNumElements(); 5650 ReverseVEXT = false; 5651 5652 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5653 if (M[0] < 0) 5654 return false; 5655 5656 Imm = M[0]; 5657 5658 // If this is a VEXT shuffle, the immediate value is the index of the first 5659 // element. The other shuffle indices must be the successive elements after 5660 // the first one. 5661 unsigned ExpectedElt = Imm; 5662 for (unsigned i = 1; i < NumElts; ++i) { 5663 // Increment the expected index. If it wraps around, it may still be 5664 // a VEXT but the source vectors must be swapped. 5665 ExpectedElt += 1; 5666 if (ExpectedElt == NumElts * 2) { 5667 ExpectedElt = 0; 5668 ReverseVEXT = true; 5669 } 5670 5671 if (M[i] < 0) continue; // ignore UNDEF indices 5672 if (ExpectedElt != static_cast<unsigned>(M[i])) 5673 return false; 5674 } 5675 5676 // Adjust the index value if the source operands will be swapped. 5677 if (ReverseVEXT) 5678 Imm -= NumElts; 5679 5680 return true; 5681 } 5682 5683 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5684 /// instruction with the specified blocksize. (The order of the elements 5685 /// within each block of the vector is reversed.) 5686 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5687 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5688 "Only possible block sizes for VREV are: 16, 32, 64"); 5689 5690 unsigned EltSz = VT.getScalarSizeInBits(); 5691 if (EltSz == 64) 5692 return false; 5693 5694 unsigned NumElts = VT.getVectorNumElements(); 5695 unsigned BlockElts = M[0] + 1; 5696 // If the first shuffle index is UNDEF, be optimistic. 5697 if (M[0] < 0) 5698 BlockElts = BlockSize / EltSz; 5699 5700 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5701 return false; 5702 5703 for (unsigned i = 0; i < NumElts; ++i) { 5704 if (M[i] < 0) continue; // ignore UNDEF indices 5705 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5706 return false; 5707 } 5708 5709 return true; 5710 } 5711 5712 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5713 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5714 // range, then 0 is placed into the resulting vector. So pretty much any mask 5715 // of 8 elements can work here. 5716 return VT == MVT::v8i8 && M.size() == 8; 5717 } 5718 5719 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5720 // checking that pairs of elements in the shuffle mask represent the same index 5721 // in each vector, incrementing the expected index by 2 at each step. 5722 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5723 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5724 // v2={e,f,g,h} 5725 // WhichResult gives the offset for each element in the mask based on which 5726 // of the two results it belongs to. 5727 // 5728 // The transpose can be represented either as: 5729 // result1 = shufflevector v1, v2, result1_shuffle_mask 5730 // result2 = shufflevector v1, v2, result2_shuffle_mask 5731 // where v1/v2 and the shuffle masks have the same number of elements 5732 // (here WhichResult (see below) indicates which result is being checked) 5733 // 5734 // or as: 5735 // results = shufflevector v1, v2, shuffle_mask 5736 // where both results are returned in one vector and the shuffle mask has twice 5737 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5738 // want to check the low half and high half of the shuffle mask as if it were 5739 // the other case 5740 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5741 unsigned EltSz = VT.getScalarSizeInBits(); 5742 if (EltSz == 64) 5743 return false; 5744 5745 unsigned NumElts = VT.getVectorNumElements(); 5746 if (M.size() != NumElts && M.size() != NumElts*2) 5747 return false; 5748 5749 // If the mask is twice as long as the input vector then we need to check the 5750 // upper and lower parts of the mask with a matching value for WhichResult 5751 // FIXME: A mask with only even values will be rejected in case the first 5752 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5753 // M[0] is used to determine WhichResult 5754 for (unsigned i = 0; i < M.size(); i += NumElts) { 5755 if (M.size() == NumElts * 2) 5756 WhichResult = i / NumElts; 5757 else 5758 WhichResult = M[i] == 0 ? 0 : 1; 5759 for (unsigned j = 0; j < NumElts; j += 2) { 5760 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5761 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5762 return false; 5763 } 5764 } 5765 5766 if (M.size() == NumElts*2) 5767 WhichResult = 0; 5768 5769 return true; 5770 } 5771 5772 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5773 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5774 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5775 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5776 unsigned EltSz = VT.getScalarSizeInBits(); 5777 if (EltSz == 64) 5778 return false; 5779 5780 unsigned NumElts = VT.getVectorNumElements(); 5781 if (M.size() != NumElts && M.size() != NumElts*2) 5782 return false; 5783 5784 for (unsigned i = 0; i < M.size(); i += NumElts) { 5785 if (M.size() == NumElts * 2) 5786 WhichResult = i / NumElts; 5787 else 5788 WhichResult = M[i] == 0 ? 0 : 1; 5789 for (unsigned j = 0; j < NumElts; j += 2) { 5790 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5791 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5792 return false; 5793 } 5794 } 5795 5796 if (M.size() == NumElts*2) 5797 WhichResult = 0; 5798 5799 return true; 5800 } 5801 5802 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5803 // that the mask elements are either all even and in steps of size 2 or all odd 5804 // and in steps of size 2. 5805 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5806 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5807 // v2={e,f,g,h} 5808 // Requires similar checks to that of isVTRNMask with 5809 // respect the how results are returned. 5810 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5811 unsigned EltSz = VT.getScalarSizeInBits(); 5812 if (EltSz == 64) 5813 return false; 5814 5815 unsigned NumElts = VT.getVectorNumElements(); 5816 if (M.size() != NumElts && M.size() != NumElts*2) 5817 return false; 5818 5819 for (unsigned i = 0; i < M.size(); i += NumElts) { 5820 WhichResult = M[i] == 0 ? 0 : 1; 5821 for (unsigned j = 0; j < NumElts; ++j) { 5822 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5823 return false; 5824 } 5825 } 5826 5827 if (M.size() == NumElts*2) 5828 WhichResult = 0; 5829 5830 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5831 if (VT.is64BitVector() && EltSz == 32) 5832 return false; 5833 5834 return true; 5835 } 5836 5837 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5838 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5839 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5840 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5841 unsigned EltSz = VT.getScalarSizeInBits(); 5842 if (EltSz == 64) 5843 return false; 5844 5845 unsigned NumElts = VT.getVectorNumElements(); 5846 if (M.size() != NumElts && M.size() != NumElts*2) 5847 return false; 5848 5849 unsigned Half = NumElts / 2; 5850 for (unsigned i = 0; i < M.size(); i += NumElts) { 5851 WhichResult = M[i] == 0 ? 0 : 1; 5852 for (unsigned j = 0; j < NumElts; j += Half) { 5853 unsigned Idx = WhichResult; 5854 for (unsigned k = 0; k < Half; ++k) { 5855 int MIdx = M[i + j + k]; 5856 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5857 return false; 5858 Idx += 2; 5859 } 5860 } 5861 } 5862 5863 if (M.size() == NumElts*2) 5864 WhichResult = 0; 5865 5866 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5867 if (VT.is64BitVector() && EltSz == 32) 5868 return false; 5869 5870 return true; 5871 } 5872 5873 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 5874 // that pairs of elements of the shufflemask represent the same index in each 5875 // vector incrementing sequentially through the vectors. 5876 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 5877 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 5878 // v2={e,f,g,h} 5879 // Requires similar checks to that of isVTRNMask with respect the how results 5880 // are returned. 5881 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5882 unsigned EltSz = VT.getScalarSizeInBits(); 5883 if (EltSz == 64) 5884 return false; 5885 5886 unsigned NumElts = VT.getVectorNumElements(); 5887 if (M.size() != NumElts && M.size() != NumElts*2) 5888 return false; 5889 5890 for (unsigned i = 0; i < M.size(); i += NumElts) { 5891 WhichResult = M[i] == 0 ? 0 : 1; 5892 unsigned Idx = WhichResult * NumElts / 2; 5893 for (unsigned j = 0; j < NumElts; j += 2) { 5894 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5895 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 5896 return false; 5897 Idx += 1; 5898 } 5899 } 5900 5901 if (M.size() == NumElts*2) 5902 WhichResult = 0; 5903 5904 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5905 if (VT.is64BitVector() && EltSz == 32) 5906 return false; 5907 5908 return true; 5909 } 5910 5911 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 5912 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5913 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5914 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5915 unsigned EltSz = VT.getScalarSizeInBits(); 5916 if (EltSz == 64) 5917 return false; 5918 5919 unsigned NumElts = VT.getVectorNumElements(); 5920 if (M.size() != NumElts && M.size() != NumElts*2) 5921 return false; 5922 5923 for (unsigned i = 0; i < M.size(); i += NumElts) { 5924 WhichResult = M[i] == 0 ? 0 : 1; 5925 unsigned Idx = WhichResult * NumElts / 2; 5926 for (unsigned j = 0; j < NumElts; j += 2) { 5927 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 5928 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 5929 return false; 5930 Idx += 1; 5931 } 5932 } 5933 5934 if (M.size() == NumElts*2) 5935 WhichResult = 0; 5936 5937 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5938 if (VT.is64BitVector() && EltSz == 32) 5939 return false; 5940 5941 return true; 5942 } 5943 5944 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 5945 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 5946 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 5947 unsigned &WhichResult, 5948 bool &isV_UNDEF) { 5949 isV_UNDEF = false; 5950 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5951 return ARMISD::VTRN; 5952 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5953 return ARMISD::VUZP; 5954 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5955 return ARMISD::VZIP; 5956 5957 isV_UNDEF = true; 5958 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5959 return ARMISD::VTRN; 5960 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5961 return ARMISD::VUZP; 5962 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5963 return ARMISD::VZIP; 5964 5965 return 0; 5966 } 5967 5968 /// \return true if this is a reverse operation on an vector. 5969 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 5970 unsigned NumElts = VT.getVectorNumElements(); 5971 // Make sure the mask has the right size. 5972 if (NumElts != M.size()) 5973 return false; 5974 5975 // Look for <15, ..., 3, -1, 1, 0>. 5976 for (unsigned i = 0; i != NumElts; ++i) 5977 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 5978 return false; 5979 5980 return true; 5981 } 5982 5983 // If N is an integer constant that can be moved into a register in one 5984 // instruction, return an SDValue of such a constant (will become a MOV 5985 // instruction). Otherwise return null. 5986 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 5987 const ARMSubtarget *ST, const SDLoc &dl) { 5988 uint64_t Val; 5989 if (!isa<ConstantSDNode>(N)) 5990 return SDValue(); 5991 Val = cast<ConstantSDNode>(N)->getZExtValue(); 5992 5993 if (ST->isThumb1Only()) { 5994 if (Val <= 255 || ~Val <= 255) 5995 return DAG.getConstant(Val, dl, MVT::i32); 5996 } else { 5997 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 5998 return DAG.getConstant(Val, dl, MVT::i32); 5999 } 6000 return SDValue(); 6001 } 6002 6003 // If this is a case we can't handle, return null and let the default 6004 // expansion code take care of it. 6005 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6006 const ARMSubtarget *ST) const { 6007 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6008 SDLoc dl(Op); 6009 EVT VT = Op.getValueType(); 6010 6011 APInt SplatBits, SplatUndef; 6012 unsigned SplatBitSize; 6013 bool HasAnyUndefs; 6014 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6015 if (SplatUndef.isAllOnesValue()) 6016 return DAG.getUNDEF(VT); 6017 6018 if (SplatBitSize <= 64) { 6019 // Check if an immediate VMOV works. 6020 EVT VmovVT; 6021 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6022 SplatUndef.getZExtValue(), SplatBitSize, 6023 DAG, dl, VmovVT, VT.is128BitVector(), 6024 VMOVModImm); 6025 if (Val.getNode()) { 6026 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6027 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6028 } 6029 6030 // Try an immediate VMVN. 6031 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6032 Val = isNEONModifiedImm(NegatedImm, 6033 SplatUndef.getZExtValue(), SplatBitSize, 6034 DAG, dl, VmovVT, VT.is128BitVector(), 6035 VMVNModImm); 6036 if (Val.getNode()) { 6037 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6038 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6039 } 6040 6041 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6042 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6043 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6044 if (ImmVal != -1) { 6045 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6046 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6047 } 6048 } 6049 } 6050 } 6051 6052 // Scan through the operands to see if only one value is used. 6053 // 6054 // As an optimisation, even if more than one value is used it may be more 6055 // profitable to splat with one value then change some lanes. 6056 // 6057 // Heuristically we decide to do this if the vector has a "dominant" value, 6058 // defined as splatted to more than half of the lanes. 6059 unsigned NumElts = VT.getVectorNumElements(); 6060 bool isOnlyLowElement = true; 6061 bool usesOnlyOneValue = true; 6062 bool hasDominantValue = false; 6063 bool isConstant = true; 6064 6065 // Map of the number of times a particular SDValue appears in the 6066 // element list. 6067 DenseMap<SDValue, unsigned> ValueCounts; 6068 SDValue Value; 6069 for (unsigned i = 0; i < NumElts; ++i) { 6070 SDValue V = Op.getOperand(i); 6071 if (V.isUndef()) 6072 continue; 6073 if (i > 0) 6074 isOnlyLowElement = false; 6075 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6076 isConstant = false; 6077 6078 ValueCounts.insert(std::make_pair(V, 0)); 6079 unsigned &Count = ValueCounts[V]; 6080 6081 // Is this value dominant? (takes up more than half of the lanes) 6082 if (++Count > (NumElts / 2)) { 6083 hasDominantValue = true; 6084 Value = V; 6085 } 6086 } 6087 if (ValueCounts.size() != 1) 6088 usesOnlyOneValue = false; 6089 if (!Value.getNode() && !ValueCounts.empty()) 6090 Value = ValueCounts.begin()->first; 6091 6092 if (ValueCounts.empty()) 6093 return DAG.getUNDEF(VT); 6094 6095 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6096 // Keep going if we are hitting this case. 6097 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6098 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6099 6100 unsigned EltSize = VT.getScalarSizeInBits(); 6101 6102 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6103 // i32 and try again. 6104 if (hasDominantValue && EltSize <= 32) { 6105 if (!isConstant) { 6106 SDValue N; 6107 6108 // If we are VDUPing a value that comes directly from a vector, that will 6109 // cause an unnecessary move to and from a GPR, where instead we could 6110 // just use VDUPLANE. We can only do this if the lane being extracted 6111 // is at a constant index, as the VDUP from lane instructions only have 6112 // constant-index forms. 6113 ConstantSDNode *constIndex; 6114 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6115 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6116 // We need to create a new undef vector to use for the VDUPLANE if the 6117 // size of the vector from which we get the value is different than the 6118 // size of the vector that we need to create. We will insert the element 6119 // such that the register coalescer will remove unnecessary copies. 6120 if (VT != Value->getOperand(0).getValueType()) { 6121 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6122 VT.getVectorNumElements(); 6123 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6124 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6125 Value, DAG.getConstant(index, dl, MVT::i32)), 6126 DAG.getConstant(index, dl, MVT::i32)); 6127 } else 6128 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6129 Value->getOperand(0), Value->getOperand(1)); 6130 } else 6131 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6132 6133 if (!usesOnlyOneValue) { 6134 // The dominant value was splatted as 'N', but we now have to insert 6135 // all differing elements. 6136 for (unsigned I = 0; I < NumElts; ++I) { 6137 if (Op.getOperand(I) == Value) 6138 continue; 6139 SmallVector<SDValue, 3> Ops; 6140 Ops.push_back(N); 6141 Ops.push_back(Op.getOperand(I)); 6142 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6143 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6144 } 6145 } 6146 return N; 6147 } 6148 if (VT.getVectorElementType().isFloatingPoint()) { 6149 SmallVector<SDValue, 8> Ops; 6150 for (unsigned i = 0; i < NumElts; ++i) 6151 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6152 Op.getOperand(i))); 6153 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6154 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6155 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6156 if (Val.getNode()) 6157 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6158 } 6159 if (usesOnlyOneValue) { 6160 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6161 if (isConstant && Val.getNode()) 6162 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6163 } 6164 } 6165 6166 // If all elements are constants and the case above didn't get hit, fall back 6167 // to the default expansion, which will generate a load from the constant 6168 // pool. 6169 if (isConstant) 6170 return SDValue(); 6171 6172 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6173 if (NumElts >= 4) { 6174 SDValue shuffle = ReconstructShuffle(Op, DAG); 6175 if (shuffle != SDValue()) 6176 return shuffle; 6177 } 6178 6179 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6180 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6181 // into two 64-bit vectors; we might discover a better way to lower it. 6182 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6183 EVT ExtVT = VT.getVectorElementType(); 6184 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6185 SDValue Lower = 6186 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6187 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6188 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6189 SDValue Upper = DAG.getBuildVector( 6190 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6191 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6192 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6193 if (Lower && Upper) 6194 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6195 } 6196 6197 // Vectors with 32- or 64-bit elements can be built by directly assigning 6198 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6199 // will be legalized. 6200 if (EltSize >= 32) { 6201 // Do the expansion with floating-point types, since that is what the VFP 6202 // registers are defined to use, and since i64 is not legal. 6203 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6204 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6205 SmallVector<SDValue, 8> Ops; 6206 for (unsigned i = 0; i < NumElts; ++i) 6207 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6208 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6209 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6210 } 6211 6212 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6213 // know the default expansion would otherwise fall back on something even 6214 // worse. For a vector with one or two non-undef values, that's 6215 // scalar_to_vector for the elements followed by a shuffle (provided the 6216 // shuffle is valid for the target) and materialization element by element 6217 // on the stack followed by a load for everything else. 6218 if (!isConstant && !usesOnlyOneValue) { 6219 SDValue Vec = DAG.getUNDEF(VT); 6220 for (unsigned i = 0 ; i < NumElts; ++i) { 6221 SDValue V = Op.getOperand(i); 6222 if (V.isUndef()) 6223 continue; 6224 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6225 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6226 } 6227 return Vec; 6228 } 6229 6230 return SDValue(); 6231 } 6232 6233 // Gather data to see if the operation can be modelled as a 6234 // shuffle in combination with VEXTs. 6235 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6236 SelectionDAG &DAG) const { 6237 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6238 SDLoc dl(Op); 6239 EVT VT = Op.getValueType(); 6240 unsigned NumElts = VT.getVectorNumElements(); 6241 6242 struct ShuffleSourceInfo { 6243 SDValue Vec; 6244 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6245 unsigned MaxElt = 0; 6246 6247 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6248 // be compatible with the shuffle we intend to construct. As a result 6249 // ShuffleVec will be some sliding window into the original Vec. 6250 SDValue ShuffleVec; 6251 6252 // Code should guarantee that element i in Vec starts at element "WindowBase 6253 // + i * WindowScale in ShuffleVec". 6254 int WindowBase = 0; 6255 int WindowScale = 1; 6256 6257 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6258 6259 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6260 }; 6261 6262 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6263 // node. 6264 SmallVector<ShuffleSourceInfo, 2> Sources; 6265 for (unsigned i = 0; i < NumElts; ++i) { 6266 SDValue V = Op.getOperand(i); 6267 if (V.isUndef()) 6268 continue; 6269 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6270 // A shuffle can only come from building a vector from various 6271 // elements of other vectors. 6272 return SDValue(); 6273 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6274 // Furthermore, shuffles require a constant mask, whereas extractelts 6275 // accept variable indices. 6276 return SDValue(); 6277 } 6278 6279 // Add this element source to the list if it's not already there. 6280 SDValue SourceVec = V.getOperand(0); 6281 auto Source = llvm::find(Sources, SourceVec); 6282 if (Source == Sources.end()) 6283 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6284 6285 // Update the minimum and maximum lane number seen. 6286 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6287 Source->MinElt = std::min(Source->MinElt, EltNo); 6288 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6289 } 6290 6291 // Currently only do something sane when at most two source vectors 6292 // are involved. 6293 if (Sources.size() > 2) 6294 return SDValue(); 6295 6296 // Find out the smallest element size among result and two sources, and use 6297 // it as element size to build the shuffle_vector. 6298 EVT SmallestEltTy = VT.getVectorElementType(); 6299 for (auto &Source : Sources) { 6300 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6301 if (SrcEltTy.bitsLT(SmallestEltTy)) 6302 SmallestEltTy = SrcEltTy; 6303 } 6304 unsigned ResMultiplier = 6305 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6306 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6307 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6308 6309 // If the source vector is too wide or too narrow, we may nevertheless be able 6310 // to construct a compatible shuffle either by concatenating it with UNDEF or 6311 // extracting a suitable range of elements. 6312 for (auto &Src : Sources) { 6313 EVT SrcVT = Src.ShuffleVec.getValueType(); 6314 6315 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6316 continue; 6317 6318 // This stage of the search produces a source with the same element type as 6319 // the original, but with a total width matching the BUILD_VECTOR output. 6320 EVT EltVT = SrcVT.getVectorElementType(); 6321 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6322 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6323 6324 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6325 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6326 return SDValue(); 6327 // We can pad out the smaller vector for free, so if it's part of a 6328 // shuffle... 6329 Src.ShuffleVec = 6330 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6331 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6332 continue; 6333 } 6334 6335 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6336 return SDValue(); 6337 6338 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6339 // Span too large for a VEXT to cope 6340 return SDValue(); 6341 } 6342 6343 if (Src.MinElt >= NumSrcElts) { 6344 // The extraction can just take the second half 6345 Src.ShuffleVec = 6346 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6347 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6348 Src.WindowBase = -NumSrcElts; 6349 } else if (Src.MaxElt < NumSrcElts) { 6350 // The extraction can just take the first half 6351 Src.ShuffleVec = 6352 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6353 DAG.getConstant(0, dl, MVT::i32)); 6354 } else { 6355 // An actual VEXT is needed 6356 SDValue VEXTSrc1 = 6357 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6358 DAG.getConstant(0, dl, MVT::i32)); 6359 SDValue VEXTSrc2 = 6360 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6361 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6362 6363 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6364 VEXTSrc2, 6365 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6366 Src.WindowBase = -Src.MinElt; 6367 } 6368 } 6369 6370 // Another possible incompatibility occurs from the vector element types. We 6371 // can fix this by bitcasting the source vectors to the same type we intend 6372 // for the shuffle. 6373 for (auto &Src : Sources) { 6374 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6375 if (SrcEltTy == SmallestEltTy) 6376 continue; 6377 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6378 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6379 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6380 Src.WindowBase *= Src.WindowScale; 6381 } 6382 6383 // Final sanity check before we try to actually produce a shuffle. 6384 DEBUG( 6385 for (auto Src : Sources) 6386 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6387 ); 6388 6389 // The stars all align, our next step is to produce the mask for the shuffle. 6390 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6391 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6392 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6393 SDValue Entry = Op.getOperand(i); 6394 if (Entry.isUndef()) 6395 continue; 6396 6397 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6398 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6399 6400 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6401 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6402 // segment. 6403 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6404 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6405 VT.getScalarSizeInBits()); 6406 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6407 6408 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6409 // starting at the appropriate offset. 6410 int *LaneMask = &Mask[i * ResMultiplier]; 6411 6412 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6413 ExtractBase += NumElts * (Src - Sources.begin()); 6414 for (int j = 0; j < LanesDefined; ++j) 6415 LaneMask[j] = ExtractBase + j; 6416 } 6417 6418 // Final check before we try to produce nonsense... 6419 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6420 return SDValue(); 6421 6422 // We can't handle more than two sources. This should have already 6423 // been checked before this point. 6424 assert(Sources.size() <= 2 && "Too many sources!"); 6425 6426 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6427 for (unsigned i = 0; i < Sources.size(); ++i) 6428 ShuffleOps[i] = Sources[i].ShuffleVec; 6429 6430 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6431 ShuffleOps[1], Mask); 6432 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6433 } 6434 6435 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6436 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6437 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6438 /// are assumed to be legal. 6439 bool 6440 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6441 EVT VT) const { 6442 if (VT.getVectorNumElements() == 4 && 6443 (VT.is128BitVector() || VT.is64BitVector())) { 6444 unsigned PFIndexes[4]; 6445 for (unsigned i = 0; i != 4; ++i) { 6446 if (M[i] < 0) 6447 PFIndexes[i] = 8; 6448 else 6449 PFIndexes[i] = M[i]; 6450 } 6451 6452 // Compute the index in the perfect shuffle table. 6453 unsigned PFTableIndex = 6454 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6455 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6456 unsigned Cost = (PFEntry >> 30); 6457 6458 if (Cost <= 4) 6459 return true; 6460 } 6461 6462 bool ReverseVEXT, isV_UNDEF; 6463 unsigned Imm, WhichResult; 6464 6465 unsigned EltSize = VT.getScalarSizeInBits(); 6466 return (EltSize >= 32 || 6467 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6468 isVREVMask(M, VT, 64) || 6469 isVREVMask(M, VT, 32) || 6470 isVREVMask(M, VT, 16) || 6471 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6472 isVTBLMask(M, VT) || 6473 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6474 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6475 } 6476 6477 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6478 /// the specified operations to build the shuffle. 6479 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6480 SDValue RHS, SelectionDAG &DAG, 6481 const SDLoc &dl) { 6482 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6483 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6484 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6485 6486 enum { 6487 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6488 OP_VREV, 6489 OP_VDUP0, 6490 OP_VDUP1, 6491 OP_VDUP2, 6492 OP_VDUP3, 6493 OP_VEXT1, 6494 OP_VEXT2, 6495 OP_VEXT3, 6496 OP_VUZPL, // VUZP, left result 6497 OP_VUZPR, // VUZP, right result 6498 OP_VZIPL, // VZIP, left result 6499 OP_VZIPR, // VZIP, right result 6500 OP_VTRNL, // VTRN, left result 6501 OP_VTRNR // VTRN, right result 6502 }; 6503 6504 if (OpNum == OP_COPY) { 6505 if (LHSID == (1*9+2)*9+3) return LHS; 6506 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6507 return RHS; 6508 } 6509 6510 SDValue OpLHS, OpRHS; 6511 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6512 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6513 EVT VT = OpLHS.getValueType(); 6514 6515 switch (OpNum) { 6516 default: llvm_unreachable("Unknown shuffle opcode!"); 6517 case OP_VREV: 6518 // VREV divides the vector in half and swaps within the half. 6519 if (VT.getVectorElementType() == MVT::i32 || 6520 VT.getVectorElementType() == MVT::f32) 6521 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6522 // vrev <4 x i16> -> VREV32 6523 if (VT.getVectorElementType() == MVT::i16) 6524 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6525 // vrev <4 x i8> -> VREV16 6526 assert(VT.getVectorElementType() == MVT::i8); 6527 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6528 case OP_VDUP0: 6529 case OP_VDUP1: 6530 case OP_VDUP2: 6531 case OP_VDUP3: 6532 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6533 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6534 case OP_VEXT1: 6535 case OP_VEXT2: 6536 case OP_VEXT3: 6537 return DAG.getNode(ARMISD::VEXT, dl, VT, 6538 OpLHS, OpRHS, 6539 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6540 case OP_VUZPL: 6541 case OP_VUZPR: 6542 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6543 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6544 case OP_VZIPL: 6545 case OP_VZIPR: 6546 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6547 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6548 case OP_VTRNL: 6549 case OP_VTRNR: 6550 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6551 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6552 } 6553 } 6554 6555 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6556 ArrayRef<int> ShuffleMask, 6557 SelectionDAG &DAG) { 6558 // Check to see if we can use the VTBL instruction. 6559 SDValue V1 = Op.getOperand(0); 6560 SDValue V2 = Op.getOperand(1); 6561 SDLoc DL(Op); 6562 6563 SmallVector<SDValue, 8> VTBLMask; 6564 for (ArrayRef<int>::iterator 6565 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6566 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6567 6568 if (V2.getNode()->isUndef()) 6569 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6570 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6571 6572 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6573 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6574 } 6575 6576 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6577 SelectionDAG &DAG) { 6578 SDLoc DL(Op); 6579 SDValue OpLHS = Op.getOperand(0); 6580 EVT VT = OpLHS.getValueType(); 6581 6582 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6583 "Expect an v8i16/v16i8 type"); 6584 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6585 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6586 // extract the first 8 bytes into the top double word and the last 8 bytes 6587 // into the bottom double word. The v8i16 case is similar. 6588 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6589 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6590 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6591 } 6592 6593 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6594 SDValue V1 = Op.getOperand(0); 6595 SDValue V2 = Op.getOperand(1); 6596 SDLoc dl(Op); 6597 EVT VT = Op.getValueType(); 6598 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6599 6600 // Convert shuffles that are directly supported on NEON to target-specific 6601 // DAG nodes, instead of keeping them as shuffles and matching them again 6602 // during code selection. This is more efficient and avoids the possibility 6603 // of inconsistencies between legalization and selection. 6604 // FIXME: floating-point vectors should be canonicalized to integer vectors 6605 // of the same time so that they get CSEd properly. 6606 ArrayRef<int> ShuffleMask = SVN->getMask(); 6607 6608 unsigned EltSize = VT.getScalarSizeInBits(); 6609 if (EltSize <= 32) { 6610 if (SVN->isSplat()) { 6611 int Lane = SVN->getSplatIndex(); 6612 // If this is undef splat, generate it via "just" vdup, if possible. 6613 if (Lane == -1) Lane = 0; 6614 6615 // Test if V1 is a SCALAR_TO_VECTOR. 6616 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6617 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6618 } 6619 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6620 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6621 // reaches it). 6622 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6623 !isa<ConstantSDNode>(V1.getOperand(0))) { 6624 bool IsScalarToVector = true; 6625 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6626 if (!V1.getOperand(i).isUndef()) { 6627 IsScalarToVector = false; 6628 break; 6629 } 6630 if (IsScalarToVector) 6631 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6632 } 6633 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6634 DAG.getConstant(Lane, dl, MVT::i32)); 6635 } 6636 6637 bool ReverseVEXT; 6638 unsigned Imm; 6639 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6640 if (ReverseVEXT) 6641 std::swap(V1, V2); 6642 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6643 DAG.getConstant(Imm, dl, MVT::i32)); 6644 } 6645 6646 if (isVREVMask(ShuffleMask, VT, 64)) 6647 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6648 if (isVREVMask(ShuffleMask, VT, 32)) 6649 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6650 if (isVREVMask(ShuffleMask, VT, 16)) 6651 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6652 6653 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6654 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6655 DAG.getConstant(Imm, dl, MVT::i32)); 6656 } 6657 6658 // Check for Neon shuffles that modify both input vectors in place. 6659 // If both results are used, i.e., if there are two shuffles with the same 6660 // source operands and with masks corresponding to both results of one of 6661 // these operations, DAG memoization will ensure that a single node is 6662 // used for both shuffles. 6663 unsigned WhichResult; 6664 bool isV_UNDEF; 6665 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6666 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6667 if (isV_UNDEF) 6668 V2 = V1; 6669 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6670 .getValue(WhichResult); 6671 } 6672 6673 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6674 // shuffles that produce a result larger than their operands with: 6675 // shuffle(concat(v1, undef), concat(v2, undef)) 6676 // -> 6677 // shuffle(concat(v1, v2), undef) 6678 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6679 // 6680 // This is useful in the general case, but there are special cases where 6681 // native shuffles produce larger results: the two-result ops. 6682 // 6683 // Look through the concat when lowering them: 6684 // shuffle(concat(v1, v2), undef) 6685 // -> 6686 // concat(VZIP(v1, v2):0, :1) 6687 // 6688 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6689 SDValue SubV1 = V1->getOperand(0); 6690 SDValue SubV2 = V1->getOperand(1); 6691 EVT SubVT = SubV1.getValueType(); 6692 6693 // We expect these to have been canonicalized to -1. 6694 assert(llvm::all_of(ShuffleMask, [&](int i) { 6695 return i < (int)VT.getVectorNumElements(); 6696 }) && "Unexpected shuffle index into UNDEF operand!"); 6697 6698 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6699 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6700 if (isV_UNDEF) 6701 SubV2 = SubV1; 6702 assert((WhichResult == 0) && 6703 "In-place shuffle of concat can only have one result!"); 6704 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6705 SubV1, SubV2); 6706 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6707 Res.getValue(1)); 6708 } 6709 } 6710 } 6711 6712 // If the shuffle is not directly supported and it has 4 elements, use 6713 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6714 unsigned NumElts = VT.getVectorNumElements(); 6715 if (NumElts == 4) { 6716 unsigned PFIndexes[4]; 6717 for (unsigned i = 0; i != 4; ++i) { 6718 if (ShuffleMask[i] < 0) 6719 PFIndexes[i] = 8; 6720 else 6721 PFIndexes[i] = ShuffleMask[i]; 6722 } 6723 6724 // Compute the index in the perfect shuffle table. 6725 unsigned PFTableIndex = 6726 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6727 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6728 unsigned Cost = (PFEntry >> 30); 6729 6730 if (Cost <= 4) 6731 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6732 } 6733 6734 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6735 if (EltSize >= 32) { 6736 // Do the expansion with floating-point types, since that is what the VFP 6737 // registers are defined to use, and since i64 is not legal. 6738 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6739 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6740 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6741 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6742 SmallVector<SDValue, 8> Ops; 6743 for (unsigned i = 0; i < NumElts; ++i) { 6744 if (ShuffleMask[i] < 0) 6745 Ops.push_back(DAG.getUNDEF(EltVT)); 6746 else 6747 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6748 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6749 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6750 dl, MVT::i32))); 6751 } 6752 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6753 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6754 } 6755 6756 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6757 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6758 6759 if (VT == MVT::v8i8) 6760 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6761 return NewOp; 6762 6763 return SDValue(); 6764 } 6765 6766 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6767 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6768 SDValue Lane = Op.getOperand(2); 6769 if (!isa<ConstantSDNode>(Lane)) 6770 return SDValue(); 6771 6772 return Op; 6773 } 6774 6775 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6776 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6777 SDValue Lane = Op.getOperand(1); 6778 if (!isa<ConstantSDNode>(Lane)) 6779 return SDValue(); 6780 6781 SDValue Vec = Op.getOperand(0); 6782 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 6783 SDLoc dl(Op); 6784 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6785 } 6786 6787 return Op; 6788 } 6789 6790 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6791 // The only time a CONCAT_VECTORS operation can have legal types is when 6792 // two 64-bit vectors are concatenated to a 128-bit vector. 6793 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6794 "unexpected CONCAT_VECTORS"); 6795 SDLoc dl(Op); 6796 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6797 SDValue Op0 = Op.getOperand(0); 6798 SDValue Op1 = Op.getOperand(1); 6799 if (!Op0.isUndef()) 6800 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6801 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6802 DAG.getIntPtrConstant(0, dl)); 6803 if (!Op1.isUndef()) 6804 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6805 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6806 DAG.getIntPtrConstant(1, dl)); 6807 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6808 } 6809 6810 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6811 /// element has been zero/sign-extended, depending on the isSigned parameter, 6812 /// from an integer type half its size. 6813 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6814 bool isSigned) { 6815 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6816 EVT VT = N->getValueType(0); 6817 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6818 SDNode *BVN = N->getOperand(0).getNode(); 6819 if (BVN->getValueType(0) != MVT::v4i32 || 6820 BVN->getOpcode() != ISD::BUILD_VECTOR) 6821 return false; 6822 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6823 unsigned HiElt = 1 - LoElt; 6824 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6825 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6826 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6827 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6828 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6829 return false; 6830 if (isSigned) { 6831 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6832 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6833 return true; 6834 } else { 6835 if (Hi0->isNullValue() && Hi1->isNullValue()) 6836 return true; 6837 } 6838 return false; 6839 } 6840 6841 if (N->getOpcode() != ISD::BUILD_VECTOR) 6842 return false; 6843 6844 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6845 SDNode *Elt = N->getOperand(i).getNode(); 6846 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6847 unsigned EltSize = VT.getScalarSizeInBits(); 6848 unsigned HalfSize = EltSize / 2; 6849 if (isSigned) { 6850 if (!isIntN(HalfSize, C->getSExtValue())) 6851 return false; 6852 } else { 6853 if (!isUIntN(HalfSize, C->getZExtValue())) 6854 return false; 6855 } 6856 continue; 6857 } 6858 return false; 6859 } 6860 6861 return true; 6862 } 6863 6864 /// isSignExtended - Check if a node is a vector value that is sign-extended 6865 /// or a constant BUILD_VECTOR with sign-extended elements. 6866 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 6867 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 6868 return true; 6869 if (isExtendedBUILD_VECTOR(N, DAG, true)) 6870 return true; 6871 return false; 6872 } 6873 6874 /// isZeroExtended - Check if a node is a vector value that is zero-extended 6875 /// or a constant BUILD_VECTOR with zero-extended elements. 6876 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 6877 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 6878 return true; 6879 if (isExtendedBUILD_VECTOR(N, DAG, false)) 6880 return true; 6881 return false; 6882 } 6883 6884 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 6885 if (OrigVT.getSizeInBits() >= 64) 6886 return OrigVT; 6887 6888 assert(OrigVT.isSimple() && "Expecting a simple value type"); 6889 6890 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 6891 switch (OrigSimpleTy) { 6892 default: llvm_unreachable("Unexpected Vector Type"); 6893 case MVT::v2i8: 6894 case MVT::v2i16: 6895 return MVT::v2i32; 6896 case MVT::v4i8: 6897 return MVT::v4i16; 6898 } 6899 } 6900 6901 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 6902 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 6903 /// We insert the required extension here to get the vector to fill a D register. 6904 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 6905 const EVT &OrigTy, 6906 const EVT &ExtTy, 6907 unsigned ExtOpcode) { 6908 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 6909 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 6910 // 64-bits we need to insert a new extension so that it will be 64-bits. 6911 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 6912 if (OrigTy.getSizeInBits() >= 64) 6913 return N; 6914 6915 // Must extend size to at least 64 bits to be used as an operand for VMULL. 6916 EVT NewVT = getExtensionTo64Bits(OrigTy); 6917 6918 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 6919 } 6920 6921 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 6922 /// does not do any sign/zero extension. If the original vector is less 6923 /// than 64 bits, an appropriate extension will be added after the load to 6924 /// reach a total size of 64 bits. We have to add the extension separately 6925 /// because ARM does not have a sign/zero extending load for vectors. 6926 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 6927 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 6928 6929 // The load already has the right type. 6930 if (ExtendedTy == LD->getMemoryVT()) 6931 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 6932 LD->getBasePtr(), LD->getPointerInfo(), 6933 LD->getAlignment(), LD->getMemOperand()->getFlags()); 6934 6935 // We need to create a zextload/sextload. We cannot just create a load 6936 // followed by a zext/zext node because LowerMUL is also run during normal 6937 // operation legalization where we can't create illegal types. 6938 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 6939 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 6940 LD->getMemoryVT(), LD->getAlignment(), 6941 LD->getMemOperand()->getFlags()); 6942 } 6943 6944 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 6945 /// extending load, or BUILD_VECTOR with extended elements, return the 6946 /// unextended value. The unextended vector should be 64 bits so that it can 6947 /// be used as an operand to a VMULL instruction. If the original vector size 6948 /// before extension is less than 64 bits we add a an extension to resize 6949 /// the vector to 64 bits. 6950 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 6951 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 6952 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 6953 N->getOperand(0)->getValueType(0), 6954 N->getValueType(0), 6955 N->getOpcode()); 6956 6957 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 6958 return SkipLoadExtensionForVMULL(LD, DAG); 6959 6960 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 6961 // have been legalized as a BITCAST from v4i32. 6962 if (N->getOpcode() == ISD::BITCAST) { 6963 SDNode *BVN = N->getOperand(0).getNode(); 6964 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 6965 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 6966 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6967 return DAG.getBuildVector( 6968 MVT::v2i32, SDLoc(N), 6969 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 6970 } 6971 // Construct a new BUILD_VECTOR with elements truncated to half the size. 6972 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 6973 EVT VT = N->getValueType(0); 6974 unsigned EltSize = VT.getScalarSizeInBits() / 2; 6975 unsigned NumElts = VT.getVectorNumElements(); 6976 MVT TruncVT = MVT::getIntegerVT(EltSize); 6977 SmallVector<SDValue, 8> Ops; 6978 SDLoc dl(N); 6979 for (unsigned i = 0; i != NumElts; ++i) { 6980 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 6981 const APInt &CInt = C->getAPIntValue(); 6982 // Element types smaller than 32 bits are not legal, so use i32 elements. 6983 // The values are implicitly truncated so sext vs. zext doesn't matter. 6984 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 6985 } 6986 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 6987 } 6988 6989 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 6990 unsigned Opcode = N->getOpcode(); 6991 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 6992 SDNode *N0 = N->getOperand(0).getNode(); 6993 SDNode *N1 = N->getOperand(1).getNode(); 6994 return N0->hasOneUse() && N1->hasOneUse() && 6995 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 6996 } 6997 return false; 6998 } 6999 7000 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7001 unsigned Opcode = N->getOpcode(); 7002 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7003 SDNode *N0 = N->getOperand(0).getNode(); 7004 SDNode *N1 = N->getOperand(1).getNode(); 7005 return N0->hasOneUse() && N1->hasOneUse() && 7006 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7007 } 7008 return false; 7009 } 7010 7011 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7012 // Multiplications are only custom-lowered for 128-bit vectors so that 7013 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7014 EVT VT = Op.getValueType(); 7015 assert(VT.is128BitVector() && VT.isInteger() && 7016 "unexpected type for custom-lowering ISD::MUL"); 7017 SDNode *N0 = Op.getOperand(0).getNode(); 7018 SDNode *N1 = Op.getOperand(1).getNode(); 7019 unsigned NewOpc = 0; 7020 bool isMLA = false; 7021 bool isN0SExt = isSignExtended(N0, DAG); 7022 bool isN1SExt = isSignExtended(N1, DAG); 7023 if (isN0SExt && isN1SExt) 7024 NewOpc = ARMISD::VMULLs; 7025 else { 7026 bool isN0ZExt = isZeroExtended(N0, DAG); 7027 bool isN1ZExt = isZeroExtended(N1, DAG); 7028 if (isN0ZExt && isN1ZExt) 7029 NewOpc = ARMISD::VMULLu; 7030 else if (isN1SExt || isN1ZExt) { 7031 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7032 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7033 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7034 NewOpc = ARMISD::VMULLs; 7035 isMLA = true; 7036 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7037 NewOpc = ARMISD::VMULLu; 7038 isMLA = true; 7039 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7040 std::swap(N0, N1); 7041 NewOpc = ARMISD::VMULLu; 7042 isMLA = true; 7043 } 7044 } 7045 7046 if (!NewOpc) { 7047 if (VT == MVT::v2i64) 7048 // Fall through to expand this. It is not legal. 7049 return SDValue(); 7050 else 7051 // Other vector multiplications are legal. 7052 return Op; 7053 } 7054 } 7055 7056 // Legalize to a VMULL instruction. 7057 SDLoc DL(Op); 7058 SDValue Op0; 7059 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7060 if (!isMLA) { 7061 Op0 = SkipExtensionForVMULL(N0, DAG); 7062 assert(Op0.getValueType().is64BitVector() && 7063 Op1.getValueType().is64BitVector() && 7064 "unexpected types for extended operands to VMULL"); 7065 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7066 } 7067 7068 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7069 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7070 // vmull q0, d4, d6 7071 // vmlal q0, d5, d6 7072 // is faster than 7073 // vaddl q0, d4, d5 7074 // vmovl q1, d6 7075 // vmul q0, q0, q1 7076 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7077 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7078 EVT Op1VT = Op1.getValueType(); 7079 return DAG.getNode(N0->getOpcode(), DL, VT, 7080 DAG.getNode(NewOpc, DL, VT, 7081 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7082 DAG.getNode(NewOpc, DL, VT, 7083 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7084 } 7085 7086 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7087 SelectionDAG &DAG) { 7088 // TODO: Should this propagate fast-math-flags? 7089 7090 // Convert to float 7091 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7092 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7093 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7094 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7095 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7096 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7097 // Get reciprocal estimate. 7098 // float4 recip = vrecpeq_f32(yf); 7099 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7100 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7101 Y); 7102 // Because char has a smaller range than uchar, we can actually get away 7103 // without any newton steps. This requires that we use a weird bias 7104 // of 0xb000, however (again, this has been exhaustively tested). 7105 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7106 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7107 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7108 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7109 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7110 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7111 // Convert back to short. 7112 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7113 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7114 return X; 7115 } 7116 7117 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7118 SelectionDAG &DAG) { 7119 // TODO: Should this propagate fast-math-flags? 7120 7121 SDValue N2; 7122 // Convert to float. 7123 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7124 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7125 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7126 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7127 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7128 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7129 7130 // Use reciprocal estimate and one refinement step. 7131 // float4 recip = vrecpeq_f32(yf); 7132 // recip *= vrecpsq_f32(yf, recip); 7133 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7134 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7135 N1); 7136 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7137 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7138 N1, N2); 7139 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7140 // Because short has a smaller range than ushort, we can actually get away 7141 // with only a single newton step. This requires that we use a weird bias 7142 // of 89, however (again, this has been exhaustively tested). 7143 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7144 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7145 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7146 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7147 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7148 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7149 // Convert back to integer and return. 7150 // return vmovn_s32(vcvt_s32_f32(result)); 7151 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7152 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7153 return N0; 7154 } 7155 7156 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7157 EVT VT = Op.getValueType(); 7158 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7159 "unexpected type for custom-lowering ISD::SDIV"); 7160 7161 SDLoc dl(Op); 7162 SDValue N0 = Op.getOperand(0); 7163 SDValue N1 = Op.getOperand(1); 7164 SDValue N2, N3; 7165 7166 if (VT == MVT::v8i8) { 7167 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7168 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7169 7170 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7171 DAG.getIntPtrConstant(4, dl)); 7172 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7173 DAG.getIntPtrConstant(4, dl)); 7174 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7175 DAG.getIntPtrConstant(0, dl)); 7176 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7177 DAG.getIntPtrConstant(0, dl)); 7178 7179 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7180 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7181 7182 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7183 N0 = LowerCONCAT_VECTORS(N0, DAG); 7184 7185 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7186 return N0; 7187 } 7188 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7189 } 7190 7191 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7192 // TODO: Should this propagate fast-math-flags? 7193 EVT VT = Op.getValueType(); 7194 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7195 "unexpected type for custom-lowering ISD::UDIV"); 7196 7197 SDLoc dl(Op); 7198 SDValue N0 = Op.getOperand(0); 7199 SDValue N1 = Op.getOperand(1); 7200 SDValue N2, N3; 7201 7202 if (VT == MVT::v8i8) { 7203 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7204 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7205 7206 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7207 DAG.getIntPtrConstant(4, dl)); 7208 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7209 DAG.getIntPtrConstant(4, dl)); 7210 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7211 DAG.getIntPtrConstant(0, dl)); 7212 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7213 DAG.getIntPtrConstant(0, dl)); 7214 7215 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7216 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7217 7218 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7219 N0 = LowerCONCAT_VECTORS(N0, DAG); 7220 7221 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7222 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7223 MVT::i32), 7224 N0); 7225 return N0; 7226 } 7227 7228 // v4i16 sdiv ... Convert to float. 7229 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7230 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7231 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7232 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7233 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7234 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7235 7236 // Use reciprocal estimate and two refinement steps. 7237 // float4 recip = vrecpeq_f32(yf); 7238 // recip *= vrecpsq_f32(yf, recip); 7239 // recip *= vrecpsq_f32(yf, recip); 7240 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7241 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7242 BN1); 7243 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7244 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7245 BN1, N2); 7246 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7247 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7248 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7249 BN1, N2); 7250 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7251 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7252 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7253 // and that it will never cause us to return an answer too large). 7254 // float4 result = as_float4(as_int4(xf*recip) + 2); 7255 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7256 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7257 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7258 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7259 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7260 // Convert back to integer and return. 7261 // return vmovn_u32(vcvt_s32_f32(result)); 7262 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7263 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7264 return N0; 7265 } 7266 7267 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7268 EVT VT = Op.getNode()->getValueType(0); 7269 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7270 7271 unsigned Opc; 7272 bool ExtraOp = false; 7273 switch (Op.getOpcode()) { 7274 default: llvm_unreachable("Invalid code"); 7275 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7276 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7277 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7278 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7279 } 7280 7281 if (!ExtraOp) 7282 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7283 Op.getOperand(1)); 7284 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7285 Op.getOperand(1), Op.getOperand(2)); 7286 } 7287 7288 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7289 assert(Subtarget->isTargetDarwin()); 7290 7291 // For iOS, we want to call an alternative entry point: __sincos_stret, 7292 // return values are passed via sret. 7293 SDLoc dl(Op); 7294 SDValue Arg = Op.getOperand(0); 7295 EVT ArgVT = Arg.getValueType(); 7296 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7297 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7298 7299 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7300 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7301 7302 // Pair of floats / doubles used to pass the result. 7303 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 7304 auto &DL = DAG.getDataLayout(); 7305 7306 ArgListTy Args; 7307 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7308 SDValue SRet; 7309 if (ShouldUseSRet) { 7310 // Create stack object for sret. 7311 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7312 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7313 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7314 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7315 7316 ArgListEntry Entry; 7317 Entry.Node = SRet; 7318 Entry.Ty = RetTy->getPointerTo(); 7319 Entry.isSExt = false; 7320 Entry.isZExt = false; 7321 Entry.isSRet = true; 7322 Args.push_back(Entry); 7323 RetTy = Type::getVoidTy(*DAG.getContext()); 7324 } 7325 7326 ArgListEntry Entry; 7327 Entry.Node = Arg; 7328 Entry.Ty = ArgTy; 7329 Entry.isSExt = false; 7330 Entry.isZExt = false; 7331 Args.push_back(Entry); 7332 7333 const char *LibcallName = 7334 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 7335 RTLIB::Libcall LC = 7336 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 7337 CallingConv::ID CC = getLibcallCallingConv(LC); 7338 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7339 7340 TargetLowering::CallLoweringInfo CLI(DAG); 7341 CLI.setDebugLoc(dl) 7342 .setChain(DAG.getEntryNode()) 7343 .setCallee(CC, RetTy, Callee, std::move(Args)) 7344 .setDiscardResult(ShouldUseSRet); 7345 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7346 7347 if (!ShouldUseSRet) 7348 return CallResult.first; 7349 7350 SDValue LoadSin = 7351 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7352 7353 // Address of cos field. 7354 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7355 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7356 SDValue LoadCos = 7357 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7358 7359 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7360 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7361 LoadSin.getValue(0), LoadCos.getValue(0)); 7362 } 7363 7364 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7365 bool Signed, 7366 SDValue &Chain) const { 7367 EVT VT = Op.getValueType(); 7368 assert((VT == MVT::i32 || VT == MVT::i64) && 7369 "unexpected type for custom lowering DIV"); 7370 SDLoc dl(Op); 7371 7372 const auto &DL = DAG.getDataLayout(); 7373 const auto &TLI = DAG.getTargetLoweringInfo(); 7374 7375 const char *Name = nullptr; 7376 if (Signed) 7377 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7378 else 7379 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7380 7381 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7382 7383 ARMTargetLowering::ArgListTy Args; 7384 7385 for (auto AI : {1, 0}) { 7386 ArgListEntry Arg; 7387 Arg.Node = Op.getOperand(AI); 7388 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7389 Args.push_back(Arg); 7390 } 7391 7392 CallLoweringInfo CLI(DAG); 7393 CLI.setDebugLoc(dl) 7394 .setChain(Chain) 7395 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7396 ES, std::move(Args)); 7397 7398 return LowerCallTo(CLI).first; 7399 } 7400 7401 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7402 bool Signed) const { 7403 assert(Op.getValueType() == MVT::i32 && 7404 "unexpected type for custom lowering DIV"); 7405 SDLoc dl(Op); 7406 7407 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7408 DAG.getEntryNode(), Op.getOperand(1)); 7409 7410 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7411 } 7412 7413 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7414 SDLoc DL(N); 7415 SDValue Op = N->getOperand(1); 7416 if (N->getValueType(0) == MVT::i32) 7417 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7418 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7419 DAG.getConstant(0, DL, MVT::i32)); 7420 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7421 DAG.getConstant(1, DL, MVT::i32)); 7422 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7423 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7424 } 7425 7426 void ARMTargetLowering::ExpandDIV_Windows( 7427 SDValue Op, SelectionDAG &DAG, bool Signed, 7428 SmallVectorImpl<SDValue> &Results) const { 7429 const auto &DL = DAG.getDataLayout(); 7430 const auto &TLI = DAG.getTargetLoweringInfo(); 7431 7432 assert(Op.getValueType() == MVT::i64 && 7433 "unexpected type for custom lowering DIV"); 7434 SDLoc dl(Op); 7435 7436 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7437 7438 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7439 7440 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7441 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7442 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7443 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7444 7445 Results.push_back(Lower); 7446 Results.push_back(Upper); 7447 } 7448 7449 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7450 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7451 // Acquire/Release load/store is not legal for targets without a dmb or 7452 // equivalent available. 7453 return SDValue(); 7454 7455 // Monotonic load/store is legal for all targets. 7456 return Op; 7457 } 7458 7459 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7460 SmallVectorImpl<SDValue> &Results, 7461 SelectionDAG &DAG, 7462 const ARMSubtarget *Subtarget) { 7463 SDLoc DL(N); 7464 // Under Power Management extensions, the cycle-count is: 7465 // mrc p15, #0, <Rt>, c9, c13, #0 7466 SDValue Ops[] = { N->getOperand(0), // Chain 7467 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7468 DAG.getConstant(15, DL, MVT::i32), 7469 DAG.getConstant(0, DL, MVT::i32), 7470 DAG.getConstant(9, DL, MVT::i32), 7471 DAG.getConstant(13, DL, MVT::i32), 7472 DAG.getConstant(0, DL, MVT::i32) 7473 }; 7474 7475 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7476 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7477 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7478 DAG.getConstant(0, DL, MVT::i32))); 7479 Results.push_back(Cycles32.getValue(1)); 7480 } 7481 7482 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7483 SDLoc dl(V.getNode()); 7484 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7485 SDValue VHi = DAG.getAnyExtOrTrunc( 7486 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7487 dl, MVT::i32); 7488 SDValue RegClass = 7489 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7490 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7491 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7492 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7493 return SDValue( 7494 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7495 } 7496 7497 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7498 SmallVectorImpl<SDValue> & Results, 7499 SelectionDAG &DAG) { 7500 assert(N->getValueType(0) == MVT::i64 && 7501 "AtomicCmpSwap on types less than 64 should be legal"); 7502 SDValue Ops[] = {N->getOperand(1), 7503 createGPRPairNode(DAG, N->getOperand(2)), 7504 createGPRPairNode(DAG, N->getOperand(3)), 7505 N->getOperand(0)}; 7506 SDNode *CmpSwap = DAG.getMachineNode( 7507 ARM::CMP_SWAP_64, SDLoc(N), 7508 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7509 7510 MachineFunction &MF = DAG.getMachineFunction(); 7511 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7512 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7513 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7514 7515 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32, 7516 SDValue(CmpSwap, 0))); 7517 Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32, 7518 SDValue(CmpSwap, 0))); 7519 Results.push_back(SDValue(CmpSwap, 2)); 7520 } 7521 7522 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 7523 SelectionDAG &DAG) { 7524 const auto &TLI = DAG.getTargetLoweringInfo(); 7525 7526 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 7527 "Custom lowering is MSVCRT specific!"); 7528 7529 SDLoc dl(Op); 7530 SDValue Val = Op.getOperand(0); 7531 MVT Ty = Val->getSimpleValueType(0); 7532 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 7533 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 7534 TLI.getPointerTy(DAG.getDataLayout())); 7535 7536 TargetLowering::ArgListTy Args; 7537 TargetLowering::ArgListEntry Entry; 7538 7539 Entry.Node = Val; 7540 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7541 Entry.isZExt = true; 7542 Args.push_back(Entry); 7543 7544 Entry.Node = Exponent; 7545 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 7546 Entry.isZExt = true; 7547 Args.push_back(Entry); 7548 7549 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7550 7551 // In the in-chain to the call is the entry node If we are emitting a 7552 // tailcall, the chain will be mutated if the node has a non-entry input 7553 // chain. 7554 SDValue InChain = DAG.getEntryNode(); 7555 SDValue TCChain = InChain; 7556 7557 const auto *F = DAG.getMachineFunction().getFunction(); 7558 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 7559 F->getReturnType() == LCRTy; 7560 if (IsTC) 7561 InChain = TCChain; 7562 7563 TargetLowering::CallLoweringInfo CLI(DAG); 7564 CLI.setDebugLoc(dl) 7565 .setChain(InChain) 7566 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 7567 .setTailCall(IsTC); 7568 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 7569 7570 // Return the chain (the DAG root) if it is a tail call 7571 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 7572 } 7573 7574 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7575 switch (Op.getOpcode()) { 7576 default: llvm_unreachable("Don't know how to custom lower this!"); 7577 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7578 case ISD::ConstantPool: 7579 if (Subtarget->genExecuteOnly()) 7580 llvm_unreachable("execute-only should not generate constant pools"); 7581 return LowerConstantPool(Op, DAG); 7582 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7583 case ISD::GlobalAddress: 7584 switch (Subtarget->getTargetTriple().getObjectFormat()) { 7585 default: llvm_unreachable("unknown object format"); 7586 case Triple::COFF: 7587 return LowerGlobalAddressWindows(Op, DAG); 7588 case Triple::ELF: 7589 return LowerGlobalAddressELF(Op, DAG); 7590 case Triple::MachO: 7591 return LowerGlobalAddressDarwin(Op, DAG); 7592 } 7593 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7594 case ISD::SELECT: return LowerSELECT(Op, DAG); 7595 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7596 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7597 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7598 case ISD::VASTART: return LowerVASTART(Op, DAG); 7599 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7600 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7601 case ISD::SINT_TO_FP: 7602 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7603 case ISD::FP_TO_SINT: 7604 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7605 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7606 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7607 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7608 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7609 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7610 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7611 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7612 Subtarget); 7613 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7614 case ISD::SHL: 7615 case ISD::SRL: 7616 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7617 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7618 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7619 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7620 case ISD::SRL_PARTS: 7621 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7622 case ISD::CTTZ: 7623 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7624 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7625 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7626 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7627 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7628 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7629 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7630 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7631 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7632 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7633 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7634 case ISD::MUL: return LowerMUL(Op, DAG); 7635 case ISD::SDIV: 7636 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7637 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7638 return LowerSDIV(Op, DAG); 7639 case ISD::UDIV: 7640 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7641 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7642 return LowerUDIV(Op, DAG); 7643 case ISD::ADDC: 7644 case ISD::ADDE: 7645 case ISD::SUBC: 7646 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7647 case ISD::SADDO: 7648 case ISD::UADDO: 7649 case ISD::SSUBO: 7650 case ISD::USUBO: 7651 return LowerXALUO(Op, DAG); 7652 case ISD::ATOMIC_LOAD: 7653 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7654 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7655 case ISD::SDIVREM: 7656 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7657 case ISD::DYNAMIC_STACKALLOC: 7658 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7659 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7660 llvm_unreachable("Don't know how to custom lower this!"); 7661 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7662 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7663 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 7664 case ARMISD::WIN__DBZCHK: return SDValue(); 7665 } 7666 } 7667 7668 /// ReplaceNodeResults - Replace the results of node with an illegal result 7669 /// type with new values built out of custom code. 7670 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7671 SmallVectorImpl<SDValue> &Results, 7672 SelectionDAG &DAG) const { 7673 SDValue Res; 7674 switch (N->getOpcode()) { 7675 default: 7676 llvm_unreachable("Don't know how to custom expand this!"); 7677 case ISD::READ_REGISTER: 7678 ExpandREAD_REGISTER(N, Results, DAG); 7679 break; 7680 case ISD::BITCAST: 7681 Res = ExpandBITCAST(N, DAG); 7682 break; 7683 case ISD::SRL: 7684 case ISD::SRA: 7685 Res = Expand64BitShift(N, DAG, Subtarget); 7686 break; 7687 case ISD::SREM: 7688 case ISD::UREM: 7689 Res = LowerREM(N, DAG); 7690 break; 7691 case ISD::SDIVREM: 7692 case ISD::UDIVREM: 7693 Res = LowerDivRem(SDValue(N, 0), DAG); 7694 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7695 Results.push_back(Res.getValue(0)); 7696 Results.push_back(Res.getValue(1)); 7697 return; 7698 case ISD::READCYCLECOUNTER: 7699 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7700 return; 7701 case ISD::UDIV: 7702 case ISD::SDIV: 7703 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7704 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7705 Results); 7706 case ISD::ATOMIC_CMP_SWAP: 7707 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7708 return; 7709 } 7710 if (Res.getNode()) 7711 Results.push_back(Res); 7712 } 7713 7714 //===----------------------------------------------------------------------===// 7715 // ARM Scheduler Hooks 7716 //===----------------------------------------------------------------------===// 7717 7718 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7719 /// registers the function context. 7720 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 7721 MachineBasicBlock *MBB, 7722 MachineBasicBlock *DispatchBB, 7723 int FI) const { 7724 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 7725 "ROPI/RWPI not currently supported with SjLj"); 7726 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7727 DebugLoc dl = MI.getDebugLoc(); 7728 MachineFunction *MF = MBB->getParent(); 7729 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7730 MachineConstantPool *MCP = MF->getConstantPool(); 7731 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7732 const Function *F = MF->getFunction(); 7733 7734 bool isThumb = Subtarget->isThumb(); 7735 bool isThumb2 = Subtarget->isThumb2(); 7736 7737 unsigned PCLabelId = AFI->createPICLabelUId(); 7738 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7739 ARMConstantPoolValue *CPV = 7740 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 7741 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7742 7743 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7744 : &ARM::GPRRegClass; 7745 7746 // Grab constant pool and fixed stack memory operands. 7747 MachineMemOperand *CPMMO = 7748 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7749 MachineMemOperand::MOLoad, 4, 4); 7750 7751 MachineMemOperand *FIMMOSt = 7752 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7753 MachineMemOperand::MOStore, 4, 4); 7754 7755 // Load the address of the dispatch MBB into the jump buffer. 7756 if (isThumb2) { 7757 // Incoming value: jbuf 7758 // ldr.n r5, LCPI1_1 7759 // orr r5, r5, #1 7760 // add r5, pc 7761 // str r5, [$jbuf, #+4] ; &jbuf[1] 7762 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7763 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7764 .addConstantPoolIndex(CPI) 7765 .addMemOperand(CPMMO) 7766 .add(predOps(ARMCC::AL)); 7767 // Set the low bit because of thumb mode. 7768 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7769 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7770 .addReg(NewVReg1, RegState::Kill) 7771 .addImm(0x01) 7772 .add(predOps(ARMCC::AL)) 7773 .add(condCodeOp()); 7774 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7775 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 7776 .addReg(NewVReg2, RegState::Kill) 7777 .addImm(PCLabelId); 7778 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 7779 .addReg(NewVReg3, RegState::Kill) 7780 .addFrameIndex(FI) 7781 .addImm(36) // &jbuf[1] :: pc 7782 .addMemOperand(FIMMOSt) 7783 .add(predOps(ARMCC::AL)); 7784 } else if (isThumb) { 7785 // Incoming value: jbuf 7786 // ldr.n r1, LCPI1_4 7787 // add r1, pc 7788 // mov r2, #1 7789 // orrs r1, r2 7790 // add r2, $jbuf, #+4 ; &jbuf[1] 7791 // str r1, [r2] 7792 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7793 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 7794 .addConstantPoolIndex(CPI) 7795 .addMemOperand(CPMMO) 7796 .add(predOps(ARMCC::AL)); 7797 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7798 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 7799 .addReg(NewVReg1, RegState::Kill) 7800 .addImm(PCLabelId); 7801 // Set the low bit because of thumb mode. 7802 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7803 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 7804 .addReg(ARM::CPSR, RegState::Define) 7805 .addImm(1) 7806 .add(predOps(ARMCC::AL)); 7807 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 7808 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 7809 .addReg(ARM::CPSR, RegState::Define) 7810 .addReg(NewVReg2, RegState::Kill) 7811 .addReg(NewVReg3, RegState::Kill) 7812 .add(predOps(ARMCC::AL)); 7813 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 7814 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 7815 .addFrameIndex(FI) 7816 .addImm(36); // &jbuf[1] :: pc 7817 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 7818 .addReg(NewVReg4, RegState::Kill) 7819 .addReg(NewVReg5, RegState::Kill) 7820 .addImm(0) 7821 .addMemOperand(FIMMOSt) 7822 .add(predOps(ARMCC::AL)); 7823 } else { 7824 // Incoming value: jbuf 7825 // ldr r1, LCPI1_1 7826 // add r1, pc, r1 7827 // str r1, [$jbuf, #+4] ; &jbuf[1] 7828 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7829 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 7830 .addConstantPoolIndex(CPI) 7831 .addImm(0) 7832 .addMemOperand(CPMMO) 7833 .add(predOps(ARMCC::AL)); 7834 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7835 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 7836 .addReg(NewVReg1, RegState::Kill) 7837 .addImm(PCLabelId) 7838 .add(predOps(ARMCC::AL)); 7839 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 7840 .addReg(NewVReg2, RegState::Kill) 7841 .addFrameIndex(FI) 7842 .addImm(36) // &jbuf[1] :: pc 7843 .addMemOperand(FIMMOSt) 7844 .add(predOps(ARMCC::AL)); 7845 } 7846 } 7847 7848 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 7849 MachineBasicBlock *MBB) const { 7850 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7851 DebugLoc dl = MI.getDebugLoc(); 7852 MachineFunction *MF = MBB->getParent(); 7853 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7854 MachineFrameInfo &MFI = MF->getFrameInfo(); 7855 int FI = MFI.getFunctionContextIndex(); 7856 7857 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 7858 : &ARM::GPRnopcRegClass; 7859 7860 // Get a mapping of the call site numbers to all of the landing pads they're 7861 // associated with. 7862 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 7863 unsigned MaxCSNum = 0; 7864 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 7865 ++BB) { 7866 if (!BB->isEHPad()) continue; 7867 7868 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 7869 // pad. 7870 for (MachineBasicBlock::iterator 7871 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 7872 if (!II->isEHLabel()) continue; 7873 7874 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 7875 if (!MF->hasCallSiteLandingPad(Sym)) continue; 7876 7877 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 7878 for (SmallVectorImpl<unsigned>::iterator 7879 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 7880 CSI != CSE; ++CSI) { 7881 CallSiteNumToLPad[*CSI].push_back(&*BB); 7882 MaxCSNum = std::max(MaxCSNum, *CSI); 7883 } 7884 break; 7885 } 7886 } 7887 7888 // Get an ordered list of the machine basic blocks for the jump table. 7889 std::vector<MachineBasicBlock*> LPadList; 7890 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 7891 LPadList.reserve(CallSiteNumToLPad.size()); 7892 for (unsigned I = 1; I <= MaxCSNum; ++I) { 7893 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 7894 for (SmallVectorImpl<MachineBasicBlock*>::iterator 7895 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 7896 LPadList.push_back(*II); 7897 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 7898 } 7899 } 7900 7901 assert(!LPadList.empty() && 7902 "No landing pad destinations for the dispatch jump table!"); 7903 7904 // Create the jump table and associated information. 7905 MachineJumpTableInfo *JTI = 7906 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 7907 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 7908 7909 // Create the MBBs for the dispatch code. 7910 7911 // Shove the dispatch's address into the return slot in the function context. 7912 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 7913 DispatchBB->setIsEHPad(); 7914 7915 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 7916 unsigned trap_opcode; 7917 if (Subtarget->isThumb()) 7918 trap_opcode = ARM::tTRAP; 7919 else 7920 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 7921 7922 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 7923 DispatchBB->addSuccessor(TrapBB); 7924 7925 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 7926 DispatchBB->addSuccessor(DispContBB); 7927 7928 // Insert and MBBs. 7929 MF->insert(MF->end(), DispatchBB); 7930 MF->insert(MF->end(), DispContBB); 7931 MF->insert(MF->end(), TrapBB); 7932 7933 // Insert code into the entry block that creates and registers the function 7934 // context. 7935 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 7936 7937 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 7938 MachinePointerInfo::getFixedStack(*MF, FI), 7939 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 7940 7941 MachineInstrBuilder MIB; 7942 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 7943 7944 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 7945 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 7946 7947 // Add a register mask with no preserved registers. This results in all 7948 // registers being marked as clobbered. This can't work if the dispatch block 7949 // is in a Thumb1 function and is linked with ARM code which uses the FP 7950 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 7951 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 7952 7953 bool IsPositionIndependent = isPositionIndependent(); 7954 unsigned NumLPads = LPadList.size(); 7955 if (Subtarget->isThumb2()) { 7956 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7957 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 7958 .addFrameIndex(FI) 7959 .addImm(4) 7960 .addMemOperand(FIMMOLd) 7961 .add(predOps(ARMCC::AL)); 7962 7963 if (NumLPads < 256) { 7964 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 7965 .addReg(NewVReg1) 7966 .addImm(LPadList.size()) 7967 .add(predOps(ARMCC::AL)); 7968 } else { 7969 unsigned VReg1 = MRI->createVirtualRegister(TRC); 7970 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 7971 .addImm(NumLPads & 0xFFFF) 7972 .add(predOps(ARMCC::AL)); 7973 7974 unsigned VReg2 = VReg1; 7975 if ((NumLPads & 0xFFFF0000) != 0) { 7976 VReg2 = MRI->createVirtualRegister(TRC); 7977 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 7978 .addReg(VReg1) 7979 .addImm(NumLPads >> 16) 7980 .add(predOps(ARMCC::AL)); 7981 } 7982 7983 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 7984 .addReg(NewVReg1) 7985 .addReg(VReg2) 7986 .add(predOps(ARMCC::AL)); 7987 } 7988 7989 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 7990 .addMBB(TrapBB) 7991 .addImm(ARMCC::HI) 7992 .addReg(ARM::CPSR); 7993 7994 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 7995 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 7996 .addJumpTableIndex(MJTI) 7997 .add(predOps(ARMCC::AL)); 7998 7999 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8000 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8001 .addReg(NewVReg3, RegState::Kill) 8002 .addReg(NewVReg1) 8003 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8004 .add(predOps(ARMCC::AL)) 8005 .add(condCodeOp()); 8006 8007 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8008 .addReg(NewVReg4, RegState::Kill) 8009 .addReg(NewVReg1) 8010 .addJumpTableIndex(MJTI); 8011 } else if (Subtarget->isThumb()) { 8012 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8013 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8014 .addFrameIndex(FI) 8015 .addImm(1) 8016 .addMemOperand(FIMMOLd) 8017 .add(predOps(ARMCC::AL)); 8018 8019 if (NumLPads < 256) { 8020 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8021 .addReg(NewVReg1) 8022 .addImm(NumLPads) 8023 .add(predOps(ARMCC::AL)); 8024 } else { 8025 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8026 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8027 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8028 8029 // MachineConstantPool wants an explicit alignment. 8030 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8031 if (Align == 0) 8032 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8033 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8034 8035 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8036 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8037 .addReg(VReg1, RegState::Define) 8038 .addConstantPoolIndex(Idx) 8039 .add(predOps(ARMCC::AL)); 8040 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8041 .addReg(NewVReg1) 8042 .addReg(VReg1) 8043 .add(predOps(ARMCC::AL)); 8044 } 8045 8046 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8047 .addMBB(TrapBB) 8048 .addImm(ARMCC::HI) 8049 .addReg(ARM::CPSR); 8050 8051 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8052 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8053 .addReg(ARM::CPSR, RegState::Define) 8054 .addReg(NewVReg1) 8055 .addImm(2) 8056 .add(predOps(ARMCC::AL)); 8057 8058 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8059 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8060 .addJumpTableIndex(MJTI) 8061 .add(predOps(ARMCC::AL)); 8062 8063 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8064 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8065 .addReg(ARM::CPSR, RegState::Define) 8066 .addReg(NewVReg2, RegState::Kill) 8067 .addReg(NewVReg3) 8068 .add(predOps(ARMCC::AL)); 8069 8070 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8071 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8072 8073 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8074 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8075 .addReg(NewVReg4, RegState::Kill) 8076 .addImm(0) 8077 .addMemOperand(JTMMOLd) 8078 .add(predOps(ARMCC::AL)); 8079 8080 unsigned NewVReg6 = NewVReg5; 8081 if (IsPositionIndependent) { 8082 NewVReg6 = MRI->createVirtualRegister(TRC); 8083 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8084 .addReg(ARM::CPSR, RegState::Define) 8085 .addReg(NewVReg5, RegState::Kill) 8086 .addReg(NewVReg3) 8087 .add(predOps(ARMCC::AL)); 8088 } 8089 8090 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8091 .addReg(NewVReg6, RegState::Kill) 8092 .addJumpTableIndex(MJTI); 8093 } else { 8094 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8095 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8096 .addFrameIndex(FI) 8097 .addImm(4) 8098 .addMemOperand(FIMMOLd) 8099 .add(predOps(ARMCC::AL)); 8100 8101 if (NumLPads < 256) { 8102 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8103 .addReg(NewVReg1) 8104 .addImm(NumLPads) 8105 .add(predOps(ARMCC::AL)); 8106 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8107 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8108 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8109 .addImm(NumLPads & 0xFFFF) 8110 .add(predOps(ARMCC::AL)); 8111 8112 unsigned VReg2 = VReg1; 8113 if ((NumLPads & 0xFFFF0000) != 0) { 8114 VReg2 = MRI->createVirtualRegister(TRC); 8115 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8116 .addReg(VReg1) 8117 .addImm(NumLPads >> 16) 8118 .add(predOps(ARMCC::AL)); 8119 } 8120 8121 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8122 .addReg(NewVReg1) 8123 .addReg(VReg2) 8124 .add(predOps(ARMCC::AL)); 8125 } else { 8126 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8127 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8128 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8129 8130 // MachineConstantPool wants an explicit alignment. 8131 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8132 if (Align == 0) 8133 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8134 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8135 8136 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8137 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8138 .addReg(VReg1, RegState::Define) 8139 .addConstantPoolIndex(Idx) 8140 .addImm(0) 8141 .add(predOps(ARMCC::AL)); 8142 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8143 .addReg(NewVReg1) 8144 .addReg(VReg1, RegState::Kill) 8145 .add(predOps(ARMCC::AL)); 8146 } 8147 8148 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8149 .addMBB(TrapBB) 8150 .addImm(ARMCC::HI) 8151 .addReg(ARM::CPSR); 8152 8153 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8154 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8155 .addReg(NewVReg1) 8156 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8157 .add(predOps(ARMCC::AL)) 8158 .add(condCodeOp()); 8159 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8160 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8161 .addJumpTableIndex(MJTI) 8162 .add(predOps(ARMCC::AL)); 8163 8164 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8165 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8166 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8167 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8168 .addReg(NewVReg3, RegState::Kill) 8169 .addReg(NewVReg4) 8170 .addImm(0) 8171 .addMemOperand(JTMMOLd) 8172 .add(predOps(ARMCC::AL)); 8173 8174 if (IsPositionIndependent) { 8175 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8176 .addReg(NewVReg5, RegState::Kill) 8177 .addReg(NewVReg4) 8178 .addJumpTableIndex(MJTI); 8179 } else { 8180 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8181 .addReg(NewVReg5, RegState::Kill) 8182 .addJumpTableIndex(MJTI); 8183 } 8184 } 8185 8186 // Add the jump table entries as successors to the MBB. 8187 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8188 for (std::vector<MachineBasicBlock*>::iterator 8189 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8190 MachineBasicBlock *CurMBB = *I; 8191 if (SeenMBBs.insert(CurMBB).second) 8192 DispContBB->addSuccessor(CurMBB); 8193 } 8194 8195 // N.B. the order the invoke BBs are processed in doesn't matter here. 8196 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8197 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8198 for (MachineBasicBlock *BB : InvokeBBs) { 8199 8200 // Remove the landing pad successor from the invoke block and replace it 8201 // with the new dispatch block. 8202 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8203 BB->succ_end()); 8204 while (!Successors.empty()) { 8205 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8206 if (SMBB->isEHPad()) { 8207 BB->removeSuccessor(SMBB); 8208 MBBLPads.push_back(SMBB); 8209 } 8210 } 8211 8212 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8213 BB->normalizeSuccProbs(); 8214 8215 // Find the invoke call and mark all of the callee-saved registers as 8216 // 'implicit defined' so that they're spilled. This prevents code from 8217 // moving instructions to before the EH block, where they will never be 8218 // executed. 8219 for (MachineBasicBlock::reverse_iterator 8220 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8221 if (!II->isCall()) continue; 8222 8223 DenseMap<unsigned, bool> DefRegs; 8224 for (MachineInstr::mop_iterator 8225 OI = II->operands_begin(), OE = II->operands_end(); 8226 OI != OE; ++OI) { 8227 if (!OI->isReg()) continue; 8228 DefRegs[OI->getReg()] = true; 8229 } 8230 8231 MachineInstrBuilder MIB(*MF, &*II); 8232 8233 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8234 unsigned Reg = SavedRegs[i]; 8235 if (Subtarget->isThumb2() && 8236 !ARM::tGPRRegClass.contains(Reg) && 8237 !ARM::hGPRRegClass.contains(Reg)) 8238 continue; 8239 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8240 continue; 8241 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8242 continue; 8243 if (!DefRegs[Reg]) 8244 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8245 } 8246 8247 break; 8248 } 8249 } 8250 8251 // Mark all former landing pads as non-landing pads. The dispatch is the only 8252 // landing pad now. 8253 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8254 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8255 (*I)->setIsEHPad(false); 8256 8257 // The instruction is gone now. 8258 MI.eraseFromParent(); 8259 } 8260 8261 static 8262 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8263 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8264 E = MBB->succ_end(); I != E; ++I) 8265 if (*I != Succ) 8266 return *I; 8267 llvm_unreachable("Expecting a BB with two successors!"); 8268 } 8269 8270 /// Return the load opcode for a given load size. If load size >= 8, 8271 /// neon opcode will be returned. 8272 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8273 if (LdSize >= 8) 8274 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8275 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8276 if (IsThumb1) 8277 return LdSize == 4 ? ARM::tLDRi 8278 : LdSize == 2 ? ARM::tLDRHi 8279 : LdSize == 1 ? ARM::tLDRBi : 0; 8280 if (IsThumb2) 8281 return LdSize == 4 ? ARM::t2LDR_POST 8282 : LdSize == 2 ? ARM::t2LDRH_POST 8283 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8284 return LdSize == 4 ? ARM::LDR_POST_IMM 8285 : LdSize == 2 ? ARM::LDRH_POST 8286 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8287 } 8288 8289 /// Return the store opcode for a given store size. If store size >= 8, 8290 /// neon opcode will be returned. 8291 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8292 if (StSize >= 8) 8293 return StSize == 16 ? ARM::VST1q32wb_fixed 8294 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8295 if (IsThumb1) 8296 return StSize == 4 ? ARM::tSTRi 8297 : StSize == 2 ? ARM::tSTRHi 8298 : StSize == 1 ? ARM::tSTRBi : 0; 8299 if (IsThumb2) 8300 return StSize == 4 ? ARM::t2STR_POST 8301 : StSize == 2 ? ARM::t2STRH_POST 8302 : StSize == 1 ? ARM::t2STRB_POST : 0; 8303 return StSize == 4 ? ARM::STR_POST_IMM 8304 : StSize == 2 ? ARM::STRH_POST 8305 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8306 } 8307 8308 /// Emit a post-increment load operation with given size. The instructions 8309 /// will be added to BB at Pos. 8310 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8311 const TargetInstrInfo *TII, const DebugLoc &dl, 8312 unsigned LdSize, unsigned Data, unsigned AddrIn, 8313 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8314 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8315 assert(LdOpc != 0 && "Should have a load opcode"); 8316 if (LdSize >= 8) { 8317 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8318 .addReg(AddrOut, RegState::Define) 8319 .addReg(AddrIn) 8320 .addImm(0) 8321 .add(predOps(ARMCC::AL)); 8322 } else if (IsThumb1) { 8323 // load + update AddrIn 8324 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8325 .addReg(AddrIn) 8326 .addImm(0) 8327 .add(predOps(ARMCC::AL)); 8328 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8329 .add(t1CondCodeOp()) 8330 .addReg(AddrIn) 8331 .addImm(LdSize) 8332 .add(predOps(ARMCC::AL)); 8333 } else if (IsThumb2) { 8334 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8335 .addReg(AddrOut, RegState::Define) 8336 .addReg(AddrIn) 8337 .addImm(LdSize) 8338 .add(predOps(ARMCC::AL)); 8339 } else { // arm 8340 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8341 .addReg(AddrOut, RegState::Define) 8342 .addReg(AddrIn) 8343 .addReg(0) 8344 .addImm(LdSize) 8345 .add(predOps(ARMCC::AL)); 8346 } 8347 } 8348 8349 /// Emit a post-increment store operation with given size. The instructions 8350 /// will be added to BB at Pos. 8351 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8352 const TargetInstrInfo *TII, const DebugLoc &dl, 8353 unsigned StSize, unsigned Data, unsigned AddrIn, 8354 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8355 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8356 assert(StOpc != 0 && "Should have a store opcode"); 8357 if (StSize >= 8) { 8358 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8359 .addReg(AddrIn) 8360 .addImm(0) 8361 .addReg(Data) 8362 .add(predOps(ARMCC::AL)); 8363 } else if (IsThumb1) { 8364 // store + update AddrIn 8365 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8366 .addReg(Data) 8367 .addReg(AddrIn) 8368 .addImm(0) 8369 .add(predOps(ARMCC::AL)); 8370 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8371 .add(t1CondCodeOp()) 8372 .addReg(AddrIn) 8373 .addImm(StSize) 8374 .add(predOps(ARMCC::AL)); 8375 } else if (IsThumb2) { 8376 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8377 .addReg(Data) 8378 .addReg(AddrIn) 8379 .addImm(StSize) 8380 .add(predOps(ARMCC::AL)); 8381 } else { // arm 8382 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8383 .addReg(Data) 8384 .addReg(AddrIn) 8385 .addReg(0) 8386 .addImm(StSize) 8387 .add(predOps(ARMCC::AL)); 8388 } 8389 } 8390 8391 MachineBasicBlock * 8392 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8393 MachineBasicBlock *BB) const { 8394 // This pseudo instruction has 3 operands: dst, src, size 8395 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8396 // Otherwise, we will generate unrolled scalar copies. 8397 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8398 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8399 MachineFunction::iterator It = ++BB->getIterator(); 8400 8401 unsigned dest = MI.getOperand(0).getReg(); 8402 unsigned src = MI.getOperand(1).getReg(); 8403 unsigned SizeVal = MI.getOperand(2).getImm(); 8404 unsigned Align = MI.getOperand(3).getImm(); 8405 DebugLoc dl = MI.getDebugLoc(); 8406 8407 MachineFunction *MF = BB->getParent(); 8408 MachineRegisterInfo &MRI = MF->getRegInfo(); 8409 unsigned UnitSize = 0; 8410 const TargetRegisterClass *TRC = nullptr; 8411 const TargetRegisterClass *VecTRC = nullptr; 8412 8413 bool IsThumb1 = Subtarget->isThumb1Only(); 8414 bool IsThumb2 = Subtarget->isThumb2(); 8415 bool IsThumb = Subtarget->isThumb(); 8416 8417 if (Align & 1) { 8418 UnitSize = 1; 8419 } else if (Align & 2) { 8420 UnitSize = 2; 8421 } else { 8422 // Check whether we can use NEON instructions. 8423 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) && 8424 Subtarget->hasNEON()) { 8425 if ((Align % 16 == 0) && SizeVal >= 16) 8426 UnitSize = 16; 8427 else if ((Align % 8 == 0) && SizeVal >= 8) 8428 UnitSize = 8; 8429 } 8430 // Can't use NEON instructions. 8431 if (UnitSize == 0) 8432 UnitSize = 4; 8433 } 8434 8435 // Select the correct opcode and register class for unit size load/store 8436 bool IsNeon = UnitSize >= 8; 8437 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8438 if (IsNeon) 8439 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8440 : UnitSize == 8 ? &ARM::DPRRegClass 8441 : nullptr; 8442 8443 unsigned BytesLeft = SizeVal % UnitSize; 8444 unsigned LoopSize = SizeVal - BytesLeft; 8445 8446 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8447 // Use LDR and STR to copy. 8448 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8449 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8450 unsigned srcIn = src; 8451 unsigned destIn = dest; 8452 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8453 unsigned srcOut = MRI.createVirtualRegister(TRC); 8454 unsigned destOut = MRI.createVirtualRegister(TRC); 8455 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8456 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8457 IsThumb1, IsThumb2); 8458 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8459 IsThumb1, IsThumb2); 8460 srcIn = srcOut; 8461 destIn = destOut; 8462 } 8463 8464 // Handle the leftover bytes with LDRB and STRB. 8465 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8466 // [destOut] = STRB_POST(scratch, destIn, 1) 8467 for (unsigned i = 0; i < BytesLeft; i++) { 8468 unsigned srcOut = MRI.createVirtualRegister(TRC); 8469 unsigned destOut = MRI.createVirtualRegister(TRC); 8470 unsigned scratch = MRI.createVirtualRegister(TRC); 8471 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8472 IsThumb1, IsThumb2); 8473 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8474 IsThumb1, IsThumb2); 8475 srcIn = srcOut; 8476 destIn = destOut; 8477 } 8478 MI.eraseFromParent(); // The instruction is gone now. 8479 return BB; 8480 } 8481 8482 // Expand the pseudo op to a loop. 8483 // thisMBB: 8484 // ... 8485 // movw varEnd, # --> with thumb2 8486 // movt varEnd, # 8487 // ldrcp varEnd, idx --> without thumb2 8488 // fallthrough --> loopMBB 8489 // loopMBB: 8490 // PHI varPhi, varEnd, varLoop 8491 // PHI srcPhi, src, srcLoop 8492 // PHI destPhi, dst, destLoop 8493 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8494 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8495 // subs varLoop, varPhi, #UnitSize 8496 // bne loopMBB 8497 // fallthrough --> exitMBB 8498 // exitMBB: 8499 // epilogue to handle left-over bytes 8500 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8501 // [destOut] = STRB_POST(scratch, destLoop, 1) 8502 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8503 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8504 MF->insert(It, loopMBB); 8505 MF->insert(It, exitMBB); 8506 8507 // Transfer the remainder of BB and its successor edges to exitMBB. 8508 exitMBB->splice(exitMBB->begin(), BB, 8509 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8510 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8511 8512 // Load an immediate to varEnd. 8513 unsigned varEnd = MRI.createVirtualRegister(TRC); 8514 if (Subtarget->useMovt(*MF)) { 8515 unsigned Vtmp = varEnd; 8516 if ((LoopSize & 0xFFFF0000) != 0) 8517 Vtmp = MRI.createVirtualRegister(TRC); 8518 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 8519 .addImm(LoopSize & 0xFFFF) 8520 .add(predOps(ARMCC::AL)); 8521 8522 if ((LoopSize & 0xFFFF0000) != 0) 8523 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 8524 .addReg(Vtmp) 8525 .addImm(LoopSize >> 16) 8526 .add(predOps(ARMCC::AL)); 8527 } else { 8528 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8529 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 8530 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8531 8532 // MachineConstantPool wants an explicit alignment. 8533 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8534 if (Align == 0) 8535 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8536 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8537 8538 if (IsThumb) 8539 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 8540 .addReg(varEnd, RegState::Define) 8541 .addConstantPoolIndex(Idx) 8542 .add(predOps(ARMCC::AL)); 8543 else 8544 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 8545 .addReg(varEnd, RegState::Define) 8546 .addConstantPoolIndex(Idx) 8547 .addImm(0) 8548 .add(predOps(ARMCC::AL)); 8549 } 8550 BB->addSuccessor(loopMBB); 8551 8552 // Generate the loop body: 8553 // varPhi = PHI(varLoop, varEnd) 8554 // srcPhi = PHI(srcLoop, src) 8555 // destPhi = PHI(destLoop, dst) 8556 MachineBasicBlock *entryBB = BB; 8557 BB = loopMBB; 8558 unsigned varLoop = MRI.createVirtualRegister(TRC); 8559 unsigned varPhi = MRI.createVirtualRegister(TRC); 8560 unsigned srcLoop = MRI.createVirtualRegister(TRC); 8561 unsigned srcPhi = MRI.createVirtualRegister(TRC); 8562 unsigned destLoop = MRI.createVirtualRegister(TRC); 8563 unsigned destPhi = MRI.createVirtualRegister(TRC); 8564 8565 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 8566 .addReg(varLoop).addMBB(loopMBB) 8567 .addReg(varEnd).addMBB(entryBB); 8568 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 8569 .addReg(srcLoop).addMBB(loopMBB) 8570 .addReg(src).addMBB(entryBB); 8571 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 8572 .addReg(destLoop).addMBB(loopMBB) 8573 .addReg(dest).addMBB(entryBB); 8574 8575 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8576 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 8577 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8578 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 8579 IsThumb1, IsThumb2); 8580 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 8581 IsThumb1, IsThumb2); 8582 8583 // Decrement loop variable by UnitSize. 8584 if (IsThumb1) { 8585 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 8586 .add(t1CondCodeOp()) 8587 .addReg(varPhi) 8588 .addImm(UnitSize) 8589 .add(predOps(ARMCC::AL)); 8590 } else { 8591 MachineInstrBuilder MIB = 8592 BuildMI(*BB, BB->end(), dl, 8593 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 8594 MIB.addReg(varPhi) 8595 .addImm(UnitSize) 8596 .add(predOps(ARMCC::AL)) 8597 .add(condCodeOp()); 8598 MIB->getOperand(5).setReg(ARM::CPSR); 8599 MIB->getOperand(5).setIsDef(true); 8600 } 8601 BuildMI(*BB, BB->end(), dl, 8602 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8603 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 8604 8605 // loopMBB can loop back to loopMBB or fall through to exitMBB. 8606 BB->addSuccessor(loopMBB); 8607 BB->addSuccessor(exitMBB); 8608 8609 // Add epilogue to handle BytesLeft. 8610 BB = exitMBB; 8611 auto StartOfExit = exitMBB->begin(); 8612 8613 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8614 // [destOut] = STRB_POST(scratch, destLoop, 1) 8615 unsigned srcIn = srcLoop; 8616 unsigned destIn = destLoop; 8617 for (unsigned i = 0; i < BytesLeft; i++) { 8618 unsigned srcOut = MRI.createVirtualRegister(TRC); 8619 unsigned destOut = MRI.createVirtualRegister(TRC); 8620 unsigned scratch = MRI.createVirtualRegister(TRC); 8621 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 8622 IsThumb1, IsThumb2); 8623 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8624 IsThumb1, IsThumb2); 8625 srcIn = srcOut; 8626 destIn = destOut; 8627 } 8628 8629 MI.eraseFromParent(); // The instruction is gone now. 8630 return BB; 8631 } 8632 8633 MachineBasicBlock * 8634 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 8635 MachineBasicBlock *MBB) const { 8636 const TargetMachine &TM = getTargetMachine(); 8637 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8638 DebugLoc DL = MI.getDebugLoc(); 8639 8640 assert(Subtarget->isTargetWindows() && 8641 "__chkstk is only supported on Windows"); 8642 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8643 8644 // __chkstk takes the number of words to allocate on the stack in R4, and 8645 // returns the stack adjustment in number of bytes in R4. This will not 8646 // clober any other registers (other than the obvious lr). 8647 // 8648 // Although, technically, IP should be considered a register which may be 8649 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8650 // thumb-2 environment, so there is no interworking required. As a result, we 8651 // do not expect a veneer to be emitted by the linker, clobbering IP. 8652 // 8653 // Each module receives its own copy of __chkstk, so no import thunk is 8654 // required, again, ensuring that IP is not clobbered. 8655 // 8656 // Finally, although some linkers may theoretically provide a trampoline for 8657 // out of range calls (which is quite common due to a 32M range limitation of 8658 // branches for Thumb), we can generate the long-call version via 8659 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8660 // IP. 8661 8662 switch (TM.getCodeModel()) { 8663 case CodeModel::Small: 8664 case CodeModel::Medium: 8665 case CodeModel::Default: 8666 case CodeModel::Kernel: 8667 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8668 .add(predOps(ARMCC::AL)) 8669 .addExternalSymbol("__chkstk") 8670 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8671 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8672 .addReg(ARM::R12, 8673 RegState::Implicit | RegState::Define | RegState::Dead); 8674 break; 8675 case CodeModel::Large: 8676 case CodeModel::JITDefault: { 8677 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8678 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8679 8680 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8681 .addExternalSymbol("__chkstk"); 8682 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8683 .add(predOps(ARMCC::AL)) 8684 .addReg(Reg, RegState::Kill) 8685 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8686 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8687 .addReg(ARM::R12, 8688 RegState::Implicit | RegState::Define | RegState::Dead); 8689 break; 8690 } 8691 } 8692 8693 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 8694 .addReg(ARM::SP, RegState::Kill) 8695 .addReg(ARM::R4, RegState::Kill) 8696 .setMIFlags(MachineInstr::FrameSetup) 8697 .add(predOps(ARMCC::AL)) 8698 .add(condCodeOp()); 8699 8700 MI.eraseFromParent(); 8701 return MBB; 8702 } 8703 8704 MachineBasicBlock * 8705 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 8706 MachineBasicBlock *MBB) const { 8707 DebugLoc DL = MI.getDebugLoc(); 8708 MachineFunction *MF = MBB->getParent(); 8709 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8710 8711 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8712 MF->insert(++MBB->getIterator(), ContBB); 8713 ContBB->splice(ContBB->begin(), MBB, 8714 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8715 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8716 MBB->addSuccessor(ContBB); 8717 8718 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8719 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 8720 MF->push_back(TrapBB); 8721 MBB->addSuccessor(TrapBB); 8722 8723 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 8724 .addReg(MI.getOperand(0).getReg()) 8725 .addImm(0) 8726 .add(predOps(ARMCC::AL)); 8727 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 8728 .addMBB(TrapBB) 8729 .addImm(ARMCC::EQ) 8730 .addReg(ARM::CPSR); 8731 8732 MI.eraseFromParent(); 8733 return ContBB; 8734 } 8735 8736 MachineBasicBlock * 8737 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8738 MachineBasicBlock *BB) const { 8739 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8740 DebugLoc dl = MI.getDebugLoc(); 8741 bool isThumb2 = Subtarget->isThumb2(); 8742 switch (MI.getOpcode()) { 8743 default: { 8744 MI.print(errs()); 8745 llvm_unreachable("Unexpected instr type to insert"); 8746 } 8747 8748 // Thumb1 post-indexed loads are really just single-register LDMs. 8749 case ARM::tLDR_postidx: { 8750 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 8751 .add(MI.getOperand(1)) // Rn_wb 8752 .add(MI.getOperand(2)) // Rn 8753 .add(MI.getOperand(3)) // PredImm 8754 .add(MI.getOperand(4)) // PredReg 8755 .add(MI.getOperand(0)); // Rt 8756 MI.eraseFromParent(); 8757 return BB; 8758 } 8759 8760 // The Thumb2 pre-indexed stores have the same MI operands, they just 8761 // define them differently in the .td files from the isel patterns, so 8762 // they need pseudos. 8763 case ARM::t2STR_preidx: 8764 MI.setDesc(TII->get(ARM::t2STR_PRE)); 8765 return BB; 8766 case ARM::t2STRB_preidx: 8767 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 8768 return BB; 8769 case ARM::t2STRH_preidx: 8770 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 8771 return BB; 8772 8773 case ARM::STRi_preidx: 8774 case ARM::STRBi_preidx: { 8775 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 8776 : ARM::STRB_PRE_IMM; 8777 // Decode the offset. 8778 unsigned Offset = MI.getOperand(4).getImm(); 8779 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 8780 Offset = ARM_AM::getAM2Offset(Offset); 8781 if (isSub) 8782 Offset = -Offset; 8783 8784 MachineMemOperand *MMO = *MI.memoperands_begin(); 8785 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 8786 .add(MI.getOperand(0)) // Rn_wb 8787 .add(MI.getOperand(1)) // Rt 8788 .add(MI.getOperand(2)) // Rn 8789 .addImm(Offset) // offset (skip GPR==zero_reg) 8790 .add(MI.getOperand(5)) // pred 8791 .add(MI.getOperand(6)) 8792 .addMemOperand(MMO); 8793 MI.eraseFromParent(); 8794 return BB; 8795 } 8796 case ARM::STRr_preidx: 8797 case ARM::STRBr_preidx: 8798 case ARM::STRH_preidx: { 8799 unsigned NewOpc; 8800 switch (MI.getOpcode()) { 8801 default: llvm_unreachable("unexpected opcode!"); 8802 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 8803 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 8804 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 8805 } 8806 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 8807 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 8808 MIB.add(MI.getOperand(i)); 8809 MI.eraseFromParent(); 8810 return BB; 8811 } 8812 8813 case ARM::tMOVCCr_pseudo: { 8814 // To "insert" a SELECT_CC instruction, we actually have to insert the 8815 // diamond control-flow pattern. The incoming instruction knows the 8816 // destination vreg to set, the condition code register to branch on, the 8817 // true/false values to select between, and a branch opcode to use. 8818 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8819 MachineFunction::iterator It = ++BB->getIterator(); 8820 8821 // thisMBB: 8822 // ... 8823 // TrueVal = ... 8824 // cmpTY ccX, r1, r2 8825 // bCC copy1MBB 8826 // fallthrough --> copy0MBB 8827 MachineBasicBlock *thisMBB = BB; 8828 MachineFunction *F = BB->getParent(); 8829 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 8830 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 8831 F->insert(It, copy0MBB); 8832 F->insert(It, sinkMBB); 8833 8834 // Transfer the remainder of BB and its successor edges to sinkMBB. 8835 sinkMBB->splice(sinkMBB->begin(), BB, 8836 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8837 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 8838 8839 BB->addSuccessor(copy0MBB); 8840 BB->addSuccessor(sinkMBB); 8841 8842 BuildMI(BB, dl, TII->get(ARM::tBcc)) 8843 .addMBB(sinkMBB) 8844 .addImm(MI.getOperand(3).getImm()) 8845 .addReg(MI.getOperand(4).getReg()); 8846 8847 // copy0MBB: 8848 // %FalseValue = ... 8849 // # fallthrough to sinkMBB 8850 BB = copy0MBB; 8851 8852 // Update machine-CFG edges 8853 BB->addSuccessor(sinkMBB); 8854 8855 // sinkMBB: 8856 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 8857 // ... 8858 BB = sinkMBB; 8859 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 8860 .addReg(MI.getOperand(1).getReg()) 8861 .addMBB(copy0MBB) 8862 .addReg(MI.getOperand(2).getReg()) 8863 .addMBB(thisMBB); 8864 8865 MI.eraseFromParent(); // The pseudo instruction is gone now. 8866 return BB; 8867 } 8868 8869 case ARM::BCCi64: 8870 case ARM::BCCZi64: { 8871 // If there is an unconditional branch to the other successor, remove it. 8872 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8873 8874 // Compare both parts that make up the double comparison separately for 8875 // equality. 8876 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 8877 8878 unsigned LHS1 = MI.getOperand(1).getReg(); 8879 unsigned LHS2 = MI.getOperand(2).getReg(); 8880 if (RHSisZero) { 8881 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8882 .addReg(LHS1) 8883 .addImm(0) 8884 .add(predOps(ARMCC::AL)); 8885 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8886 .addReg(LHS2).addImm(0) 8887 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8888 } else { 8889 unsigned RHS1 = MI.getOperand(3).getReg(); 8890 unsigned RHS2 = MI.getOperand(4).getReg(); 8891 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8892 .addReg(LHS1) 8893 .addReg(RHS1) 8894 .add(predOps(ARMCC::AL)); 8895 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 8896 .addReg(LHS2).addReg(RHS2) 8897 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 8898 } 8899 8900 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 8901 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 8902 if (MI.getOperand(0).getImm() == ARMCC::NE) 8903 std::swap(destMBB, exitMBB); 8904 8905 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8906 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 8907 if (isThumb2) 8908 BuildMI(BB, dl, TII->get(ARM::t2B)) 8909 .addMBB(exitMBB) 8910 .add(predOps(ARMCC::AL)); 8911 else 8912 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 8913 8914 MI.eraseFromParent(); // The pseudo instruction is gone now. 8915 return BB; 8916 } 8917 8918 case ARM::Int_eh_sjlj_setjmp: 8919 case ARM::Int_eh_sjlj_setjmp_nofp: 8920 case ARM::tInt_eh_sjlj_setjmp: 8921 case ARM::t2Int_eh_sjlj_setjmp: 8922 case ARM::t2Int_eh_sjlj_setjmp_nofp: 8923 return BB; 8924 8925 case ARM::Int_eh_sjlj_setup_dispatch: 8926 EmitSjLjDispatchBlock(MI, BB); 8927 return BB; 8928 8929 case ARM::ABS: 8930 case ARM::t2ABS: { 8931 // To insert an ABS instruction, we have to insert the 8932 // diamond control-flow pattern. The incoming instruction knows the 8933 // source vreg to test against 0, the destination vreg to set, 8934 // the condition code register to branch on, the 8935 // true/false values to select between, and a branch opcode to use. 8936 // It transforms 8937 // V1 = ABS V0 8938 // into 8939 // V2 = MOVS V0 8940 // BCC (branch to SinkBB if V0 >= 0) 8941 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 8942 // SinkBB: V1 = PHI(V2, V3) 8943 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8944 MachineFunction::iterator BBI = ++BB->getIterator(); 8945 MachineFunction *Fn = BB->getParent(); 8946 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8947 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 8948 Fn->insert(BBI, RSBBB); 8949 Fn->insert(BBI, SinkBB); 8950 8951 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 8952 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 8953 bool ABSSrcKIll = MI.getOperand(1).isKill(); 8954 bool isThumb2 = Subtarget->isThumb2(); 8955 MachineRegisterInfo &MRI = Fn->getRegInfo(); 8956 // In Thumb mode S must not be specified if source register is the SP or 8957 // PC and if destination register is the SP, so restrict register class 8958 unsigned NewRsbDstReg = 8959 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 8960 8961 // Transfer the remainder of BB and its successor edges to sinkMBB. 8962 SinkBB->splice(SinkBB->begin(), BB, 8963 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8964 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 8965 8966 BB->addSuccessor(RSBBB); 8967 BB->addSuccessor(SinkBB); 8968 8969 // fall through to SinkMBB 8970 RSBBB->addSuccessor(SinkBB); 8971 8972 // insert a cmp at the end of BB 8973 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 8974 .addReg(ABSSrcReg) 8975 .addImm(0) 8976 .add(predOps(ARMCC::AL)); 8977 8978 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 8979 BuildMI(BB, dl, 8980 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 8981 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 8982 8983 // insert rsbri in RSBBB 8984 // Note: BCC and rsbri will be converted into predicated rsbmi 8985 // by if-conversion pass 8986 BuildMI(*RSBBB, RSBBB->begin(), dl, 8987 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 8988 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 8989 .addImm(0) 8990 .add(predOps(ARMCC::AL)) 8991 .add(condCodeOp()); 8992 8993 // insert PHI in SinkBB, 8994 // reuse ABSDstReg to not change uses of ABS instruction 8995 BuildMI(*SinkBB, SinkBB->begin(), dl, 8996 TII->get(ARM::PHI), ABSDstReg) 8997 .addReg(NewRsbDstReg).addMBB(RSBBB) 8998 .addReg(ABSSrcReg).addMBB(BB); 8999 9000 // remove ABS instruction 9001 MI.eraseFromParent(); 9002 9003 // return last added BB 9004 return SinkBB; 9005 } 9006 case ARM::COPY_STRUCT_BYVAL_I32: 9007 ++NumLoopByVals; 9008 return EmitStructByval(MI, BB); 9009 case ARM::WIN__CHKSTK: 9010 return EmitLowered__chkstk(MI, BB); 9011 case ARM::WIN__DBZCHK: 9012 return EmitLowered__dbzchk(MI, BB); 9013 } 9014 } 9015 9016 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 9017 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9018 /// instead of as a custom inserter because we need the use list from the SDNode. 9019 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9020 MachineInstr &MI, const SDNode *Node) { 9021 bool isThumb1 = Subtarget->isThumb1Only(); 9022 9023 DebugLoc DL = MI.getDebugLoc(); 9024 MachineFunction *MF = MI.getParent()->getParent(); 9025 MachineRegisterInfo &MRI = MF->getRegInfo(); 9026 MachineInstrBuilder MIB(*MF, MI); 9027 9028 // If the new dst/src is unused mark it as dead. 9029 if (!Node->hasAnyUseOfValue(0)) { 9030 MI.getOperand(0).setIsDead(true); 9031 } 9032 if (!Node->hasAnyUseOfValue(1)) { 9033 MI.getOperand(1).setIsDead(true); 9034 } 9035 9036 // The MEMCPY both defines and kills the scratch registers. 9037 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9038 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9039 : &ARM::GPRRegClass); 9040 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9041 } 9042 } 9043 9044 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9045 SDNode *Node) const { 9046 if (MI.getOpcode() == ARM::MEMCPY) { 9047 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9048 return; 9049 } 9050 9051 const MCInstrDesc *MCID = &MI.getDesc(); 9052 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9053 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9054 // operand is still set to noreg. If needed, set the optional operand's 9055 // register to CPSR, and remove the redundant implicit def. 9056 // 9057 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 9058 9059 // Rename pseudo opcodes. 9060 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9061 if (NewOpc) { 9062 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9063 MCID = &TII->get(NewOpc); 9064 9065 assert(MCID->getNumOperands() == MI.getDesc().getNumOperands() + 1 && 9066 "converted opcode should be the same except for cc_out"); 9067 9068 MI.setDesc(*MCID); 9069 9070 // Add the optional cc_out operand 9071 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9072 } 9073 unsigned ccOutIdx = MCID->getNumOperands() - 1; 9074 9075 // Any ARM instruction that sets the 's' bit should specify an optional 9076 // "cc_out" operand in the last operand position. 9077 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9078 assert(!NewOpc && "Optional cc_out operand required"); 9079 return; 9080 } 9081 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9082 // since we already have an optional CPSR def. 9083 bool definesCPSR = false; 9084 bool deadCPSR = false; 9085 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9086 ++i) { 9087 const MachineOperand &MO = MI.getOperand(i); 9088 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9089 definesCPSR = true; 9090 if (MO.isDead()) 9091 deadCPSR = true; 9092 MI.RemoveOperand(i); 9093 break; 9094 } 9095 } 9096 if (!definesCPSR) { 9097 assert(!NewOpc && "Optional cc_out operand required"); 9098 return; 9099 } 9100 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9101 if (deadCPSR) { 9102 assert(!MI.getOperand(ccOutIdx).getReg() && 9103 "expect uninitialized optional cc_out operand"); 9104 return; 9105 } 9106 9107 // If this instruction was defined with an optional CPSR def and its dag node 9108 // had a live implicit CPSR def, then activate the optional CPSR def. 9109 MachineOperand &MO = MI.getOperand(ccOutIdx); 9110 MO.setReg(ARM::CPSR); 9111 MO.setIsDef(true); 9112 } 9113 9114 //===----------------------------------------------------------------------===// 9115 // ARM Optimization Hooks 9116 //===----------------------------------------------------------------------===// 9117 9118 // Helper function that checks if N is a null or all ones constant. 9119 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9120 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9121 } 9122 9123 // Return true if N is conditionally 0 or all ones. 9124 // Detects these expressions where cc is an i1 value: 9125 // 9126 // (select cc 0, y) [AllOnes=0] 9127 // (select cc y, 0) [AllOnes=0] 9128 // (zext cc) [AllOnes=0] 9129 // (sext cc) [AllOnes=0/1] 9130 // (select cc -1, y) [AllOnes=1] 9131 // (select cc y, -1) [AllOnes=1] 9132 // 9133 // Invert is set when N is the null/all ones constant when CC is false. 9134 // OtherOp is set to the alternative value of N. 9135 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9136 SDValue &CC, bool &Invert, 9137 SDValue &OtherOp, 9138 SelectionDAG &DAG) { 9139 switch (N->getOpcode()) { 9140 default: return false; 9141 case ISD::SELECT: { 9142 CC = N->getOperand(0); 9143 SDValue N1 = N->getOperand(1); 9144 SDValue N2 = N->getOperand(2); 9145 if (isZeroOrAllOnes(N1, AllOnes)) { 9146 Invert = false; 9147 OtherOp = N2; 9148 return true; 9149 } 9150 if (isZeroOrAllOnes(N2, AllOnes)) { 9151 Invert = true; 9152 OtherOp = N1; 9153 return true; 9154 } 9155 return false; 9156 } 9157 case ISD::ZERO_EXTEND: 9158 // (zext cc) can never be the all ones value. 9159 if (AllOnes) 9160 return false; 9161 LLVM_FALLTHROUGH; 9162 case ISD::SIGN_EXTEND: { 9163 SDLoc dl(N); 9164 EVT VT = N->getValueType(0); 9165 CC = N->getOperand(0); 9166 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9167 return false; 9168 Invert = !AllOnes; 9169 if (AllOnes) 9170 // When looking for an AllOnes constant, N is an sext, and the 'other' 9171 // value is 0. 9172 OtherOp = DAG.getConstant(0, dl, VT); 9173 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9174 // When looking for a 0 constant, N can be zext or sext. 9175 OtherOp = DAG.getConstant(1, dl, VT); 9176 else 9177 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9178 VT); 9179 return true; 9180 } 9181 } 9182 } 9183 9184 // Combine a constant select operand into its use: 9185 // 9186 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9187 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9188 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9189 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9190 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9191 // 9192 // The transform is rejected if the select doesn't have a constant operand that 9193 // is null, or all ones when AllOnes is set. 9194 // 9195 // Also recognize sext/zext from i1: 9196 // 9197 // (add (zext cc), x) -> (select cc (add x, 1), x) 9198 // (add (sext cc), x) -> (select cc (add x, -1), x) 9199 // 9200 // These transformations eventually create predicated instructions. 9201 // 9202 // @param N The node to transform. 9203 // @param Slct The N operand that is a select. 9204 // @param OtherOp The other N operand (x above). 9205 // @param DCI Context. 9206 // @param AllOnes Require the select constant to be all ones instead of null. 9207 // @returns The new node, or SDValue() on failure. 9208 static 9209 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9210 TargetLowering::DAGCombinerInfo &DCI, 9211 bool AllOnes = false) { 9212 SelectionDAG &DAG = DCI.DAG; 9213 EVT VT = N->getValueType(0); 9214 SDValue NonConstantVal; 9215 SDValue CCOp; 9216 bool SwapSelectOps; 9217 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9218 NonConstantVal, DAG)) 9219 return SDValue(); 9220 9221 // Slct is now know to be the desired identity constant when CC is true. 9222 SDValue TrueVal = OtherOp; 9223 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9224 OtherOp, NonConstantVal); 9225 // Unless SwapSelectOps says CC should be false. 9226 if (SwapSelectOps) 9227 std::swap(TrueVal, FalseVal); 9228 9229 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9230 CCOp, TrueVal, FalseVal); 9231 } 9232 9233 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9234 static 9235 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9236 TargetLowering::DAGCombinerInfo &DCI) { 9237 SDValue N0 = N->getOperand(0); 9238 SDValue N1 = N->getOperand(1); 9239 if (N0.getNode()->hasOneUse()) 9240 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9241 return Result; 9242 if (N1.getNode()->hasOneUse()) 9243 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9244 return Result; 9245 return SDValue(); 9246 } 9247 9248 static bool IsVUZPShuffleNode(SDNode *N) { 9249 // VUZP shuffle node. 9250 if (N->getOpcode() == ARMISD::VUZP) 9251 return true; 9252 9253 // "VUZP" on i32 is an alias for VTRN. 9254 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9255 return true; 9256 9257 return false; 9258 } 9259 9260 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9261 TargetLowering::DAGCombinerInfo &DCI, 9262 const ARMSubtarget *Subtarget) { 9263 // Look for ADD(VUZP.0, VUZP.1). 9264 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9265 N0 == N1) 9266 return SDValue(); 9267 9268 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9269 if (!N->getValueType(0).is64BitVector()) 9270 return SDValue(); 9271 9272 // Generate vpadd. 9273 SelectionDAG &DAG = DCI.DAG; 9274 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9275 SDLoc dl(N); 9276 SDNode *Unzip = N0.getNode(); 9277 EVT VT = N->getValueType(0); 9278 9279 SmallVector<SDValue, 8> Ops; 9280 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9281 TLI.getPointerTy(DAG.getDataLayout()))); 9282 Ops.push_back(Unzip->getOperand(0)); 9283 Ops.push_back(Unzip->getOperand(1)); 9284 9285 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9286 } 9287 9288 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9289 TargetLowering::DAGCombinerInfo &DCI, 9290 const ARMSubtarget *Subtarget) { 9291 // Check for two extended operands. 9292 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9293 N1.getOpcode() == ISD::SIGN_EXTEND) && 9294 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9295 N1.getOpcode() == ISD::ZERO_EXTEND)) 9296 return SDValue(); 9297 9298 SDValue N00 = N0.getOperand(0); 9299 SDValue N10 = N1.getOperand(0); 9300 9301 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9302 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9303 N00 == N10) 9304 return SDValue(); 9305 9306 // We only recognize Q register paddl here; this can't be reached until 9307 // after type legalization. 9308 if (!N00.getValueType().is64BitVector() || 9309 !N0.getValueType().is128BitVector()) 9310 return SDValue(); 9311 9312 // Generate vpaddl. 9313 SelectionDAG &DAG = DCI.DAG; 9314 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9315 SDLoc dl(N); 9316 EVT VT = N->getValueType(0); 9317 9318 SmallVector<SDValue, 8> Ops; 9319 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9320 unsigned Opcode; 9321 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9322 Opcode = Intrinsic::arm_neon_vpaddls; 9323 else 9324 Opcode = Intrinsic::arm_neon_vpaddlu; 9325 Ops.push_back(DAG.getConstant(Opcode, dl, 9326 TLI.getPointerTy(DAG.getDataLayout()))); 9327 EVT ElemTy = N00.getValueType().getVectorElementType(); 9328 unsigned NumElts = VT.getVectorNumElements(); 9329 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9330 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9331 N00.getOperand(0), N00.getOperand(1)); 9332 Ops.push_back(Concat); 9333 9334 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9335 } 9336 9337 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9338 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9339 // much easier to match. 9340 static SDValue 9341 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9342 TargetLowering::DAGCombinerInfo &DCI, 9343 const ARMSubtarget *Subtarget) { 9344 // Only perform optimization if after legalize, and if NEON is available. We 9345 // also expected both operands to be BUILD_VECTORs. 9346 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9347 || N0.getOpcode() != ISD::BUILD_VECTOR 9348 || N1.getOpcode() != ISD::BUILD_VECTOR) 9349 return SDValue(); 9350 9351 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9352 EVT VT = N->getValueType(0); 9353 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9354 return SDValue(); 9355 9356 // Check that the vector operands are of the right form. 9357 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9358 // operands, where N is the size of the formed vector. 9359 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9360 // index such that we have a pair wise add pattern. 9361 9362 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9363 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9364 return SDValue(); 9365 SDValue Vec = N0->getOperand(0)->getOperand(0); 9366 SDNode *V = Vec.getNode(); 9367 unsigned nextIndex = 0; 9368 9369 // For each operands to the ADD which are BUILD_VECTORs, 9370 // check to see if each of their operands are an EXTRACT_VECTOR with 9371 // the same vector and appropriate index. 9372 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9373 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9374 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9375 9376 SDValue ExtVec0 = N0->getOperand(i); 9377 SDValue ExtVec1 = N1->getOperand(i); 9378 9379 // First operand is the vector, verify its the same. 9380 if (V != ExtVec0->getOperand(0).getNode() || 9381 V != ExtVec1->getOperand(0).getNode()) 9382 return SDValue(); 9383 9384 // Second is the constant, verify its correct. 9385 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9386 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9387 9388 // For the constant, we want to see all the even or all the odd. 9389 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9390 || C1->getZExtValue() != nextIndex+1) 9391 return SDValue(); 9392 9393 // Increment index. 9394 nextIndex+=2; 9395 } else 9396 return SDValue(); 9397 } 9398 9399 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. 9400 if (Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9401 return SDValue(); 9402 9403 // Create VPADDL node. 9404 SelectionDAG &DAG = DCI.DAG; 9405 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9406 9407 SDLoc dl(N); 9408 9409 // Build operand list. 9410 SmallVector<SDValue, 8> Ops; 9411 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9412 TLI.getPointerTy(DAG.getDataLayout()))); 9413 9414 // Input is the vector. 9415 Ops.push_back(Vec); 9416 9417 // Get widened type and narrowed type. 9418 MVT widenType; 9419 unsigned numElem = VT.getVectorNumElements(); 9420 9421 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9422 switch (inputLaneType.getSimpleVT().SimpleTy) { 9423 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9424 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9425 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9426 default: 9427 llvm_unreachable("Invalid vector element type for padd optimization."); 9428 } 9429 9430 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9431 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9432 return DAG.getNode(ExtOp, dl, VT, tmp); 9433 } 9434 9435 static SDValue findMUL_LOHI(SDValue V) { 9436 if (V->getOpcode() == ISD::UMUL_LOHI || 9437 V->getOpcode() == ISD::SMUL_LOHI) 9438 return V; 9439 return SDValue(); 9440 } 9441 9442 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 9443 TargetLowering::DAGCombinerInfo &DCI, 9444 const ARMSubtarget *Subtarget) { 9445 // Look for multiply add opportunities. 9446 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 9447 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 9448 // a glue link from the first add to the second add. 9449 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 9450 // a S/UMLAL instruction. 9451 // UMUL_LOHI 9452 // / :lo \ :hi 9453 // / \ [no multiline comment] 9454 // loAdd -> ADDE | 9455 // \ :glue / 9456 // \ / 9457 // ADDC <- hiAdd 9458 // 9459 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 9460 SDValue AddcOp0 = AddcNode->getOperand(0); 9461 SDValue AddcOp1 = AddcNode->getOperand(1); 9462 9463 // Check if the two operands are from the same mul_lohi node. 9464 if (AddcOp0.getNode() == AddcOp1.getNode()) 9465 return SDValue(); 9466 9467 assert(AddcNode->getNumValues() == 2 && 9468 AddcNode->getValueType(0) == MVT::i32 && 9469 "Expect ADDC with two result values. First: i32"); 9470 9471 // Check that we have a glued ADDC node. 9472 if (AddcNode->getValueType(1) != MVT::Glue) 9473 return SDValue(); 9474 9475 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 9476 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 9477 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 9478 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 9479 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 9480 return SDValue(); 9481 9482 // Look for the glued ADDE. 9483 SDNode* AddeNode = AddcNode->getGluedUser(); 9484 if (!AddeNode) 9485 return SDValue(); 9486 9487 // Make sure it is really an ADDE. 9488 if (AddeNode->getOpcode() != ISD::ADDE) 9489 return SDValue(); 9490 9491 assert(AddeNode->getNumOperands() == 3 && 9492 AddeNode->getOperand(2).getValueType() == MVT::Glue && 9493 "ADDE node has the wrong inputs"); 9494 9495 // Check for the triangle shape. 9496 SDValue AddeOp0 = AddeNode->getOperand(0); 9497 SDValue AddeOp1 = AddeNode->getOperand(1); 9498 9499 // Make sure that the ADDE operands are not coming from the same node. 9500 if (AddeOp0.getNode() == AddeOp1.getNode()) 9501 return SDValue(); 9502 9503 // Find the MUL_LOHI node walking up ADDE's operands. 9504 bool IsLeftOperandMUL = false; 9505 SDValue MULOp = findMUL_LOHI(AddeOp0); 9506 if (MULOp == SDValue()) 9507 MULOp = findMUL_LOHI(AddeOp1); 9508 else 9509 IsLeftOperandMUL = true; 9510 if (MULOp == SDValue()) 9511 return SDValue(); 9512 9513 // Figure out the right opcode. 9514 unsigned Opc = MULOp->getOpcode(); 9515 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 9516 9517 // Figure out the high and low input values to the MLAL node. 9518 SDValue* HiAdd = nullptr; 9519 SDValue* LoMul = nullptr; 9520 SDValue* LowAdd = nullptr; 9521 9522 // Ensure that ADDE is from high result of ISD::SMUL_LOHI. 9523 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 9524 return SDValue(); 9525 9526 if (IsLeftOperandMUL) 9527 HiAdd = &AddeOp1; 9528 else 9529 HiAdd = &AddeOp0; 9530 9531 9532 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 9533 // whose low result is fed to the ADDC we are checking. 9534 9535 if (AddcOp0 == MULOp.getValue(0)) { 9536 LoMul = &AddcOp0; 9537 LowAdd = &AddcOp1; 9538 } 9539 if (AddcOp1 == MULOp.getValue(0)) { 9540 LoMul = &AddcOp1; 9541 LowAdd = &AddcOp0; 9542 } 9543 9544 if (!LoMul) 9545 return SDValue(); 9546 9547 // Create the merged node. 9548 SelectionDAG &DAG = DCI.DAG; 9549 9550 // Build operand list. 9551 SmallVector<SDValue, 8> Ops; 9552 Ops.push_back(LoMul->getOperand(0)); 9553 Ops.push_back(LoMul->getOperand(1)); 9554 Ops.push_back(*LowAdd); 9555 Ops.push_back(*HiAdd); 9556 9557 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 9558 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9559 9560 // Replace the ADDs' nodes uses by the MLA node's values. 9561 SDValue HiMLALResult(MLALNode.getNode(), 1); 9562 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9563 9564 SDValue LoMLALResult(MLALNode.getNode(), 0); 9565 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9566 9567 // Return original node to notify the driver to stop replacing. 9568 SDValue resNode(AddcNode, 0); 9569 return resNode; 9570 } 9571 9572 static SDValue AddCombineTo64bitUMAAL(SDNode *AddcNode, 9573 TargetLowering::DAGCombinerInfo &DCI, 9574 const ARMSubtarget *Subtarget) { 9575 // UMAAL is similar to UMLAL except that it adds two unsigned values. 9576 // While trying to combine for the other MLAL nodes, first search for the 9577 // chance to use UMAAL. Check if Addc uses another addc node which can first 9578 // be combined into a UMLAL. The other pattern is AddcNode being combined 9579 // into an UMLAL and then using another addc is handled in ISelDAGToDAG. 9580 9581 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP() || 9582 (Subtarget->isThumb() && !Subtarget->hasThumb2())) 9583 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9584 9585 SDNode *PrevAddc = nullptr; 9586 if (AddcNode->getOperand(0).getOpcode() == ISD::ADDC) 9587 PrevAddc = AddcNode->getOperand(0).getNode(); 9588 else if (AddcNode->getOperand(1).getOpcode() == ISD::ADDC) 9589 PrevAddc = AddcNode->getOperand(1).getNode(); 9590 9591 // If there's no addc chains, just return a search for any MLAL. 9592 if (PrevAddc == nullptr) 9593 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9594 9595 // Try to convert the addc operand to an MLAL and if that fails try to 9596 // combine AddcNode. 9597 SDValue MLAL = AddCombineTo64bitMLAL(PrevAddc, DCI, Subtarget); 9598 if (MLAL != SDValue(PrevAddc, 0)) 9599 return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget); 9600 9601 // Find the converted UMAAL or quit if it doesn't exist. 9602 SDNode *UmlalNode = nullptr; 9603 SDValue AddHi; 9604 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 9605 UmlalNode = AddcNode->getOperand(0).getNode(); 9606 AddHi = AddcNode->getOperand(1); 9607 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 9608 UmlalNode = AddcNode->getOperand(1).getNode(); 9609 AddHi = AddcNode->getOperand(0); 9610 } else { 9611 return SDValue(); 9612 } 9613 9614 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 9615 // the ADDC as well as Zero. 9616 auto *Zero = dyn_cast<ConstantSDNode>(UmlalNode->getOperand(3)); 9617 9618 if (!Zero || Zero->getZExtValue() != 0) 9619 return SDValue(); 9620 9621 // Check that we have a glued ADDC node. 9622 if (AddcNode->getValueType(1) != MVT::Glue) 9623 return SDValue(); 9624 9625 // Look for the glued ADDE. 9626 SDNode* AddeNode = AddcNode->getGluedUser(); 9627 if (!AddeNode) 9628 return SDValue(); 9629 9630 if ((AddeNode->getOperand(0).getNode() == Zero && 9631 AddeNode->getOperand(1).getNode() == UmlalNode) || 9632 (AddeNode->getOperand(0).getNode() == UmlalNode && 9633 AddeNode->getOperand(1).getNode() == Zero)) { 9634 9635 SelectionDAG &DAG = DCI.DAG; 9636 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 9637 UmlalNode->getOperand(2), AddHi }; 9638 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 9639 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9640 9641 // Replace the ADDs' nodes uses by the UMAAL node's values. 9642 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 9643 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 9644 9645 // Return original node to notify the driver to stop replacing. 9646 return SDValue(AddcNode, 0); 9647 } 9648 return SDValue(); 9649 } 9650 9651 /// PerformADDCCombine - Target-specific dag combine transform from 9652 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL or 9653 /// ISD::ADDC, ISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 9654 static SDValue PerformADDCCombine(SDNode *N, 9655 TargetLowering::DAGCombinerInfo &DCI, 9656 const ARMSubtarget *Subtarget) { 9657 if (Subtarget->isThumb1Only()) return SDValue(); 9658 9659 // Only perform the checks after legalize when the pattern is available. 9660 if (DCI.isBeforeLegalize()) return SDValue(); 9661 9662 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 9663 } 9664 9665 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 9666 /// operands N0 and N1. This is a helper for PerformADDCombine that is 9667 /// called with the default operands, and if that fails, with commuted 9668 /// operands. 9669 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 9670 TargetLowering::DAGCombinerInfo &DCI, 9671 const ARMSubtarget *Subtarget){ 9672 // Attempt to create vpadd for this add. 9673 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 9674 return Result; 9675 9676 // Attempt to create vpaddl for this add. 9677 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 9678 return Result; 9679 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 9680 Subtarget)) 9681 return Result; 9682 9683 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9684 if (N0.getNode()->hasOneUse()) 9685 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 9686 return Result; 9687 return SDValue(); 9688 } 9689 9690 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 9691 /// 9692 static SDValue PerformADDCombine(SDNode *N, 9693 TargetLowering::DAGCombinerInfo &DCI, 9694 const ARMSubtarget *Subtarget) { 9695 SDValue N0 = N->getOperand(0); 9696 SDValue N1 = N->getOperand(1); 9697 9698 // First try with the default operand order. 9699 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 9700 return Result; 9701 9702 // If that didn't work, try again with the operands commuted. 9703 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 9704 } 9705 9706 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 9707 /// 9708 static SDValue PerformSUBCombine(SDNode *N, 9709 TargetLowering::DAGCombinerInfo &DCI) { 9710 SDValue N0 = N->getOperand(0); 9711 SDValue N1 = N->getOperand(1); 9712 9713 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9714 if (N1.getNode()->hasOneUse()) 9715 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 9716 return Result; 9717 9718 return SDValue(); 9719 } 9720 9721 /// PerformVMULCombine 9722 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 9723 /// special multiplier accumulator forwarding. 9724 /// vmul d3, d0, d2 9725 /// vmla d3, d1, d2 9726 /// is faster than 9727 /// vadd d3, d0, d1 9728 /// vmul d3, d3, d2 9729 // However, for (A + B) * (A + B), 9730 // vadd d2, d0, d1 9731 // vmul d3, d0, d2 9732 // vmla d3, d1, d2 9733 // is slower than 9734 // vadd d2, d0, d1 9735 // vmul d3, d2, d2 9736 static SDValue PerformVMULCombine(SDNode *N, 9737 TargetLowering::DAGCombinerInfo &DCI, 9738 const ARMSubtarget *Subtarget) { 9739 if (!Subtarget->hasVMLxForwarding()) 9740 return SDValue(); 9741 9742 SelectionDAG &DAG = DCI.DAG; 9743 SDValue N0 = N->getOperand(0); 9744 SDValue N1 = N->getOperand(1); 9745 unsigned Opcode = N0.getOpcode(); 9746 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9747 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 9748 Opcode = N1.getOpcode(); 9749 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 9750 Opcode != ISD::FADD && Opcode != ISD::FSUB) 9751 return SDValue(); 9752 std::swap(N0, N1); 9753 } 9754 9755 if (N0 == N1) 9756 return SDValue(); 9757 9758 EVT VT = N->getValueType(0); 9759 SDLoc DL(N); 9760 SDValue N00 = N0->getOperand(0); 9761 SDValue N01 = N0->getOperand(1); 9762 return DAG.getNode(Opcode, DL, VT, 9763 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 9764 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 9765 } 9766 9767 static SDValue PerformMULCombine(SDNode *N, 9768 TargetLowering::DAGCombinerInfo &DCI, 9769 const ARMSubtarget *Subtarget) { 9770 SelectionDAG &DAG = DCI.DAG; 9771 9772 if (Subtarget->isThumb1Only()) 9773 return SDValue(); 9774 9775 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9776 return SDValue(); 9777 9778 EVT VT = N->getValueType(0); 9779 if (VT.is64BitVector() || VT.is128BitVector()) 9780 return PerformVMULCombine(N, DCI, Subtarget); 9781 if (VT != MVT::i32) 9782 return SDValue(); 9783 9784 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9785 if (!C) 9786 return SDValue(); 9787 9788 int64_t MulAmt = C->getSExtValue(); 9789 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 9790 9791 ShiftAmt = ShiftAmt & (32 - 1); 9792 SDValue V = N->getOperand(0); 9793 SDLoc DL(N); 9794 9795 SDValue Res; 9796 MulAmt >>= ShiftAmt; 9797 9798 if (MulAmt >= 0) { 9799 if (isPowerOf2_32(MulAmt - 1)) { 9800 // (mul x, 2^N + 1) => (add (shl x, N), x) 9801 Res = DAG.getNode(ISD::ADD, DL, VT, 9802 V, 9803 DAG.getNode(ISD::SHL, DL, VT, 9804 V, 9805 DAG.getConstant(Log2_32(MulAmt - 1), DL, 9806 MVT::i32))); 9807 } else if (isPowerOf2_32(MulAmt + 1)) { 9808 // (mul x, 2^N - 1) => (sub (shl x, N), x) 9809 Res = DAG.getNode(ISD::SUB, DL, VT, 9810 DAG.getNode(ISD::SHL, DL, VT, 9811 V, 9812 DAG.getConstant(Log2_32(MulAmt + 1), DL, 9813 MVT::i32)), 9814 V); 9815 } else 9816 return SDValue(); 9817 } else { 9818 uint64_t MulAmtAbs = -MulAmt; 9819 if (isPowerOf2_32(MulAmtAbs + 1)) { 9820 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 9821 Res = DAG.getNode(ISD::SUB, DL, VT, 9822 V, 9823 DAG.getNode(ISD::SHL, DL, VT, 9824 V, 9825 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 9826 MVT::i32))); 9827 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 9828 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 9829 Res = DAG.getNode(ISD::ADD, DL, VT, 9830 V, 9831 DAG.getNode(ISD::SHL, DL, VT, 9832 V, 9833 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 9834 MVT::i32))); 9835 Res = DAG.getNode(ISD::SUB, DL, VT, 9836 DAG.getConstant(0, DL, MVT::i32), Res); 9837 9838 } else 9839 return SDValue(); 9840 } 9841 9842 if (ShiftAmt != 0) 9843 Res = DAG.getNode(ISD::SHL, DL, VT, 9844 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 9845 9846 // Do not add new nodes to DAG combiner worklist. 9847 DCI.CombineTo(N, Res, false); 9848 return SDValue(); 9849 } 9850 9851 static SDValue PerformANDCombine(SDNode *N, 9852 TargetLowering::DAGCombinerInfo &DCI, 9853 const ARMSubtarget *Subtarget) { 9854 // Attempt to use immediate-form VBIC 9855 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9856 SDLoc dl(N); 9857 EVT VT = N->getValueType(0); 9858 SelectionDAG &DAG = DCI.DAG; 9859 9860 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9861 return SDValue(); 9862 9863 APInt SplatBits, SplatUndef; 9864 unsigned SplatBitSize; 9865 bool HasAnyUndefs; 9866 if (BVN && 9867 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9868 if (SplatBitSize <= 64) { 9869 EVT VbicVT; 9870 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 9871 SplatUndef.getZExtValue(), SplatBitSize, 9872 DAG, dl, VbicVT, VT.is128BitVector(), 9873 OtherModImm); 9874 if (Val.getNode()) { 9875 SDValue Input = 9876 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 9877 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 9878 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 9879 } 9880 } 9881 } 9882 9883 if (!Subtarget->isThumb1Only()) { 9884 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 9885 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 9886 return Result; 9887 } 9888 9889 return SDValue(); 9890 } 9891 9892 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 9893 static SDValue PerformORCombine(SDNode *N, 9894 TargetLowering::DAGCombinerInfo &DCI, 9895 const ARMSubtarget *Subtarget) { 9896 // Attempt to use immediate-form VORR 9897 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 9898 SDLoc dl(N); 9899 EVT VT = N->getValueType(0); 9900 SelectionDAG &DAG = DCI.DAG; 9901 9902 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9903 return SDValue(); 9904 9905 APInt SplatBits, SplatUndef; 9906 unsigned SplatBitSize; 9907 bool HasAnyUndefs; 9908 if (BVN && Subtarget->hasNEON() && 9909 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 9910 if (SplatBitSize <= 64) { 9911 EVT VorrVT; 9912 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 9913 SplatUndef.getZExtValue(), SplatBitSize, 9914 DAG, dl, VorrVT, VT.is128BitVector(), 9915 OtherModImm); 9916 if (Val.getNode()) { 9917 SDValue Input = 9918 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 9919 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 9920 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 9921 } 9922 } 9923 } 9924 9925 if (!Subtarget->isThumb1Only()) { 9926 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9927 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 9928 return Result; 9929 } 9930 9931 // The code below optimizes (or (and X, Y), Z). 9932 // The AND operand needs to have a single user to make these optimizations 9933 // profitable. 9934 SDValue N0 = N->getOperand(0); 9935 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 9936 return SDValue(); 9937 SDValue N1 = N->getOperand(1); 9938 9939 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 9940 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 9941 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 9942 APInt SplatUndef; 9943 unsigned SplatBitSize; 9944 bool HasAnyUndefs; 9945 9946 APInt SplatBits0, SplatBits1; 9947 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 9948 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 9949 // Ensure that the second operand of both ands are constants 9950 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 9951 HasAnyUndefs) && !HasAnyUndefs) { 9952 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 9953 HasAnyUndefs) && !HasAnyUndefs) { 9954 // Ensure that the bit width of the constants are the same and that 9955 // the splat arguments are logical inverses as per the pattern we 9956 // are trying to simplify. 9957 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 9958 SplatBits0 == ~SplatBits1) { 9959 // Canonicalize the vector type to make instruction selection 9960 // simpler. 9961 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 9962 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 9963 N0->getOperand(1), 9964 N0->getOperand(0), 9965 N1->getOperand(0)); 9966 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9967 } 9968 } 9969 } 9970 } 9971 9972 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 9973 // reasonable. 9974 9975 // BFI is only available on V6T2+ 9976 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 9977 return SDValue(); 9978 9979 SDLoc DL(N); 9980 // 1) or (and A, mask), val => ARMbfi A, val, mask 9981 // iff (val & mask) == val 9982 // 9983 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 9984 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 9985 // && mask == ~mask2 9986 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 9987 // && ~mask == mask2 9988 // (i.e., copy a bitfield value into another bitfield of the same width) 9989 9990 if (VT != MVT::i32) 9991 return SDValue(); 9992 9993 SDValue N00 = N0.getOperand(0); 9994 9995 // The value and the mask need to be constants so we can verify this is 9996 // actually a bitfield set. If the mask is 0xffff, we can do better 9997 // via a movt instruction, so don't use BFI in that case. 9998 SDValue MaskOp = N0.getOperand(1); 9999 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10000 if (!MaskC) 10001 return SDValue(); 10002 unsigned Mask = MaskC->getZExtValue(); 10003 if (Mask == 0xffff) 10004 return SDValue(); 10005 SDValue Res; 10006 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10007 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10008 if (N1C) { 10009 unsigned Val = N1C->getZExtValue(); 10010 if ((Val & ~Mask) != Val) 10011 return SDValue(); 10012 10013 if (ARM::isBitFieldInvertedMask(Mask)) { 10014 Val >>= countTrailingZeros(~Mask); 10015 10016 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10017 DAG.getConstant(Val, DL, MVT::i32), 10018 DAG.getConstant(Mask, DL, MVT::i32)); 10019 10020 // Do not add new nodes to DAG combiner worklist. 10021 DCI.CombineTo(N, Res, false); 10022 return SDValue(); 10023 } 10024 } else if (N1.getOpcode() == ISD::AND) { 10025 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10026 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10027 if (!N11C) 10028 return SDValue(); 10029 unsigned Mask2 = N11C->getZExtValue(); 10030 10031 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10032 // as is to match. 10033 if (ARM::isBitFieldInvertedMask(Mask) && 10034 (Mask == ~Mask2)) { 10035 // The pack halfword instruction works better for masks that fit it, 10036 // so use that when it's available. 10037 if (Subtarget->hasDSP() && 10038 (Mask == 0xffff || Mask == 0xffff0000)) 10039 return SDValue(); 10040 // 2a 10041 unsigned amt = countTrailingZeros(Mask2); 10042 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10043 DAG.getConstant(amt, DL, MVT::i32)); 10044 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10045 DAG.getConstant(Mask, DL, MVT::i32)); 10046 // Do not add new nodes to DAG combiner worklist. 10047 DCI.CombineTo(N, Res, false); 10048 return SDValue(); 10049 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10050 (~Mask == Mask2)) { 10051 // The pack halfword instruction works better for masks that fit it, 10052 // so use that when it's available. 10053 if (Subtarget->hasDSP() && 10054 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10055 return SDValue(); 10056 // 2b 10057 unsigned lsb = countTrailingZeros(Mask); 10058 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10059 DAG.getConstant(lsb, DL, MVT::i32)); 10060 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10061 DAG.getConstant(Mask2, DL, MVT::i32)); 10062 // Do not add new nodes to DAG combiner worklist. 10063 DCI.CombineTo(N, Res, false); 10064 return SDValue(); 10065 } 10066 } 10067 10068 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10069 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10070 ARM::isBitFieldInvertedMask(~Mask)) { 10071 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10072 // where lsb(mask) == #shamt and masked bits of B are known zero. 10073 SDValue ShAmt = N00.getOperand(1); 10074 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10075 unsigned LSB = countTrailingZeros(Mask); 10076 if (ShAmtC != LSB) 10077 return SDValue(); 10078 10079 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10080 DAG.getConstant(~Mask, DL, MVT::i32)); 10081 10082 // Do not add new nodes to DAG combiner worklist. 10083 DCI.CombineTo(N, Res, false); 10084 } 10085 10086 return SDValue(); 10087 } 10088 10089 static SDValue PerformXORCombine(SDNode *N, 10090 TargetLowering::DAGCombinerInfo &DCI, 10091 const ARMSubtarget *Subtarget) { 10092 EVT VT = N->getValueType(0); 10093 SelectionDAG &DAG = DCI.DAG; 10094 10095 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10096 return SDValue(); 10097 10098 if (!Subtarget->isThumb1Only()) { 10099 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10100 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10101 return Result; 10102 } 10103 10104 return SDValue(); 10105 } 10106 10107 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 10108 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 10109 // their position in "to" (Rd). 10110 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 10111 assert(N->getOpcode() == ARMISD::BFI); 10112 10113 SDValue From = N->getOperand(1); 10114 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 10115 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 10116 10117 // If the Base came from a SHR #C, we can deduce that it is really testing bit 10118 // #C in the base of the SHR. 10119 if (From->getOpcode() == ISD::SRL && 10120 isa<ConstantSDNode>(From->getOperand(1))) { 10121 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 10122 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 10123 FromMask <<= Shift.getLimitedValue(31); 10124 From = From->getOperand(0); 10125 } 10126 10127 return From; 10128 } 10129 10130 // If A and B contain one contiguous set of bits, does A | B == A . B? 10131 // 10132 // Neither A nor B must be zero. 10133 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 10134 unsigned LastActiveBitInA = A.countTrailingZeros(); 10135 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 10136 return LastActiveBitInA - 1 == FirstActiveBitInB; 10137 } 10138 10139 static SDValue FindBFIToCombineWith(SDNode *N) { 10140 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 10141 // if one exists. 10142 APInt ToMask, FromMask; 10143 SDValue From = ParseBFI(N, ToMask, FromMask); 10144 SDValue To = N->getOperand(0); 10145 10146 // Now check for a compatible BFI to merge with. We can pass through BFIs that 10147 // aren't compatible, but not if they set the same bit in their destination as 10148 // we do (or that of any BFI we're going to combine with). 10149 SDValue V = To; 10150 APInt CombinedToMask = ToMask; 10151 while (V.getOpcode() == ARMISD::BFI) { 10152 APInt NewToMask, NewFromMask; 10153 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 10154 if (NewFrom != From) { 10155 // This BFI has a different base. Keep going. 10156 CombinedToMask |= NewToMask; 10157 V = V.getOperand(0); 10158 continue; 10159 } 10160 10161 // Do the written bits conflict with any we've seen so far? 10162 if ((NewToMask & CombinedToMask).getBoolValue()) 10163 // Conflicting bits - bail out because going further is unsafe. 10164 return SDValue(); 10165 10166 // Are the new bits contiguous when combined with the old bits? 10167 if (BitsProperlyConcatenate(ToMask, NewToMask) && 10168 BitsProperlyConcatenate(FromMask, NewFromMask)) 10169 return V; 10170 if (BitsProperlyConcatenate(NewToMask, ToMask) && 10171 BitsProperlyConcatenate(NewFromMask, FromMask)) 10172 return V; 10173 10174 // We've seen a write to some bits, so track it. 10175 CombinedToMask |= NewToMask; 10176 // Keep going... 10177 V = V.getOperand(0); 10178 } 10179 10180 return SDValue(); 10181 } 10182 10183 static SDValue PerformBFICombine(SDNode *N, 10184 TargetLowering::DAGCombinerInfo &DCI) { 10185 SDValue N1 = N->getOperand(1); 10186 if (N1.getOpcode() == ISD::AND) { 10187 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 10188 // the bits being cleared by the AND are not demanded by the BFI. 10189 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10190 if (!N11C) 10191 return SDValue(); 10192 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 10193 unsigned LSB = countTrailingZeros(~InvMask); 10194 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 10195 assert(Width < 10196 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 10197 "undefined behavior"); 10198 unsigned Mask = (1u << Width) - 1; 10199 unsigned Mask2 = N11C->getZExtValue(); 10200 if ((Mask & (~Mask2)) == 0) 10201 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 10202 N->getOperand(0), N1.getOperand(0), 10203 N->getOperand(2)); 10204 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 10205 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 10206 // Keep track of any consecutive bits set that all come from the same base 10207 // value. We can combine these together into a single BFI. 10208 SDValue CombineBFI = FindBFIToCombineWith(N); 10209 if (CombineBFI == SDValue()) 10210 return SDValue(); 10211 10212 // We've found a BFI. 10213 APInt ToMask1, FromMask1; 10214 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 10215 10216 APInt ToMask2, FromMask2; 10217 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 10218 assert(From1 == From2); 10219 (void)From2; 10220 10221 // First, unlink CombineBFI. 10222 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 10223 // Then create a new BFI, combining the two together. 10224 APInt NewFromMask = FromMask1 | FromMask2; 10225 APInt NewToMask = ToMask1 | ToMask2; 10226 10227 EVT VT = N->getValueType(0); 10228 SDLoc dl(N); 10229 10230 if (NewFromMask[0] == 0) 10231 From1 = DCI.DAG.getNode( 10232 ISD::SRL, dl, VT, From1, 10233 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 10234 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 10235 DCI.DAG.getConstant(~NewToMask, dl, VT)); 10236 } 10237 return SDValue(); 10238 } 10239 10240 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 10241 /// ARMISD::VMOVRRD. 10242 static SDValue PerformVMOVRRDCombine(SDNode *N, 10243 TargetLowering::DAGCombinerInfo &DCI, 10244 const ARMSubtarget *Subtarget) { 10245 // vmovrrd(vmovdrr x, y) -> x,y 10246 SDValue InDouble = N->getOperand(0); 10247 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 10248 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 10249 10250 // vmovrrd(load f64) -> (load i32), (load i32) 10251 SDNode *InNode = InDouble.getNode(); 10252 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 10253 InNode->getValueType(0) == MVT::f64 && 10254 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 10255 !cast<LoadSDNode>(InNode)->isVolatile()) { 10256 // TODO: Should this be done for non-FrameIndex operands? 10257 LoadSDNode *LD = cast<LoadSDNode>(InNode); 10258 10259 SelectionDAG &DAG = DCI.DAG; 10260 SDLoc DL(LD); 10261 SDValue BasePtr = LD->getBasePtr(); 10262 SDValue NewLD1 = 10263 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 10264 LD->getAlignment(), LD->getMemOperand()->getFlags()); 10265 10266 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10267 DAG.getConstant(4, DL, MVT::i32)); 10268 SDValue NewLD2 = DAG.getLoad( 10269 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 10270 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 10271 10272 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 10273 if (DCI.DAG.getDataLayout().isBigEndian()) 10274 std::swap (NewLD1, NewLD2); 10275 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 10276 return Result; 10277 } 10278 10279 return SDValue(); 10280 } 10281 10282 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 10283 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 10284 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 10285 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 10286 SDValue Op0 = N->getOperand(0); 10287 SDValue Op1 = N->getOperand(1); 10288 if (Op0.getOpcode() == ISD::BITCAST) 10289 Op0 = Op0.getOperand(0); 10290 if (Op1.getOpcode() == ISD::BITCAST) 10291 Op1 = Op1.getOperand(0); 10292 if (Op0.getOpcode() == ARMISD::VMOVRRD && 10293 Op0.getNode() == Op1.getNode() && 10294 Op0.getResNo() == 0 && Op1.getResNo() == 1) 10295 return DAG.getNode(ISD::BITCAST, SDLoc(N), 10296 N->getValueType(0), Op0.getOperand(0)); 10297 return SDValue(); 10298 } 10299 10300 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 10301 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 10302 /// i64 vector to have f64 elements, since the value can then be loaded 10303 /// directly into a VFP register. 10304 static bool hasNormalLoadOperand(SDNode *N) { 10305 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 10306 for (unsigned i = 0; i < NumElts; ++i) { 10307 SDNode *Elt = N->getOperand(i).getNode(); 10308 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 10309 return true; 10310 } 10311 return false; 10312 } 10313 10314 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 10315 /// ISD::BUILD_VECTOR. 10316 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 10317 TargetLowering::DAGCombinerInfo &DCI, 10318 const ARMSubtarget *Subtarget) { 10319 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 10320 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 10321 // into a pair of GPRs, which is fine when the value is used as a scalar, 10322 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 10323 SelectionDAG &DAG = DCI.DAG; 10324 if (N->getNumOperands() == 2) 10325 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 10326 return RV; 10327 10328 // Load i64 elements as f64 values so that type legalization does not split 10329 // them up into i32 values. 10330 EVT VT = N->getValueType(0); 10331 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 10332 return SDValue(); 10333 SDLoc dl(N); 10334 SmallVector<SDValue, 8> Ops; 10335 unsigned NumElts = VT.getVectorNumElements(); 10336 for (unsigned i = 0; i < NumElts; ++i) { 10337 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 10338 Ops.push_back(V); 10339 // Make the DAGCombiner fold the bitcast. 10340 DCI.AddToWorklist(V.getNode()); 10341 } 10342 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 10343 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 10344 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 10345 } 10346 10347 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 10348 static SDValue 10349 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10350 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 10351 // At that time, we may have inserted bitcasts from integer to float. 10352 // If these bitcasts have survived DAGCombine, change the lowering of this 10353 // BUILD_VECTOR in something more vector friendly, i.e., that does not 10354 // force to use floating point types. 10355 10356 // Make sure we can change the type of the vector. 10357 // This is possible iff: 10358 // 1. The vector is only used in a bitcast to a integer type. I.e., 10359 // 1.1. Vector is used only once. 10360 // 1.2. Use is a bit convert to an integer type. 10361 // 2. The size of its operands are 32-bits (64-bits are not legal). 10362 EVT VT = N->getValueType(0); 10363 EVT EltVT = VT.getVectorElementType(); 10364 10365 // Check 1.1. and 2. 10366 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 10367 return SDValue(); 10368 10369 // By construction, the input type must be float. 10370 assert(EltVT == MVT::f32 && "Unexpected type!"); 10371 10372 // Check 1.2. 10373 SDNode *Use = *N->use_begin(); 10374 if (Use->getOpcode() != ISD::BITCAST || 10375 Use->getValueType(0).isFloatingPoint()) 10376 return SDValue(); 10377 10378 // Check profitability. 10379 // Model is, if more than half of the relevant operands are bitcast from 10380 // i32, turn the build_vector into a sequence of insert_vector_elt. 10381 // Relevant operands are everything that is not statically 10382 // (i.e., at compile time) bitcasted. 10383 unsigned NumOfBitCastedElts = 0; 10384 unsigned NumElts = VT.getVectorNumElements(); 10385 unsigned NumOfRelevantElts = NumElts; 10386 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 10387 SDValue Elt = N->getOperand(Idx); 10388 if (Elt->getOpcode() == ISD::BITCAST) { 10389 // Assume only bit cast to i32 will go away. 10390 if (Elt->getOperand(0).getValueType() == MVT::i32) 10391 ++NumOfBitCastedElts; 10392 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 10393 // Constants are statically casted, thus do not count them as 10394 // relevant operands. 10395 --NumOfRelevantElts; 10396 } 10397 10398 // Check if more than half of the elements require a non-free bitcast. 10399 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 10400 return SDValue(); 10401 10402 SelectionDAG &DAG = DCI.DAG; 10403 // Create the new vector type. 10404 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 10405 // Check if the type is legal. 10406 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10407 if (!TLI.isTypeLegal(VecVT)) 10408 return SDValue(); 10409 10410 // Combine: 10411 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 10412 // => BITCAST INSERT_VECTOR_ELT 10413 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 10414 // (BITCAST EN), N. 10415 SDValue Vec = DAG.getUNDEF(VecVT); 10416 SDLoc dl(N); 10417 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 10418 SDValue V = N->getOperand(Idx); 10419 if (V.isUndef()) 10420 continue; 10421 if (V.getOpcode() == ISD::BITCAST && 10422 V->getOperand(0).getValueType() == MVT::i32) 10423 // Fold obvious case. 10424 V = V.getOperand(0); 10425 else { 10426 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 10427 // Make the DAGCombiner fold the bitcasts. 10428 DCI.AddToWorklist(V.getNode()); 10429 } 10430 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 10431 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 10432 } 10433 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 10434 // Make the DAGCombiner fold the bitcasts. 10435 DCI.AddToWorklist(Vec.getNode()); 10436 return Vec; 10437 } 10438 10439 /// PerformInsertEltCombine - Target-specific dag combine xforms for 10440 /// ISD::INSERT_VECTOR_ELT. 10441 static SDValue PerformInsertEltCombine(SDNode *N, 10442 TargetLowering::DAGCombinerInfo &DCI) { 10443 // Bitcast an i64 load inserted into a vector to f64. 10444 // Otherwise, the i64 value will be legalized to a pair of i32 values. 10445 EVT VT = N->getValueType(0); 10446 SDNode *Elt = N->getOperand(1).getNode(); 10447 if (VT.getVectorElementType() != MVT::i64 || 10448 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 10449 return SDValue(); 10450 10451 SelectionDAG &DAG = DCI.DAG; 10452 SDLoc dl(N); 10453 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 10454 VT.getVectorNumElements()); 10455 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 10456 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 10457 // Make the DAGCombiner fold the bitcasts. 10458 DCI.AddToWorklist(Vec.getNode()); 10459 DCI.AddToWorklist(V.getNode()); 10460 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 10461 Vec, V, N->getOperand(2)); 10462 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 10463 } 10464 10465 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 10466 /// ISD::VECTOR_SHUFFLE. 10467 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 10468 // The LLVM shufflevector instruction does not require the shuffle mask 10469 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 10470 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 10471 // operands do not match the mask length, they are extended by concatenating 10472 // them with undef vectors. That is probably the right thing for other 10473 // targets, but for NEON it is better to concatenate two double-register 10474 // size vector operands into a single quad-register size vector. Do that 10475 // transformation here: 10476 // shuffle(concat(v1, undef), concat(v2, undef)) -> 10477 // shuffle(concat(v1, v2), undef) 10478 SDValue Op0 = N->getOperand(0); 10479 SDValue Op1 = N->getOperand(1); 10480 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 10481 Op1.getOpcode() != ISD::CONCAT_VECTORS || 10482 Op0.getNumOperands() != 2 || 10483 Op1.getNumOperands() != 2) 10484 return SDValue(); 10485 SDValue Concat0Op1 = Op0.getOperand(1); 10486 SDValue Concat1Op1 = Op1.getOperand(1); 10487 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 10488 return SDValue(); 10489 // Skip the transformation if any of the types are illegal. 10490 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10491 EVT VT = N->getValueType(0); 10492 if (!TLI.isTypeLegal(VT) || 10493 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 10494 !TLI.isTypeLegal(Concat1Op1.getValueType())) 10495 return SDValue(); 10496 10497 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 10498 Op0.getOperand(0), Op1.getOperand(0)); 10499 // Translate the shuffle mask. 10500 SmallVector<int, 16> NewMask; 10501 unsigned NumElts = VT.getVectorNumElements(); 10502 unsigned HalfElts = NumElts/2; 10503 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 10504 for (unsigned n = 0; n < NumElts; ++n) { 10505 int MaskElt = SVN->getMaskElt(n); 10506 int NewElt = -1; 10507 if (MaskElt < (int)HalfElts) 10508 NewElt = MaskElt; 10509 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 10510 NewElt = HalfElts + MaskElt - NumElts; 10511 NewMask.push_back(NewElt); 10512 } 10513 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 10514 DAG.getUNDEF(VT), NewMask); 10515 } 10516 10517 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 10518 /// NEON load/store intrinsics, and generic vector load/stores, to merge 10519 /// base address updates. 10520 /// For generic load/stores, the memory type is assumed to be a vector. 10521 /// The caller is assumed to have checked legality. 10522 static SDValue CombineBaseUpdate(SDNode *N, 10523 TargetLowering::DAGCombinerInfo &DCI) { 10524 SelectionDAG &DAG = DCI.DAG; 10525 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 10526 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 10527 const bool isStore = N->getOpcode() == ISD::STORE; 10528 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 10529 SDValue Addr = N->getOperand(AddrOpIdx); 10530 MemSDNode *MemN = cast<MemSDNode>(N); 10531 SDLoc dl(N); 10532 10533 // Search for a use of the address operand that is an increment. 10534 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 10535 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 10536 SDNode *User = *UI; 10537 if (User->getOpcode() != ISD::ADD || 10538 UI.getUse().getResNo() != Addr.getResNo()) 10539 continue; 10540 10541 // Check that the add is independent of the load/store. Otherwise, folding 10542 // it would create a cycle. 10543 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 10544 continue; 10545 10546 // Find the new opcode for the updating load/store. 10547 bool isLoadOp = true; 10548 bool isLaneOp = false; 10549 unsigned NewOpc = 0; 10550 unsigned NumVecs = 0; 10551 if (isIntrinsic) { 10552 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10553 switch (IntNo) { 10554 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 10555 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 10556 NumVecs = 1; break; 10557 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 10558 NumVecs = 2; break; 10559 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 10560 NumVecs = 3; break; 10561 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 10562 NumVecs = 4; break; 10563 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 10564 NumVecs = 2; isLaneOp = true; break; 10565 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 10566 NumVecs = 3; isLaneOp = true; break; 10567 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 10568 NumVecs = 4; isLaneOp = true; break; 10569 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 10570 NumVecs = 1; isLoadOp = false; break; 10571 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 10572 NumVecs = 2; isLoadOp = false; break; 10573 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 10574 NumVecs = 3; isLoadOp = false; break; 10575 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 10576 NumVecs = 4; isLoadOp = false; break; 10577 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 10578 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 10579 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 10580 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 10581 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 10582 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 10583 } 10584 } else { 10585 isLaneOp = true; 10586 switch (N->getOpcode()) { 10587 default: llvm_unreachable("unexpected opcode for Neon base update"); 10588 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 10589 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 10590 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 10591 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 10592 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 10593 NumVecs = 1; isLaneOp = false; break; 10594 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 10595 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 10596 } 10597 } 10598 10599 // Find the size of memory referenced by the load/store. 10600 EVT VecTy; 10601 if (isLoadOp) { 10602 VecTy = N->getValueType(0); 10603 } else if (isIntrinsic) { 10604 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 10605 } else { 10606 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 10607 VecTy = N->getOperand(1).getValueType(); 10608 } 10609 10610 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 10611 if (isLaneOp) 10612 NumBytes /= VecTy.getVectorNumElements(); 10613 10614 // If the increment is a constant, it must match the memory ref size. 10615 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 10616 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 10617 uint64_t IncVal = CInc->getZExtValue(); 10618 if (IncVal != NumBytes) 10619 continue; 10620 } else if (NumBytes >= 3 * 16) { 10621 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 10622 // separate instructions that make it harder to use a non-constant update. 10623 continue; 10624 } 10625 10626 // OK, we found an ADD we can fold into the base update. 10627 // Now, create a _UPD node, taking care of not breaking alignment. 10628 10629 EVT AlignedVecTy = VecTy; 10630 unsigned Alignment = MemN->getAlignment(); 10631 10632 // If this is a less-than-standard-aligned load/store, change the type to 10633 // match the standard alignment. 10634 // The alignment is overlooked when selecting _UPD variants; and it's 10635 // easier to introduce bitcasts here than fix that. 10636 // There are 3 ways to get to this base-update combine: 10637 // - intrinsics: they are assumed to be properly aligned (to the standard 10638 // alignment of the memory type), so we don't need to do anything. 10639 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 10640 // intrinsics, so, likewise, there's nothing to do. 10641 // - generic load/store instructions: the alignment is specified as an 10642 // explicit operand, rather than implicitly as the standard alignment 10643 // of the memory type (like the intrisics). We need to change the 10644 // memory type to match the explicit alignment. That way, we don't 10645 // generate non-standard-aligned ARMISD::VLDx nodes. 10646 if (isa<LSBaseSDNode>(N)) { 10647 if (Alignment == 0) 10648 Alignment = 1; 10649 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 10650 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 10651 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 10652 assert(!isLaneOp && "Unexpected generic load/store lane."); 10653 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 10654 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 10655 } 10656 // Don't set an explicit alignment on regular load/stores that we want 10657 // to transform to VLD/VST 1_UPD nodes. 10658 // This matches the behavior of regular load/stores, which only get an 10659 // explicit alignment if the MMO alignment is larger than the standard 10660 // alignment of the memory type. 10661 // Intrinsics, however, always get an explicit alignment, set to the 10662 // alignment of the MMO. 10663 Alignment = 1; 10664 } 10665 10666 // Create the new updating load/store node. 10667 // First, create an SDVTList for the new updating node's results. 10668 EVT Tys[6]; 10669 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 10670 unsigned n; 10671 for (n = 0; n < NumResultVecs; ++n) 10672 Tys[n] = AlignedVecTy; 10673 Tys[n++] = MVT::i32; 10674 Tys[n] = MVT::Other; 10675 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 10676 10677 // Then, gather the new node's operands. 10678 SmallVector<SDValue, 8> Ops; 10679 Ops.push_back(N->getOperand(0)); // incoming chain 10680 Ops.push_back(N->getOperand(AddrOpIdx)); 10681 Ops.push_back(Inc); 10682 10683 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 10684 // Try to match the intrinsic's signature 10685 Ops.push_back(StN->getValue()); 10686 } else { 10687 // Loads (and of course intrinsics) match the intrinsics' signature, 10688 // so just add all but the alignment operand. 10689 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 10690 Ops.push_back(N->getOperand(i)); 10691 } 10692 10693 // For all node types, the alignment operand is always the last one. 10694 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 10695 10696 // If this is a non-standard-aligned STORE, the penultimate operand is the 10697 // stored value. Bitcast it to the aligned type. 10698 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 10699 SDValue &StVal = Ops[Ops.size()-2]; 10700 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 10701 } 10702 10703 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 10704 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 10705 MemN->getMemOperand()); 10706 10707 // Update the uses. 10708 SmallVector<SDValue, 5> NewResults; 10709 for (unsigned i = 0; i < NumResultVecs; ++i) 10710 NewResults.push_back(SDValue(UpdN.getNode(), i)); 10711 10712 // If this is an non-standard-aligned LOAD, the first result is the loaded 10713 // value. Bitcast it to the expected result type. 10714 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 10715 SDValue &LdVal = NewResults[0]; 10716 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 10717 } 10718 10719 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 10720 DCI.CombineTo(N, NewResults); 10721 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 10722 10723 break; 10724 } 10725 return SDValue(); 10726 } 10727 10728 static SDValue PerformVLDCombine(SDNode *N, 10729 TargetLowering::DAGCombinerInfo &DCI) { 10730 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10731 return SDValue(); 10732 10733 return CombineBaseUpdate(N, DCI); 10734 } 10735 10736 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 10737 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 10738 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 10739 /// return true. 10740 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10741 SelectionDAG &DAG = DCI.DAG; 10742 EVT VT = N->getValueType(0); 10743 // vldN-dup instructions only support 64-bit vectors for N > 1. 10744 if (!VT.is64BitVector()) 10745 return false; 10746 10747 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 10748 SDNode *VLD = N->getOperand(0).getNode(); 10749 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 10750 return false; 10751 unsigned NumVecs = 0; 10752 unsigned NewOpc = 0; 10753 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 10754 if (IntNo == Intrinsic::arm_neon_vld2lane) { 10755 NumVecs = 2; 10756 NewOpc = ARMISD::VLD2DUP; 10757 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 10758 NumVecs = 3; 10759 NewOpc = ARMISD::VLD3DUP; 10760 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 10761 NumVecs = 4; 10762 NewOpc = ARMISD::VLD4DUP; 10763 } else { 10764 return false; 10765 } 10766 10767 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 10768 // numbers match the load. 10769 unsigned VLDLaneNo = 10770 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 10771 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 10772 UI != UE; ++UI) { 10773 // Ignore uses of the chain result. 10774 if (UI.getUse().getResNo() == NumVecs) 10775 continue; 10776 SDNode *User = *UI; 10777 if (User->getOpcode() != ARMISD::VDUPLANE || 10778 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 10779 return false; 10780 } 10781 10782 // Create the vldN-dup node. 10783 EVT Tys[5]; 10784 unsigned n; 10785 for (n = 0; n < NumVecs; ++n) 10786 Tys[n] = VT; 10787 Tys[n] = MVT::Other; 10788 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 10789 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 10790 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 10791 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 10792 Ops, VLDMemInt->getMemoryVT(), 10793 VLDMemInt->getMemOperand()); 10794 10795 // Update the uses. 10796 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 10797 UI != UE; ++UI) { 10798 unsigned ResNo = UI.getUse().getResNo(); 10799 // Ignore uses of the chain result. 10800 if (ResNo == NumVecs) 10801 continue; 10802 SDNode *User = *UI; 10803 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 10804 } 10805 10806 // Now the vldN-lane intrinsic is dead except for its chain result. 10807 // Update uses of the chain. 10808 std::vector<SDValue> VLDDupResults; 10809 for (unsigned n = 0; n < NumVecs; ++n) 10810 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 10811 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 10812 DCI.CombineTo(VLD, VLDDupResults); 10813 10814 return true; 10815 } 10816 10817 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 10818 /// ARMISD::VDUPLANE. 10819 static SDValue PerformVDUPLANECombine(SDNode *N, 10820 TargetLowering::DAGCombinerInfo &DCI) { 10821 SDValue Op = N->getOperand(0); 10822 10823 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 10824 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 10825 if (CombineVLDDUP(N, DCI)) 10826 return SDValue(N, 0); 10827 10828 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 10829 // redundant. Ignore bit_converts for now; element sizes are checked below. 10830 while (Op.getOpcode() == ISD::BITCAST) 10831 Op = Op.getOperand(0); 10832 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 10833 return SDValue(); 10834 10835 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 10836 unsigned EltSize = Op.getScalarValueSizeInBits(); 10837 // The canonical VMOV for a zero vector uses a 32-bit element size. 10838 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10839 unsigned EltBits; 10840 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 10841 EltSize = 8; 10842 EVT VT = N->getValueType(0); 10843 if (EltSize > VT.getScalarSizeInBits()) 10844 return SDValue(); 10845 10846 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 10847 } 10848 10849 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 10850 static SDValue PerformVDUPCombine(SDNode *N, 10851 TargetLowering::DAGCombinerInfo &DCI) { 10852 SelectionDAG &DAG = DCI.DAG; 10853 SDValue Op = N->getOperand(0); 10854 10855 // Match VDUP(LOAD) -> VLD1DUP. 10856 // We match this pattern here rather than waiting for isel because the 10857 // transform is only legal for unindexed loads. 10858 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 10859 if (LD && Op.hasOneUse() && LD->isUnindexed() && 10860 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 10861 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 10862 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 10863 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 10864 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 10865 Ops, LD->getMemoryVT(), 10866 LD->getMemOperand()); 10867 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 10868 return VLDDup; 10869 } 10870 10871 return SDValue(); 10872 } 10873 10874 static SDValue PerformLOADCombine(SDNode *N, 10875 TargetLowering::DAGCombinerInfo &DCI) { 10876 EVT VT = N->getValueType(0); 10877 10878 // If this is a legal vector load, try to combine it into a VLD1_UPD. 10879 if (ISD::isNormalLoad(N) && VT.isVector() && 10880 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10881 return CombineBaseUpdate(N, DCI); 10882 10883 return SDValue(); 10884 } 10885 10886 /// PerformSTORECombine - Target-specific dag combine xforms for 10887 /// ISD::STORE. 10888 static SDValue PerformSTORECombine(SDNode *N, 10889 TargetLowering::DAGCombinerInfo &DCI) { 10890 StoreSDNode *St = cast<StoreSDNode>(N); 10891 if (St->isVolatile()) 10892 return SDValue(); 10893 10894 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 10895 // pack all of the elements in one place. Next, store to memory in fewer 10896 // chunks. 10897 SDValue StVal = St->getValue(); 10898 EVT VT = StVal.getValueType(); 10899 if (St->isTruncatingStore() && VT.isVector()) { 10900 SelectionDAG &DAG = DCI.DAG; 10901 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10902 EVT StVT = St->getMemoryVT(); 10903 unsigned NumElems = VT.getVectorNumElements(); 10904 assert(StVT != VT && "Cannot truncate to the same type"); 10905 unsigned FromEltSz = VT.getScalarSizeInBits(); 10906 unsigned ToEltSz = StVT.getScalarSizeInBits(); 10907 10908 // From, To sizes and ElemCount must be pow of two 10909 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 10910 10911 // We are going to use the original vector elt for storing. 10912 // Accumulated smaller vector elements must be a multiple of the store size. 10913 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 10914 10915 unsigned SizeRatio = FromEltSz / ToEltSz; 10916 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 10917 10918 // Create a type on which we perform the shuffle. 10919 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 10920 NumElems*SizeRatio); 10921 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 10922 10923 SDLoc DL(St); 10924 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 10925 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 10926 for (unsigned i = 0; i < NumElems; ++i) 10927 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 10928 ? (i + 1) * SizeRatio - 1 10929 : i * SizeRatio; 10930 10931 // Can't shuffle using an illegal type. 10932 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 10933 10934 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 10935 DAG.getUNDEF(WideVec.getValueType()), 10936 ShuffleVec); 10937 // At this point all of the data is stored at the bottom of the 10938 // register. We now need to save it to mem. 10939 10940 // Find the largest store unit 10941 MVT StoreType = MVT::i8; 10942 for (MVT Tp : MVT::integer_valuetypes()) { 10943 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 10944 StoreType = Tp; 10945 } 10946 // Didn't find a legal store type. 10947 if (!TLI.isTypeLegal(StoreType)) 10948 return SDValue(); 10949 10950 // Bitcast the original vector into a vector of store-size units 10951 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 10952 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 10953 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 10954 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 10955 SmallVector<SDValue, 8> Chains; 10956 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 10957 TLI.getPointerTy(DAG.getDataLayout())); 10958 SDValue BasePtr = St->getBasePtr(); 10959 10960 // Perform one or more big stores into memory. 10961 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 10962 for (unsigned I = 0; I < E; I++) { 10963 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 10964 StoreType, ShuffWide, 10965 DAG.getIntPtrConstant(I, DL)); 10966 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 10967 St->getPointerInfo(), St->getAlignment(), 10968 St->getMemOperand()->getFlags()); 10969 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 10970 Increment); 10971 Chains.push_back(Ch); 10972 } 10973 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10974 } 10975 10976 if (!ISD::isNormalStore(St)) 10977 return SDValue(); 10978 10979 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 10980 // ARM stores of arguments in the same cache line. 10981 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 10982 StVal.getNode()->hasOneUse()) { 10983 SelectionDAG &DAG = DCI.DAG; 10984 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 10985 SDLoc DL(St); 10986 SDValue BasePtr = St->getBasePtr(); 10987 SDValue NewST1 = DAG.getStore( 10988 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 10989 BasePtr, St->getPointerInfo(), St->getAlignment(), 10990 St->getMemOperand()->getFlags()); 10991 10992 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10993 DAG.getConstant(4, DL, MVT::i32)); 10994 return DAG.getStore(NewST1.getValue(0), DL, 10995 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 10996 OffsetPtr, St->getPointerInfo(), 10997 std::min(4U, St->getAlignment() / 2), 10998 St->getMemOperand()->getFlags()); 10999 } 11000 11001 if (StVal.getValueType() == MVT::i64 && 11002 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11003 11004 // Bitcast an i64 store extracted from a vector to f64. 11005 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11006 SelectionDAG &DAG = DCI.DAG; 11007 SDLoc dl(StVal); 11008 SDValue IntVec = StVal.getOperand(0); 11009 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11010 IntVec.getValueType().getVectorNumElements()); 11011 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 11012 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 11013 Vec, StVal.getOperand(1)); 11014 dl = SDLoc(N); 11015 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 11016 // Make the DAGCombiner fold the bitcasts. 11017 DCI.AddToWorklist(Vec.getNode()); 11018 DCI.AddToWorklist(ExtElt.getNode()); 11019 DCI.AddToWorklist(V.getNode()); 11020 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 11021 St->getPointerInfo(), St->getAlignment(), 11022 St->getMemOperand()->getFlags(), St->getAAInfo()); 11023 } 11024 11025 // If this is a legal vector store, try to combine it into a VST1_UPD. 11026 if (ISD::isNormalStore(N) && VT.isVector() && 11027 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11028 return CombineBaseUpdate(N, DCI); 11029 11030 return SDValue(); 11031 } 11032 11033 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11034 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11035 /// when the VMUL has a constant operand that is a power of 2. 11036 /// 11037 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11038 /// vmul.f32 d16, d17, d16 11039 /// vcvt.s32.f32 d16, d16 11040 /// becomes: 11041 /// vcvt.s32.f32 d16, d16, #3 11042 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11043 const ARMSubtarget *Subtarget) { 11044 if (!Subtarget->hasNEON()) 11045 return SDValue(); 11046 11047 SDValue Op = N->getOperand(0); 11048 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 11049 Op.getOpcode() != ISD::FMUL) 11050 return SDValue(); 11051 11052 SDValue ConstVec = Op->getOperand(1); 11053 if (!isa<BuildVectorSDNode>(ConstVec)) 11054 return SDValue(); 11055 11056 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 11057 uint32_t FloatBits = FloatTy.getSizeInBits(); 11058 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 11059 uint32_t IntBits = IntTy.getSizeInBits(); 11060 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11061 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11062 // These instructions only exist converting from f32 to i32. We can handle 11063 // smaller integers by generating an extra truncate, but larger ones would 11064 // be lossy. We also can't handle more then 4 lanes, since these intructions 11065 // only support v2i32/v4i32 types. 11066 return SDValue(); 11067 } 11068 11069 BitVector UndefElements; 11070 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11071 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11072 if (C == -1 || C == 0 || C > 32) 11073 return SDValue(); 11074 11075 SDLoc dl(N); 11076 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 11077 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 11078 Intrinsic::arm_neon_vcvtfp2fxu; 11079 SDValue FixConv = DAG.getNode( 11080 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11081 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 11082 DAG.getConstant(C, dl, MVT::i32)); 11083 11084 if (IntBits < FloatBits) 11085 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 11086 11087 return FixConv; 11088 } 11089 11090 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 11091 /// can replace combinations of VCVT (integer to floating-point) and VDIV 11092 /// when the VDIV has a constant operand that is a power of 2. 11093 /// 11094 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11095 /// vcvt.f32.s32 d16, d16 11096 /// vdiv.f32 d16, d17, d16 11097 /// becomes: 11098 /// vcvt.f32.s32 d16, d16, #3 11099 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 11100 const ARMSubtarget *Subtarget) { 11101 if (!Subtarget->hasNEON()) 11102 return SDValue(); 11103 11104 SDValue Op = N->getOperand(0); 11105 unsigned OpOpcode = Op.getNode()->getOpcode(); 11106 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 11107 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 11108 return SDValue(); 11109 11110 SDValue ConstVec = N->getOperand(1); 11111 if (!isa<BuildVectorSDNode>(ConstVec)) 11112 return SDValue(); 11113 11114 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 11115 uint32_t FloatBits = FloatTy.getSizeInBits(); 11116 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 11117 uint32_t IntBits = IntTy.getSizeInBits(); 11118 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11119 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11120 // These instructions only exist converting from i32 to f32. We can handle 11121 // smaller integers by generating an extra extend, but larger ones would 11122 // be lossy. We also can't handle more then 4 lanes, since these intructions 11123 // only support v2i32/v4i32 types. 11124 return SDValue(); 11125 } 11126 11127 BitVector UndefElements; 11128 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11129 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11130 if (C == -1 || C == 0 || C > 32) 11131 return SDValue(); 11132 11133 SDLoc dl(N); 11134 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 11135 SDValue ConvInput = Op.getOperand(0); 11136 if (IntBits < FloatBits) 11137 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 11138 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11139 ConvInput); 11140 11141 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 11142 Intrinsic::arm_neon_vcvtfxu2fp; 11143 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 11144 Op.getValueType(), 11145 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 11146 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 11147 } 11148 11149 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 11150 /// operand of a vector shift operation, where all the elements of the 11151 /// build_vector must have the same constant integer value. 11152 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 11153 // Ignore bit_converts. 11154 while (Op.getOpcode() == ISD::BITCAST) 11155 Op = Op.getOperand(0); 11156 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 11157 APInt SplatBits, SplatUndef; 11158 unsigned SplatBitSize; 11159 bool HasAnyUndefs; 11160 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 11161 HasAnyUndefs, ElementBits) || 11162 SplatBitSize > ElementBits) 11163 return false; 11164 Cnt = SplatBits.getSExtValue(); 11165 return true; 11166 } 11167 11168 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 11169 /// operand of a vector shift left operation. That value must be in the range: 11170 /// 0 <= Value < ElementBits for a left shift; or 11171 /// 0 <= Value <= ElementBits for a long left shift. 11172 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 11173 assert(VT.isVector() && "vector shift count is not a vector type"); 11174 int64_t ElementBits = VT.getScalarSizeInBits(); 11175 if (! getVShiftImm(Op, ElementBits, Cnt)) 11176 return false; 11177 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 11178 } 11179 11180 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 11181 /// operand of a vector shift right operation. For a shift opcode, the value 11182 /// is positive, but for an intrinsic the value count must be negative. The 11183 /// absolute value must be in the range: 11184 /// 1 <= |Value| <= ElementBits for a right shift; or 11185 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 11186 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 11187 int64_t &Cnt) { 11188 assert(VT.isVector() && "vector shift count is not a vector type"); 11189 int64_t ElementBits = VT.getScalarSizeInBits(); 11190 if (! getVShiftImm(Op, ElementBits, Cnt)) 11191 return false; 11192 if (!isIntrinsic) 11193 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 11194 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 11195 Cnt = -Cnt; 11196 return true; 11197 } 11198 return false; 11199 } 11200 11201 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 11202 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 11203 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 11204 switch (IntNo) { 11205 default: 11206 // Don't do anything for most intrinsics. 11207 break; 11208 11209 // Vector shifts: check for immediate versions and lower them. 11210 // Note: This is done during DAG combining instead of DAG legalizing because 11211 // the build_vectors for 64-bit vector element shift counts are generally 11212 // not legal, and it is hard to see their values after they get legalized to 11213 // loads from a constant pool. 11214 case Intrinsic::arm_neon_vshifts: 11215 case Intrinsic::arm_neon_vshiftu: 11216 case Intrinsic::arm_neon_vrshifts: 11217 case Intrinsic::arm_neon_vrshiftu: 11218 case Intrinsic::arm_neon_vrshiftn: 11219 case Intrinsic::arm_neon_vqshifts: 11220 case Intrinsic::arm_neon_vqshiftu: 11221 case Intrinsic::arm_neon_vqshiftsu: 11222 case Intrinsic::arm_neon_vqshiftns: 11223 case Intrinsic::arm_neon_vqshiftnu: 11224 case Intrinsic::arm_neon_vqshiftnsu: 11225 case Intrinsic::arm_neon_vqrshiftns: 11226 case Intrinsic::arm_neon_vqrshiftnu: 11227 case Intrinsic::arm_neon_vqrshiftnsu: { 11228 EVT VT = N->getOperand(1).getValueType(); 11229 int64_t Cnt; 11230 unsigned VShiftOpc = 0; 11231 11232 switch (IntNo) { 11233 case Intrinsic::arm_neon_vshifts: 11234 case Intrinsic::arm_neon_vshiftu: 11235 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 11236 VShiftOpc = ARMISD::VSHL; 11237 break; 11238 } 11239 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 11240 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 11241 ARMISD::VSHRs : ARMISD::VSHRu); 11242 break; 11243 } 11244 return SDValue(); 11245 11246 case Intrinsic::arm_neon_vrshifts: 11247 case Intrinsic::arm_neon_vrshiftu: 11248 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 11249 break; 11250 return SDValue(); 11251 11252 case Intrinsic::arm_neon_vqshifts: 11253 case Intrinsic::arm_neon_vqshiftu: 11254 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11255 break; 11256 return SDValue(); 11257 11258 case Intrinsic::arm_neon_vqshiftsu: 11259 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11260 break; 11261 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 11262 11263 case Intrinsic::arm_neon_vrshiftn: 11264 case Intrinsic::arm_neon_vqshiftns: 11265 case Intrinsic::arm_neon_vqshiftnu: 11266 case Intrinsic::arm_neon_vqshiftnsu: 11267 case Intrinsic::arm_neon_vqrshiftns: 11268 case Intrinsic::arm_neon_vqrshiftnu: 11269 case Intrinsic::arm_neon_vqrshiftnsu: 11270 // Narrowing shifts require an immediate right shift. 11271 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 11272 break; 11273 llvm_unreachable("invalid shift count for narrowing vector shift " 11274 "intrinsic"); 11275 11276 default: 11277 llvm_unreachable("unhandled vector shift"); 11278 } 11279 11280 switch (IntNo) { 11281 case Intrinsic::arm_neon_vshifts: 11282 case Intrinsic::arm_neon_vshiftu: 11283 // Opcode already set above. 11284 break; 11285 case Intrinsic::arm_neon_vrshifts: 11286 VShiftOpc = ARMISD::VRSHRs; break; 11287 case Intrinsic::arm_neon_vrshiftu: 11288 VShiftOpc = ARMISD::VRSHRu; break; 11289 case Intrinsic::arm_neon_vrshiftn: 11290 VShiftOpc = ARMISD::VRSHRN; break; 11291 case Intrinsic::arm_neon_vqshifts: 11292 VShiftOpc = ARMISD::VQSHLs; break; 11293 case Intrinsic::arm_neon_vqshiftu: 11294 VShiftOpc = ARMISD::VQSHLu; break; 11295 case Intrinsic::arm_neon_vqshiftsu: 11296 VShiftOpc = ARMISD::VQSHLsu; break; 11297 case Intrinsic::arm_neon_vqshiftns: 11298 VShiftOpc = ARMISD::VQSHRNs; break; 11299 case Intrinsic::arm_neon_vqshiftnu: 11300 VShiftOpc = ARMISD::VQSHRNu; break; 11301 case Intrinsic::arm_neon_vqshiftnsu: 11302 VShiftOpc = ARMISD::VQSHRNsu; break; 11303 case Intrinsic::arm_neon_vqrshiftns: 11304 VShiftOpc = ARMISD::VQRSHRNs; break; 11305 case Intrinsic::arm_neon_vqrshiftnu: 11306 VShiftOpc = ARMISD::VQRSHRNu; break; 11307 case Intrinsic::arm_neon_vqrshiftnsu: 11308 VShiftOpc = ARMISD::VQRSHRNsu; break; 11309 } 11310 11311 SDLoc dl(N); 11312 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11313 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 11314 } 11315 11316 case Intrinsic::arm_neon_vshiftins: { 11317 EVT VT = N->getOperand(1).getValueType(); 11318 int64_t Cnt; 11319 unsigned VShiftOpc = 0; 11320 11321 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 11322 VShiftOpc = ARMISD::VSLI; 11323 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 11324 VShiftOpc = ARMISD::VSRI; 11325 else { 11326 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 11327 } 11328 11329 SDLoc dl(N); 11330 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11331 N->getOperand(1), N->getOperand(2), 11332 DAG.getConstant(Cnt, dl, MVT::i32)); 11333 } 11334 11335 case Intrinsic::arm_neon_vqrshifts: 11336 case Intrinsic::arm_neon_vqrshiftu: 11337 // No immediate versions of these to check for. 11338 break; 11339 } 11340 11341 return SDValue(); 11342 } 11343 11344 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 11345 /// lowers them. As with the vector shift intrinsics, this is done during DAG 11346 /// combining instead of DAG legalizing because the build_vectors for 64-bit 11347 /// vector element shift counts are generally not legal, and it is hard to see 11348 /// their values after they get legalized to loads from a constant pool. 11349 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 11350 const ARMSubtarget *ST) { 11351 EVT VT = N->getValueType(0); 11352 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 11353 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 11354 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 11355 SDValue N1 = N->getOperand(1); 11356 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 11357 SDValue N0 = N->getOperand(0); 11358 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 11359 DAG.MaskedValueIsZero(N0.getOperand(0), 11360 APInt::getHighBitsSet(32, 16))) 11361 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 11362 } 11363 } 11364 11365 // Nothing to be done for scalar shifts. 11366 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11367 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 11368 return SDValue(); 11369 11370 assert(ST->hasNEON() && "unexpected vector shift"); 11371 int64_t Cnt; 11372 11373 switch (N->getOpcode()) { 11374 default: llvm_unreachable("unexpected shift opcode"); 11375 11376 case ISD::SHL: 11377 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 11378 SDLoc dl(N); 11379 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 11380 DAG.getConstant(Cnt, dl, MVT::i32)); 11381 } 11382 break; 11383 11384 case ISD::SRA: 11385 case ISD::SRL: 11386 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 11387 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 11388 ARMISD::VSHRs : ARMISD::VSHRu); 11389 SDLoc dl(N); 11390 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 11391 DAG.getConstant(Cnt, dl, MVT::i32)); 11392 } 11393 } 11394 return SDValue(); 11395 } 11396 11397 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 11398 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 11399 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 11400 const ARMSubtarget *ST) { 11401 SDValue N0 = N->getOperand(0); 11402 11403 // Check for sign- and zero-extensions of vector extract operations of 8- 11404 // and 16-bit vector elements. NEON supports these directly. They are 11405 // handled during DAG combining because type legalization will promote them 11406 // to 32-bit types and it is messy to recognize the operations after that. 11407 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11408 SDValue Vec = N0.getOperand(0); 11409 SDValue Lane = N0.getOperand(1); 11410 EVT VT = N->getValueType(0); 11411 EVT EltVT = N0.getValueType(); 11412 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11413 11414 if (VT == MVT::i32 && 11415 (EltVT == MVT::i8 || EltVT == MVT::i16) && 11416 TLI.isTypeLegal(Vec.getValueType()) && 11417 isa<ConstantSDNode>(Lane)) { 11418 11419 unsigned Opc = 0; 11420 switch (N->getOpcode()) { 11421 default: llvm_unreachable("unexpected opcode"); 11422 case ISD::SIGN_EXTEND: 11423 Opc = ARMISD::VGETLANEs; 11424 break; 11425 case ISD::ZERO_EXTEND: 11426 case ISD::ANY_EXTEND: 11427 Opc = ARMISD::VGETLANEu; 11428 break; 11429 } 11430 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 11431 } 11432 } 11433 11434 return SDValue(); 11435 } 11436 11437 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero, 11438 APInt &KnownOne) { 11439 if (Op.getOpcode() == ARMISD::BFI) { 11440 // Conservatively, we can recurse down the first operand 11441 // and just mask out all affected bits. 11442 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne); 11443 11444 // The operand to BFI is already a mask suitable for removing the bits it 11445 // sets. 11446 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 11447 const APInt &Mask = CI->getAPIntValue(); 11448 KnownZero &= Mask; 11449 KnownOne &= Mask; 11450 return; 11451 } 11452 if (Op.getOpcode() == ARMISD::CMOV) { 11453 APInt KZ2(KnownZero.getBitWidth(), 0); 11454 APInt KO2(KnownOne.getBitWidth(), 0); 11455 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne); 11456 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2); 11457 11458 KnownZero &= KZ2; 11459 KnownOne &= KO2; 11460 return; 11461 } 11462 return DAG.computeKnownBits(Op, KnownZero, KnownOne); 11463 } 11464 11465 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 11466 // If we have a CMOV, OR and AND combination such as: 11467 // if (x & CN) 11468 // y |= CM; 11469 // 11470 // And: 11471 // * CN is a single bit; 11472 // * All bits covered by CM are known zero in y 11473 // 11474 // Then we can convert this into a sequence of BFI instructions. This will 11475 // always be a win if CM is a single bit, will always be no worse than the 11476 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 11477 // three bits (due to the extra IT instruction). 11478 11479 SDValue Op0 = CMOV->getOperand(0); 11480 SDValue Op1 = CMOV->getOperand(1); 11481 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 11482 auto CC = CCNode->getAPIntValue().getLimitedValue(); 11483 SDValue CmpZ = CMOV->getOperand(4); 11484 11485 // The compare must be against zero. 11486 if (!isNullConstant(CmpZ->getOperand(1))) 11487 return SDValue(); 11488 11489 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 11490 SDValue And = CmpZ->getOperand(0); 11491 if (And->getOpcode() != ISD::AND) 11492 return SDValue(); 11493 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1)); 11494 if (!AndC || !AndC->getAPIntValue().isPowerOf2()) 11495 return SDValue(); 11496 SDValue X = And->getOperand(0); 11497 11498 if (CC == ARMCC::EQ) { 11499 // We're performing an "equal to zero" compare. Swap the operands so we 11500 // canonicalize on a "not equal to zero" compare. 11501 std::swap(Op0, Op1); 11502 } else { 11503 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 11504 } 11505 11506 if (Op1->getOpcode() != ISD::OR) 11507 return SDValue(); 11508 11509 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 11510 if (!OrC) 11511 return SDValue(); 11512 SDValue Y = Op1->getOperand(0); 11513 11514 if (Op0 != Y) 11515 return SDValue(); 11516 11517 // Now, is it profitable to continue? 11518 APInt OrCI = OrC->getAPIntValue(); 11519 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 11520 if (OrCI.countPopulation() > Heuristic) 11521 return SDValue(); 11522 11523 // Lastly, can we determine that the bits defined by OrCI 11524 // are zero in Y? 11525 APInt KnownZero, KnownOne; 11526 computeKnownBits(DAG, Y, KnownZero, KnownOne); 11527 if ((OrCI & KnownZero) != OrCI) 11528 return SDValue(); 11529 11530 // OK, we can do the combine. 11531 SDValue V = Y; 11532 SDLoc dl(X); 11533 EVT VT = X.getValueType(); 11534 unsigned BitInX = AndC->getAPIntValue().logBase2(); 11535 11536 if (BitInX != 0) { 11537 // We must shift X first. 11538 X = DAG.getNode(ISD::SRL, dl, VT, X, 11539 DAG.getConstant(BitInX, dl, VT)); 11540 } 11541 11542 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 11543 BitInY < NumActiveBits; ++BitInY) { 11544 if (OrCI[BitInY] == 0) 11545 continue; 11546 APInt Mask(VT.getSizeInBits(), 0); 11547 Mask.setBit(BitInY); 11548 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 11549 // Confusingly, the operand is an *inverted* mask. 11550 DAG.getConstant(~Mask, dl, VT)); 11551 } 11552 11553 return V; 11554 } 11555 11556 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 11557 SDValue 11558 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 11559 SDValue Cmp = N->getOperand(4); 11560 if (Cmp.getOpcode() != ARMISD::CMPZ) 11561 // Only looking at NE cases. 11562 return SDValue(); 11563 11564 EVT VT = N->getValueType(0); 11565 SDLoc dl(N); 11566 SDValue LHS = Cmp.getOperand(0); 11567 SDValue RHS = Cmp.getOperand(1); 11568 SDValue Chain = N->getOperand(0); 11569 SDValue BB = N->getOperand(1); 11570 SDValue ARMcc = N->getOperand(2); 11571 ARMCC::CondCodes CC = 11572 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11573 11574 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 11575 // -> (brcond Chain BB CC CPSR Cmp) 11576 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 11577 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 11578 LHS->getOperand(0)->hasOneUse()) { 11579 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 11580 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 11581 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11582 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11583 if ((LHS00C && LHS00C->getZExtValue() == 0) && 11584 (LHS01C && LHS01C->getZExtValue() == 1) && 11585 (LHS1C && LHS1C->getZExtValue() == 1) && 11586 (RHSC && RHSC->getZExtValue() == 0)) { 11587 return DAG.getNode( 11588 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 11589 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 11590 } 11591 } 11592 11593 return SDValue(); 11594 } 11595 11596 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 11597 SDValue 11598 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 11599 SDValue Cmp = N->getOperand(4); 11600 if (Cmp.getOpcode() != ARMISD::CMPZ) 11601 // Only looking at EQ and NE cases. 11602 return SDValue(); 11603 11604 EVT VT = N->getValueType(0); 11605 SDLoc dl(N); 11606 SDValue LHS = Cmp.getOperand(0); 11607 SDValue RHS = Cmp.getOperand(1); 11608 SDValue FalseVal = N->getOperand(0); 11609 SDValue TrueVal = N->getOperand(1); 11610 SDValue ARMcc = N->getOperand(2); 11611 ARMCC::CondCodes CC = 11612 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 11613 11614 // BFI is only available on V6T2+. 11615 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 11616 SDValue R = PerformCMOVToBFICombine(N, DAG); 11617 if (R) 11618 return R; 11619 } 11620 11621 // Simplify 11622 // mov r1, r0 11623 // cmp r1, x 11624 // mov r0, y 11625 // moveq r0, x 11626 // to 11627 // cmp r0, x 11628 // movne r0, y 11629 // 11630 // mov r1, r0 11631 // cmp r1, x 11632 // mov r0, x 11633 // movne r0, y 11634 // to 11635 // cmp r0, x 11636 // movne r0, y 11637 /// FIXME: Turn this into a target neutral optimization? 11638 SDValue Res; 11639 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 11640 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 11641 N->getOperand(3), Cmp); 11642 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 11643 SDValue ARMcc; 11644 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 11645 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 11646 N->getOperand(3), NewCmp); 11647 } 11648 11649 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 11650 // -> (cmov F T CC CPSR Cmp) 11651 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 11652 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 11653 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 11654 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 11655 if ((LHS0C && LHS0C->getZExtValue() == 0) && 11656 (LHS1C && LHS1C->getZExtValue() == 1) && 11657 (RHSC && RHSC->getZExtValue() == 0)) { 11658 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 11659 LHS->getOperand(2), LHS->getOperand(3), 11660 LHS->getOperand(4)); 11661 } 11662 } 11663 11664 if (Res.getNode()) { 11665 APInt KnownZero, KnownOne; 11666 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne); 11667 // Capture demanded bits information that would be otherwise lost. 11668 if (KnownZero == 0xfffffffe) 11669 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11670 DAG.getValueType(MVT::i1)); 11671 else if (KnownZero == 0xffffff00) 11672 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11673 DAG.getValueType(MVT::i8)); 11674 else if (KnownZero == 0xffff0000) 11675 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 11676 DAG.getValueType(MVT::i16)); 11677 } 11678 11679 return Res; 11680 } 11681 11682 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 11683 DAGCombinerInfo &DCI) const { 11684 switch (N->getOpcode()) { 11685 default: break; 11686 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 11687 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 11688 case ISD::SUB: return PerformSUBCombine(N, DCI); 11689 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 11690 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 11691 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 11692 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 11693 case ARMISD::BFI: return PerformBFICombine(N, DCI); 11694 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 11695 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 11696 case ISD::STORE: return PerformSTORECombine(N, DCI); 11697 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 11698 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 11699 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 11700 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 11701 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 11702 case ISD::FP_TO_SINT: 11703 case ISD::FP_TO_UINT: 11704 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 11705 case ISD::FDIV: 11706 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 11707 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 11708 case ISD::SHL: 11709 case ISD::SRA: 11710 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 11711 case ISD::SIGN_EXTEND: 11712 case ISD::ZERO_EXTEND: 11713 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 11714 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 11715 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 11716 case ISD::LOAD: return PerformLOADCombine(N, DCI); 11717 case ARMISD::VLD1DUP: 11718 case ARMISD::VLD2DUP: 11719 case ARMISD::VLD3DUP: 11720 case ARMISD::VLD4DUP: 11721 return PerformVLDCombine(N, DCI); 11722 case ARMISD::BUILD_VECTOR: 11723 return PerformARMBUILD_VECTORCombine(N, DCI); 11724 case ISD::INTRINSIC_VOID: 11725 case ISD::INTRINSIC_W_CHAIN: 11726 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11727 case Intrinsic::arm_neon_vld1: 11728 case Intrinsic::arm_neon_vld2: 11729 case Intrinsic::arm_neon_vld3: 11730 case Intrinsic::arm_neon_vld4: 11731 case Intrinsic::arm_neon_vld2lane: 11732 case Intrinsic::arm_neon_vld3lane: 11733 case Intrinsic::arm_neon_vld4lane: 11734 case Intrinsic::arm_neon_vst1: 11735 case Intrinsic::arm_neon_vst2: 11736 case Intrinsic::arm_neon_vst3: 11737 case Intrinsic::arm_neon_vst4: 11738 case Intrinsic::arm_neon_vst2lane: 11739 case Intrinsic::arm_neon_vst3lane: 11740 case Intrinsic::arm_neon_vst4lane: 11741 return PerformVLDCombine(N, DCI); 11742 default: break; 11743 } 11744 break; 11745 } 11746 return SDValue(); 11747 } 11748 11749 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 11750 EVT VT) const { 11751 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 11752 } 11753 11754 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 11755 unsigned, 11756 unsigned, 11757 bool *Fast) const { 11758 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 11759 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 11760 11761 switch (VT.getSimpleVT().SimpleTy) { 11762 default: 11763 return false; 11764 case MVT::i8: 11765 case MVT::i16: 11766 case MVT::i32: { 11767 // Unaligned access can use (for example) LRDB, LRDH, LDR 11768 if (AllowsUnaligned) { 11769 if (Fast) 11770 *Fast = Subtarget->hasV7Ops(); 11771 return true; 11772 } 11773 return false; 11774 } 11775 case MVT::f64: 11776 case MVT::v2f64: { 11777 // For any little-endian targets with neon, we can support unaligned ld/st 11778 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 11779 // A big-endian target may also explicitly support unaligned accesses 11780 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 11781 if (Fast) 11782 *Fast = true; 11783 return true; 11784 } 11785 return false; 11786 } 11787 } 11788 } 11789 11790 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 11791 unsigned AlignCheck) { 11792 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 11793 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 11794 } 11795 11796 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 11797 unsigned DstAlign, unsigned SrcAlign, 11798 bool IsMemset, bool ZeroMemset, 11799 bool MemcpyStrSrc, 11800 MachineFunction &MF) const { 11801 const Function *F = MF.getFunction(); 11802 11803 // See if we can use NEON instructions for this... 11804 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 11805 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 11806 bool Fast; 11807 if (Size >= 16 && 11808 (memOpAlign(SrcAlign, DstAlign, 16) || 11809 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 11810 return MVT::v2f64; 11811 } else if (Size >= 8 && 11812 (memOpAlign(SrcAlign, DstAlign, 8) || 11813 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 11814 Fast))) { 11815 return MVT::f64; 11816 } 11817 } 11818 11819 // Lowering to i32/i16 if the size permits. 11820 if (Size >= 4) 11821 return MVT::i32; 11822 else if (Size >= 2) 11823 return MVT::i16; 11824 11825 // Let the target-independent logic figure it out. 11826 return MVT::Other; 11827 } 11828 11829 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 11830 if (Val.getOpcode() != ISD::LOAD) 11831 return false; 11832 11833 EVT VT1 = Val.getValueType(); 11834 if (!VT1.isSimple() || !VT1.isInteger() || 11835 !VT2.isSimple() || !VT2.isInteger()) 11836 return false; 11837 11838 switch (VT1.getSimpleVT().SimpleTy) { 11839 default: break; 11840 case MVT::i1: 11841 case MVT::i8: 11842 case MVT::i16: 11843 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 11844 return true; 11845 } 11846 11847 return false; 11848 } 11849 11850 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 11851 EVT VT = ExtVal.getValueType(); 11852 11853 if (!isTypeLegal(VT)) 11854 return false; 11855 11856 // Don't create a loadext if we can fold the extension into a wide/long 11857 // instruction. 11858 // If there's more than one user instruction, the loadext is desirable no 11859 // matter what. There can be two uses by the same instruction. 11860 if (ExtVal->use_empty() || 11861 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 11862 return true; 11863 11864 SDNode *U = *ExtVal->use_begin(); 11865 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 11866 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 11867 return false; 11868 11869 return true; 11870 } 11871 11872 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 11873 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 11874 return false; 11875 11876 if (!isTypeLegal(EVT::getEVT(Ty1))) 11877 return false; 11878 11879 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 11880 11881 // Assuming the caller doesn't have a zeroext or signext return parameter, 11882 // truncation all the way down to i1 is valid. 11883 return true; 11884 } 11885 11886 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 11887 const AddrMode &AM, Type *Ty, 11888 unsigned AS) const { 11889 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 11890 if (Subtarget->hasFPAO()) 11891 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 11892 return 0; 11893 } 11894 return -1; 11895 } 11896 11897 11898 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 11899 if (V < 0) 11900 return false; 11901 11902 unsigned Scale = 1; 11903 switch (VT.getSimpleVT().SimpleTy) { 11904 default: return false; 11905 case MVT::i1: 11906 case MVT::i8: 11907 // Scale == 1; 11908 break; 11909 case MVT::i16: 11910 // Scale == 2; 11911 Scale = 2; 11912 break; 11913 case MVT::i32: 11914 // Scale == 4; 11915 Scale = 4; 11916 break; 11917 } 11918 11919 if ((V & (Scale - 1)) != 0) 11920 return false; 11921 V /= Scale; 11922 return V == (V & ((1LL << 5) - 1)); 11923 } 11924 11925 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 11926 const ARMSubtarget *Subtarget) { 11927 bool isNeg = false; 11928 if (V < 0) { 11929 isNeg = true; 11930 V = - V; 11931 } 11932 11933 switch (VT.getSimpleVT().SimpleTy) { 11934 default: return false; 11935 case MVT::i1: 11936 case MVT::i8: 11937 case MVT::i16: 11938 case MVT::i32: 11939 // + imm12 or - imm8 11940 if (isNeg) 11941 return V == (V & ((1LL << 8) - 1)); 11942 return V == (V & ((1LL << 12) - 1)); 11943 case MVT::f32: 11944 case MVT::f64: 11945 // Same as ARM mode. FIXME: NEON? 11946 if (!Subtarget->hasVFP2()) 11947 return false; 11948 if ((V & 3) != 0) 11949 return false; 11950 V >>= 2; 11951 return V == (V & ((1LL << 8) - 1)); 11952 } 11953 } 11954 11955 /// isLegalAddressImmediate - Return true if the integer value can be used 11956 /// as the offset of the target addressing mode for load / store of the 11957 /// given type. 11958 static bool isLegalAddressImmediate(int64_t V, EVT VT, 11959 const ARMSubtarget *Subtarget) { 11960 if (V == 0) 11961 return true; 11962 11963 if (!VT.isSimple()) 11964 return false; 11965 11966 if (Subtarget->isThumb1Only()) 11967 return isLegalT1AddressImmediate(V, VT); 11968 else if (Subtarget->isThumb2()) 11969 return isLegalT2AddressImmediate(V, VT, Subtarget); 11970 11971 // ARM mode. 11972 if (V < 0) 11973 V = - V; 11974 switch (VT.getSimpleVT().SimpleTy) { 11975 default: return false; 11976 case MVT::i1: 11977 case MVT::i8: 11978 case MVT::i32: 11979 // +- imm12 11980 return V == (V & ((1LL << 12) - 1)); 11981 case MVT::i16: 11982 // +- imm8 11983 return V == (V & ((1LL << 8) - 1)); 11984 case MVT::f32: 11985 case MVT::f64: 11986 if (!Subtarget->hasVFP2()) // FIXME: NEON? 11987 return false; 11988 if ((V & 3) != 0) 11989 return false; 11990 V >>= 2; 11991 return V == (V & ((1LL << 8) - 1)); 11992 } 11993 } 11994 11995 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 11996 EVT VT) const { 11997 int Scale = AM.Scale; 11998 if (Scale < 0) 11999 return false; 12000 12001 switch (VT.getSimpleVT().SimpleTy) { 12002 default: return false; 12003 case MVT::i1: 12004 case MVT::i8: 12005 case MVT::i16: 12006 case MVT::i32: 12007 if (Scale == 1) 12008 return true; 12009 // r + r << imm 12010 Scale = Scale & ~1; 12011 return Scale == 2 || Scale == 4 || Scale == 8; 12012 case MVT::i64: 12013 // r + r 12014 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 12015 return true; 12016 return false; 12017 case MVT::isVoid: 12018 // Note, we allow "void" uses (basically, uses that aren't loads or 12019 // stores), because arm allows folding a scale into many arithmetic 12020 // operations. This should be made more precise and revisited later. 12021 12022 // Allow r << imm, but the imm has to be a multiple of two. 12023 if (Scale & 1) return false; 12024 return isPowerOf2_32(Scale); 12025 } 12026 } 12027 12028 /// isLegalAddressingMode - Return true if the addressing mode represented 12029 /// by AM is legal for this target, for a load/store of the specified type. 12030 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 12031 const AddrMode &AM, Type *Ty, 12032 unsigned AS) const { 12033 EVT VT = getValueType(DL, Ty, true); 12034 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 12035 return false; 12036 12037 // Can never fold addr of global into load/store. 12038 if (AM.BaseGV) 12039 return false; 12040 12041 switch (AM.Scale) { 12042 case 0: // no scale reg, must be "r+i" or "r", or "i". 12043 break; 12044 case 1: 12045 if (Subtarget->isThumb1Only()) 12046 return false; 12047 LLVM_FALLTHROUGH; 12048 default: 12049 // ARM doesn't support any R+R*scale+imm addr modes. 12050 if (AM.BaseOffs) 12051 return false; 12052 12053 if (!VT.isSimple()) 12054 return false; 12055 12056 if (Subtarget->isThumb2()) 12057 return isLegalT2ScaledAddressingMode(AM, VT); 12058 12059 int Scale = AM.Scale; 12060 switch (VT.getSimpleVT().SimpleTy) { 12061 default: return false; 12062 case MVT::i1: 12063 case MVT::i8: 12064 case MVT::i32: 12065 if (Scale < 0) Scale = -Scale; 12066 if (Scale == 1) 12067 return true; 12068 // r + r << imm 12069 return isPowerOf2_32(Scale & ~1); 12070 case MVT::i16: 12071 case MVT::i64: 12072 // r + r 12073 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 12074 return true; 12075 return false; 12076 12077 case MVT::isVoid: 12078 // Note, we allow "void" uses (basically, uses that aren't loads or 12079 // stores), because arm allows folding a scale into many arithmetic 12080 // operations. This should be made more precise and revisited later. 12081 12082 // Allow r << imm, but the imm has to be a multiple of two. 12083 if (Scale & 1) return false; 12084 return isPowerOf2_32(Scale); 12085 } 12086 } 12087 return true; 12088 } 12089 12090 /// isLegalICmpImmediate - Return true if the specified immediate is legal 12091 /// icmp immediate, that is the target has icmp instructions which can compare 12092 /// a register against the immediate without having to materialize the 12093 /// immediate into a register. 12094 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 12095 // Thumb2 and ARM modes can use cmn for negative immediates. 12096 if (!Subtarget->isThumb()) 12097 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 12098 if (Subtarget->isThumb2()) 12099 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 12100 // Thumb1 doesn't have cmn, and only 8-bit immediates. 12101 return Imm >= 0 && Imm <= 255; 12102 } 12103 12104 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 12105 /// *or sub* immediate, that is the target has add or sub instructions which can 12106 /// add a register with the immediate without having to materialize the 12107 /// immediate into a register. 12108 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 12109 // Same encoding for add/sub, just flip the sign. 12110 int64_t AbsImm = std::abs(Imm); 12111 if (!Subtarget->isThumb()) 12112 return ARM_AM::getSOImmVal(AbsImm) != -1; 12113 if (Subtarget->isThumb2()) 12114 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 12115 // Thumb1 only has 8-bit unsigned immediate. 12116 return AbsImm >= 0 && AbsImm <= 255; 12117 } 12118 12119 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 12120 bool isSEXTLoad, SDValue &Base, 12121 SDValue &Offset, bool &isInc, 12122 SelectionDAG &DAG) { 12123 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12124 return false; 12125 12126 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 12127 // AddressingMode 3 12128 Base = Ptr->getOperand(0); 12129 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12130 int RHSC = (int)RHS->getZExtValue(); 12131 if (RHSC < 0 && RHSC > -256) { 12132 assert(Ptr->getOpcode() == ISD::ADD); 12133 isInc = false; 12134 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12135 return true; 12136 } 12137 } 12138 isInc = (Ptr->getOpcode() == ISD::ADD); 12139 Offset = Ptr->getOperand(1); 12140 return true; 12141 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 12142 // AddressingMode 2 12143 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12144 int RHSC = (int)RHS->getZExtValue(); 12145 if (RHSC < 0 && RHSC > -0x1000) { 12146 assert(Ptr->getOpcode() == ISD::ADD); 12147 isInc = false; 12148 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12149 Base = Ptr->getOperand(0); 12150 return true; 12151 } 12152 } 12153 12154 if (Ptr->getOpcode() == ISD::ADD) { 12155 isInc = true; 12156 ARM_AM::ShiftOpc ShOpcVal= 12157 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 12158 if (ShOpcVal != ARM_AM::no_shift) { 12159 Base = Ptr->getOperand(1); 12160 Offset = Ptr->getOperand(0); 12161 } else { 12162 Base = Ptr->getOperand(0); 12163 Offset = Ptr->getOperand(1); 12164 } 12165 return true; 12166 } 12167 12168 isInc = (Ptr->getOpcode() == ISD::ADD); 12169 Base = Ptr->getOperand(0); 12170 Offset = Ptr->getOperand(1); 12171 return true; 12172 } 12173 12174 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 12175 return false; 12176 } 12177 12178 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 12179 bool isSEXTLoad, SDValue &Base, 12180 SDValue &Offset, bool &isInc, 12181 SelectionDAG &DAG) { 12182 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12183 return false; 12184 12185 Base = Ptr->getOperand(0); 12186 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12187 int RHSC = (int)RHS->getZExtValue(); 12188 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 12189 assert(Ptr->getOpcode() == ISD::ADD); 12190 isInc = false; 12191 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12192 return true; 12193 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 12194 isInc = Ptr->getOpcode() == ISD::ADD; 12195 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12196 return true; 12197 } 12198 } 12199 12200 return false; 12201 } 12202 12203 /// getPreIndexedAddressParts - returns true by value, base pointer and 12204 /// offset pointer and addressing mode by reference if the node's address 12205 /// can be legally represented as pre-indexed load / store address. 12206 bool 12207 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 12208 SDValue &Offset, 12209 ISD::MemIndexedMode &AM, 12210 SelectionDAG &DAG) const { 12211 if (Subtarget->isThumb1Only()) 12212 return false; 12213 12214 EVT VT; 12215 SDValue Ptr; 12216 bool isSEXTLoad = false; 12217 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12218 Ptr = LD->getBasePtr(); 12219 VT = LD->getMemoryVT(); 12220 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12221 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12222 Ptr = ST->getBasePtr(); 12223 VT = ST->getMemoryVT(); 12224 } else 12225 return false; 12226 12227 bool isInc; 12228 bool isLegal = false; 12229 if (Subtarget->isThumb2()) 12230 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12231 Offset, isInc, DAG); 12232 else 12233 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12234 Offset, isInc, DAG); 12235 if (!isLegal) 12236 return false; 12237 12238 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 12239 return true; 12240 } 12241 12242 /// getPostIndexedAddressParts - returns true by value, base pointer and 12243 /// offset pointer and addressing mode by reference if this node can be 12244 /// combined with a load / store to form a post-indexed load / store. 12245 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 12246 SDValue &Base, 12247 SDValue &Offset, 12248 ISD::MemIndexedMode &AM, 12249 SelectionDAG &DAG) const { 12250 EVT VT; 12251 SDValue Ptr; 12252 bool isSEXTLoad = false, isNonExt; 12253 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12254 VT = LD->getMemoryVT(); 12255 Ptr = LD->getBasePtr(); 12256 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12257 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 12258 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12259 VT = ST->getMemoryVT(); 12260 Ptr = ST->getBasePtr(); 12261 isNonExt = !ST->isTruncatingStore(); 12262 } else 12263 return false; 12264 12265 if (Subtarget->isThumb1Only()) { 12266 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 12267 // must be non-extending/truncating, i32, with an offset of 4. 12268 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 12269 if (Op->getOpcode() != ISD::ADD || !isNonExt) 12270 return false; 12271 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 12272 if (!RHS || RHS->getZExtValue() != 4) 12273 return false; 12274 12275 Offset = Op->getOperand(1); 12276 Base = Op->getOperand(0); 12277 AM = ISD::POST_INC; 12278 return true; 12279 } 12280 12281 bool isInc; 12282 bool isLegal = false; 12283 if (Subtarget->isThumb2()) 12284 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12285 isInc, DAG); 12286 else 12287 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12288 isInc, DAG); 12289 if (!isLegal) 12290 return false; 12291 12292 if (Ptr != Base) { 12293 // Swap base ptr and offset to catch more post-index load / store when 12294 // it's legal. In Thumb2 mode, offset must be an immediate. 12295 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 12296 !Subtarget->isThumb2()) 12297 std::swap(Base, Offset); 12298 12299 // Post-indexed load / store update the base pointer. 12300 if (Ptr != Base) 12301 return false; 12302 } 12303 12304 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 12305 return true; 12306 } 12307 12308 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12309 APInt &KnownZero, 12310 APInt &KnownOne, 12311 const SelectionDAG &DAG, 12312 unsigned Depth) const { 12313 unsigned BitWidth = KnownOne.getBitWidth(); 12314 KnownZero = KnownOne = APInt(BitWidth, 0); 12315 switch (Op.getOpcode()) { 12316 default: break; 12317 case ARMISD::ADDC: 12318 case ARMISD::ADDE: 12319 case ARMISD::SUBC: 12320 case ARMISD::SUBE: 12321 // These nodes' second result is a boolean 12322 if (Op.getResNo() == 0) 12323 break; 12324 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 12325 break; 12326 case ARMISD::CMOV: { 12327 // Bits are known zero/one if known on the LHS and RHS. 12328 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 12329 if (KnownZero == 0 && KnownOne == 0) return; 12330 12331 APInt KnownZeroRHS, KnownOneRHS; 12332 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 12333 KnownZero &= KnownZeroRHS; 12334 KnownOne &= KnownOneRHS; 12335 return; 12336 } 12337 case ISD::INTRINSIC_W_CHAIN: { 12338 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 12339 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 12340 switch (IntID) { 12341 default: return; 12342 case Intrinsic::arm_ldaex: 12343 case Intrinsic::arm_ldrex: { 12344 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 12345 unsigned MemBits = VT.getScalarSizeInBits(); 12346 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 12347 return; 12348 } 12349 } 12350 } 12351 } 12352 } 12353 12354 //===----------------------------------------------------------------------===// 12355 // ARM Inline Assembly Support 12356 //===----------------------------------------------------------------------===// 12357 12358 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 12359 // Looking for "rev" which is V6+. 12360 if (!Subtarget->hasV6Ops()) 12361 return false; 12362 12363 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 12364 std::string AsmStr = IA->getAsmString(); 12365 SmallVector<StringRef, 4> AsmPieces; 12366 SplitString(AsmStr, AsmPieces, ";\n"); 12367 12368 switch (AsmPieces.size()) { 12369 default: return false; 12370 case 1: 12371 AsmStr = AsmPieces[0]; 12372 AsmPieces.clear(); 12373 SplitString(AsmStr, AsmPieces, " \t,"); 12374 12375 // rev $0, $1 12376 if (AsmPieces.size() == 3 && 12377 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 12378 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 12379 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12380 if (Ty && Ty->getBitWidth() == 32) 12381 return IntrinsicLowering::LowerToByteSwap(CI); 12382 } 12383 break; 12384 } 12385 12386 return false; 12387 } 12388 12389 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 12390 // At this point, we have to lower this constraint to something else, so we 12391 // lower it to an "r" or "w". However, by doing this we will force the result 12392 // to be in register, while the X constraint is much more permissive. 12393 // 12394 // Although we are correct (we are free to emit anything, without 12395 // constraints), we might break use cases that would expect us to be more 12396 // efficient and emit something else. 12397 if (!Subtarget->hasVFP2()) 12398 return "r"; 12399 if (ConstraintVT.isFloatingPoint()) 12400 return "w"; 12401 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 12402 (ConstraintVT.getSizeInBits() == 64 || 12403 ConstraintVT.getSizeInBits() == 128)) 12404 return "w"; 12405 12406 return "r"; 12407 } 12408 12409 /// getConstraintType - Given a constraint letter, return the type of 12410 /// constraint it is for this target. 12411 ARMTargetLowering::ConstraintType 12412 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 12413 if (Constraint.size() == 1) { 12414 switch (Constraint[0]) { 12415 default: break; 12416 case 'l': return C_RegisterClass; 12417 case 'w': return C_RegisterClass; 12418 case 'h': return C_RegisterClass; 12419 case 'x': return C_RegisterClass; 12420 case 't': return C_RegisterClass; 12421 case 'j': return C_Other; // Constant for movw. 12422 // An address with a single base register. Due to the way we 12423 // currently handle addresses it is the same as an 'r' memory constraint. 12424 case 'Q': return C_Memory; 12425 } 12426 } else if (Constraint.size() == 2) { 12427 switch (Constraint[0]) { 12428 default: break; 12429 // All 'U+' constraints are addresses. 12430 case 'U': return C_Memory; 12431 } 12432 } 12433 return TargetLowering::getConstraintType(Constraint); 12434 } 12435 12436 /// Examine constraint type and operand type and determine a weight value. 12437 /// This object must already have been set up with the operand type 12438 /// and the current alternative constraint selected. 12439 TargetLowering::ConstraintWeight 12440 ARMTargetLowering::getSingleConstraintMatchWeight( 12441 AsmOperandInfo &info, const char *constraint) const { 12442 ConstraintWeight weight = CW_Invalid; 12443 Value *CallOperandVal = info.CallOperandVal; 12444 // If we don't have a value, we can't do a match, 12445 // but allow it at the lowest weight. 12446 if (!CallOperandVal) 12447 return CW_Default; 12448 Type *type = CallOperandVal->getType(); 12449 // Look at the constraint type. 12450 switch (*constraint) { 12451 default: 12452 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12453 break; 12454 case 'l': 12455 if (type->isIntegerTy()) { 12456 if (Subtarget->isThumb()) 12457 weight = CW_SpecificReg; 12458 else 12459 weight = CW_Register; 12460 } 12461 break; 12462 case 'w': 12463 if (type->isFloatingPointTy()) 12464 weight = CW_Register; 12465 break; 12466 } 12467 return weight; 12468 } 12469 12470 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 12471 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 12472 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 12473 if (Constraint.size() == 1) { 12474 // GCC ARM Constraint Letters 12475 switch (Constraint[0]) { 12476 case 'l': // Low regs or general regs. 12477 if (Subtarget->isThumb()) 12478 return RCPair(0U, &ARM::tGPRRegClass); 12479 return RCPair(0U, &ARM::GPRRegClass); 12480 case 'h': // High regs or no regs. 12481 if (Subtarget->isThumb()) 12482 return RCPair(0U, &ARM::hGPRRegClass); 12483 break; 12484 case 'r': 12485 if (Subtarget->isThumb1Only()) 12486 return RCPair(0U, &ARM::tGPRRegClass); 12487 return RCPair(0U, &ARM::GPRRegClass); 12488 case 'w': 12489 if (VT == MVT::Other) 12490 break; 12491 if (VT == MVT::f32) 12492 return RCPair(0U, &ARM::SPRRegClass); 12493 if (VT.getSizeInBits() == 64) 12494 return RCPair(0U, &ARM::DPRRegClass); 12495 if (VT.getSizeInBits() == 128) 12496 return RCPair(0U, &ARM::QPRRegClass); 12497 break; 12498 case 'x': 12499 if (VT == MVT::Other) 12500 break; 12501 if (VT == MVT::f32) 12502 return RCPair(0U, &ARM::SPR_8RegClass); 12503 if (VT.getSizeInBits() == 64) 12504 return RCPair(0U, &ARM::DPR_8RegClass); 12505 if (VT.getSizeInBits() == 128) 12506 return RCPair(0U, &ARM::QPR_8RegClass); 12507 break; 12508 case 't': 12509 if (VT == MVT::f32) 12510 return RCPair(0U, &ARM::SPRRegClass); 12511 break; 12512 } 12513 } 12514 if (StringRef("{cc}").equals_lower(Constraint)) 12515 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 12516 12517 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12518 } 12519 12520 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12521 /// vector. If it is invalid, don't add anything to Ops. 12522 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12523 std::string &Constraint, 12524 std::vector<SDValue>&Ops, 12525 SelectionDAG &DAG) const { 12526 SDValue Result; 12527 12528 // Currently only support length 1 constraints. 12529 if (Constraint.length() != 1) return; 12530 12531 char ConstraintLetter = Constraint[0]; 12532 switch (ConstraintLetter) { 12533 default: break; 12534 case 'j': 12535 case 'I': case 'J': case 'K': case 'L': 12536 case 'M': case 'N': case 'O': 12537 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 12538 if (!C) 12539 return; 12540 12541 int64_t CVal64 = C->getSExtValue(); 12542 int CVal = (int) CVal64; 12543 // None of these constraints allow values larger than 32 bits. Check 12544 // that the value fits in an int. 12545 if (CVal != CVal64) 12546 return; 12547 12548 switch (ConstraintLetter) { 12549 case 'j': 12550 // Constant suitable for movw, must be between 0 and 12551 // 65535. 12552 if (Subtarget->hasV6T2Ops()) 12553 if (CVal >= 0 && CVal <= 65535) 12554 break; 12555 return; 12556 case 'I': 12557 if (Subtarget->isThumb1Only()) { 12558 // This must be a constant between 0 and 255, for ADD 12559 // immediates. 12560 if (CVal >= 0 && CVal <= 255) 12561 break; 12562 } else if (Subtarget->isThumb2()) { 12563 // A constant that can be used as an immediate value in a 12564 // data-processing instruction. 12565 if (ARM_AM::getT2SOImmVal(CVal) != -1) 12566 break; 12567 } else { 12568 // A constant that can be used as an immediate value in a 12569 // data-processing instruction. 12570 if (ARM_AM::getSOImmVal(CVal) != -1) 12571 break; 12572 } 12573 return; 12574 12575 case 'J': 12576 if (Subtarget->isThumb1Only()) { 12577 // This must be a constant between -255 and -1, for negated ADD 12578 // immediates. This can be used in GCC with an "n" modifier that 12579 // prints the negated value, for use with SUB instructions. It is 12580 // not useful otherwise but is implemented for compatibility. 12581 if (CVal >= -255 && CVal <= -1) 12582 break; 12583 } else { 12584 // This must be a constant between -4095 and 4095. It is not clear 12585 // what this constraint is intended for. Implemented for 12586 // compatibility with GCC. 12587 if (CVal >= -4095 && CVal <= 4095) 12588 break; 12589 } 12590 return; 12591 12592 case 'K': 12593 if (Subtarget->isThumb1Only()) { 12594 // A 32-bit value where only one byte has a nonzero value. Exclude 12595 // zero to match GCC. This constraint is used by GCC internally for 12596 // constants that can be loaded with a move/shift combination. 12597 // It is not useful otherwise but is implemented for compatibility. 12598 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 12599 break; 12600 } else if (Subtarget->isThumb2()) { 12601 // A constant whose bitwise inverse can be used as an immediate 12602 // value in a data-processing instruction. This can be used in GCC 12603 // with a "B" modifier that prints the inverted value, for use with 12604 // BIC and MVN instructions. It is not useful otherwise but is 12605 // implemented for compatibility. 12606 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 12607 break; 12608 } else { 12609 // A constant whose bitwise inverse can be used as an immediate 12610 // value in a data-processing instruction. This can be used in GCC 12611 // with a "B" modifier that prints the inverted value, for use with 12612 // BIC and MVN instructions. It is not useful otherwise but is 12613 // implemented for compatibility. 12614 if (ARM_AM::getSOImmVal(~CVal) != -1) 12615 break; 12616 } 12617 return; 12618 12619 case 'L': 12620 if (Subtarget->isThumb1Only()) { 12621 // This must be a constant between -7 and 7, 12622 // for 3-operand ADD/SUB immediate instructions. 12623 if (CVal >= -7 && CVal < 7) 12624 break; 12625 } else if (Subtarget->isThumb2()) { 12626 // A constant whose negation can be used as an immediate value in a 12627 // data-processing instruction. This can be used in GCC with an "n" 12628 // modifier that prints the negated value, for use with SUB 12629 // instructions. It is not useful otherwise but is implemented for 12630 // compatibility. 12631 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 12632 break; 12633 } else { 12634 // A constant whose negation can be used as an immediate value in a 12635 // data-processing instruction. This can be used in GCC with an "n" 12636 // modifier that prints the negated value, for use with SUB 12637 // instructions. It is not useful otherwise but is implemented for 12638 // compatibility. 12639 if (ARM_AM::getSOImmVal(-CVal) != -1) 12640 break; 12641 } 12642 return; 12643 12644 case 'M': 12645 if (Subtarget->isThumb1Only()) { 12646 // This must be a multiple of 4 between 0 and 1020, for 12647 // ADD sp + immediate. 12648 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 12649 break; 12650 } else { 12651 // A power of two or a constant between 0 and 32. This is used in 12652 // GCC for the shift amount on shifted register operands, but it is 12653 // useful in general for any shift amounts. 12654 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 12655 break; 12656 } 12657 return; 12658 12659 case 'N': 12660 if (Subtarget->isThumb()) { // FIXME thumb2 12661 // This must be a constant between 0 and 31, for shift amounts. 12662 if (CVal >= 0 && CVal <= 31) 12663 break; 12664 } 12665 return; 12666 12667 case 'O': 12668 if (Subtarget->isThumb()) { // FIXME thumb2 12669 // This must be a multiple of 4 between -508 and 508, for 12670 // ADD/SUB sp = sp + immediate. 12671 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 12672 break; 12673 } 12674 return; 12675 } 12676 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 12677 break; 12678 } 12679 12680 if (Result.getNode()) { 12681 Ops.push_back(Result); 12682 return; 12683 } 12684 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12685 } 12686 12687 static RTLIB::Libcall getDivRemLibcall( 12688 const SDNode *N, MVT::SimpleValueType SVT) { 12689 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12690 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12691 "Unhandled Opcode in getDivRemLibcall"); 12692 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12693 N->getOpcode() == ISD::SREM; 12694 RTLIB::Libcall LC; 12695 switch (SVT) { 12696 default: llvm_unreachable("Unexpected request for libcall!"); 12697 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 12698 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 12699 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 12700 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 12701 } 12702 return LC; 12703 } 12704 12705 static TargetLowering::ArgListTy getDivRemArgList( 12706 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 12707 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 12708 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 12709 "Unhandled Opcode in getDivRemArgList"); 12710 bool isSigned = N->getOpcode() == ISD::SDIVREM || 12711 N->getOpcode() == ISD::SREM; 12712 TargetLowering::ArgListTy Args; 12713 TargetLowering::ArgListEntry Entry; 12714 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12715 EVT ArgVT = N->getOperand(i).getValueType(); 12716 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 12717 Entry.Node = N->getOperand(i); 12718 Entry.Ty = ArgTy; 12719 Entry.isSExt = isSigned; 12720 Entry.isZExt = !isSigned; 12721 Args.push_back(Entry); 12722 } 12723 if (Subtarget->isTargetWindows() && Args.size() >= 2) 12724 std::swap(Args[0], Args[1]); 12725 return Args; 12726 } 12727 12728 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 12729 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 12730 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 12731 Subtarget->isTargetWindows()) && 12732 "Register-based DivRem lowering only"); 12733 unsigned Opcode = Op->getOpcode(); 12734 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 12735 "Invalid opcode for Div/Rem lowering"); 12736 bool isSigned = (Opcode == ISD::SDIVREM); 12737 EVT VT = Op->getValueType(0); 12738 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 12739 SDLoc dl(Op); 12740 12741 // If the target has hardware divide, use divide + multiply + subtract: 12742 // div = a / b 12743 // rem = a - b * div 12744 // return {div, rem} 12745 // This should be lowered into UDIV/SDIV + MLS later on. 12746 if (Subtarget->hasDivide() && Op->getValueType(0).isSimple() && 12747 Op->getSimpleValueType(0) == MVT::i32) { 12748 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 12749 const SDValue Dividend = Op->getOperand(0); 12750 const SDValue Divisor = Op->getOperand(1); 12751 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 12752 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 12753 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 12754 12755 SDValue Values[2] = {Div, Rem}; 12756 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 12757 } 12758 12759 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 12760 VT.getSimpleVT().SimpleTy); 12761 SDValue InChain = DAG.getEntryNode(); 12762 12763 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 12764 DAG.getContext(), 12765 Subtarget); 12766 12767 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 12768 getPointerTy(DAG.getDataLayout())); 12769 12770 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr); 12771 12772 if (Subtarget->isTargetWindows()) 12773 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 12774 12775 TargetLowering::CallLoweringInfo CLI(DAG); 12776 CLI.setDebugLoc(dl).setChain(InChain) 12777 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 12778 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 12779 12780 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 12781 return CallInfo.first; 12782 } 12783 12784 // Lowers REM using divmod helpers 12785 // see RTABI section 4.2/4.3 12786 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 12787 // Build return types (div and rem) 12788 std::vector<Type*> RetTyParams; 12789 Type *RetTyElement; 12790 12791 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 12792 default: llvm_unreachable("Unexpected request for libcall!"); 12793 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 12794 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 12795 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 12796 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 12797 } 12798 12799 RetTyParams.push_back(RetTyElement); 12800 RetTyParams.push_back(RetTyElement); 12801 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 12802 Type *RetTy = StructType::get(*DAG.getContext(), ret); 12803 12804 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 12805 SimpleTy); 12806 SDValue InChain = DAG.getEntryNode(); 12807 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 12808 Subtarget); 12809 bool isSigned = N->getOpcode() == ISD::SREM; 12810 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 12811 getPointerTy(DAG.getDataLayout())); 12812 12813 if (Subtarget->isTargetWindows()) 12814 InChain = WinDBZCheckDenominator(DAG, N, InChain); 12815 12816 // Lower call 12817 CallLoweringInfo CLI(DAG); 12818 CLI.setChain(InChain) 12819 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 12820 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 12821 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 12822 12823 // Return second (rem) result operand (first contains div) 12824 SDNode *ResNode = CallResult.first.getNode(); 12825 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 12826 return ResNode->getOperand(1); 12827 } 12828 12829 SDValue 12830 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 12831 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 12832 SDLoc DL(Op); 12833 12834 // Get the inputs. 12835 SDValue Chain = Op.getOperand(0); 12836 SDValue Size = Op.getOperand(1); 12837 12838 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 12839 DAG.getConstant(2, DL, MVT::i32)); 12840 12841 SDValue Flag; 12842 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 12843 Flag = Chain.getValue(1); 12844 12845 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 12846 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 12847 12848 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 12849 Chain = NewSP.getValue(1); 12850 12851 SDValue Ops[2] = { NewSP, Chain }; 12852 return DAG.getMergeValues(Ops, DL); 12853 } 12854 12855 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 12856 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 12857 "Unexpected type for custom-lowering FP_EXTEND"); 12858 12859 RTLIB::Libcall LC; 12860 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 12861 12862 SDValue SrcVal = Op.getOperand(0); 12863 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 12864 SDLoc(Op)).first; 12865 } 12866 12867 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 12868 assert(Op.getOperand(0).getValueType() == MVT::f64 && 12869 Subtarget->isFPOnlySP() && 12870 "Unexpected type for custom-lowering FP_ROUND"); 12871 12872 RTLIB::Libcall LC; 12873 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 12874 12875 SDValue SrcVal = Op.getOperand(0); 12876 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 12877 SDLoc(Op)).first; 12878 } 12879 12880 bool 12881 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 12882 // The ARM target isn't yet aware of offsets. 12883 return false; 12884 } 12885 12886 bool ARM::isBitFieldInvertedMask(unsigned v) { 12887 if (v == 0xffffffff) 12888 return false; 12889 12890 // there can be 1's on either or both "outsides", all the "inside" 12891 // bits must be 0's 12892 return isShiftedMask_32(~v); 12893 } 12894 12895 /// isFPImmLegal - Returns true if the target can instruction select the 12896 /// specified FP immediate natively. If false, the legalizer will 12897 /// materialize the FP immediate as a load from a constant pool. 12898 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 12899 if (!Subtarget->hasVFP3()) 12900 return false; 12901 if (VT == MVT::f32) 12902 return ARM_AM::getFP32Imm(Imm) != -1; 12903 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 12904 return ARM_AM::getFP64Imm(Imm) != -1; 12905 return false; 12906 } 12907 12908 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 12909 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 12910 /// specified in the intrinsic calls. 12911 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 12912 const CallInst &I, 12913 unsigned Intrinsic) const { 12914 switch (Intrinsic) { 12915 case Intrinsic::arm_neon_vld1: 12916 case Intrinsic::arm_neon_vld2: 12917 case Intrinsic::arm_neon_vld3: 12918 case Intrinsic::arm_neon_vld4: 12919 case Intrinsic::arm_neon_vld2lane: 12920 case Intrinsic::arm_neon_vld3lane: 12921 case Intrinsic::arm_neon_vld4lane: { 12922 Info.opc = ISD::INTRINSIC_W_CHAIN; 12923 // Conservatively set memVT to the entire set of vectors loaded. 12924 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12925 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 12926 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12927 Info.ptrVal = I.getArgOperand(0); 12928 Info.offset = 0; 12929 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12930 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12931 Info.vol = false; // volatile loads with NEON intrinsics not supported 12932 Info.readMem = true; 12933 Info.writeMem = false; 12934 return true; 12935 } 12936 case Intrinsic::arm_neon_vst1: 12937 case Intrinsic::arm_neon_vst2: 12938 case Intrinsic::arm_neon_vst3: 12939 case Intrinsic::arm_neon_vst4: 12940 case Intrinsic::arm_neon_vst2lane: 12941 case Intrinsic::arm_neon_vst3lane: 12942 case Intrinsic::arm_neon_vst4lane: { 12943 Info.opc = ISD::INTRINSIC_VOID; 12944 // Conservatively set memVT to the entire set of vectors stored. 12945 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12946 unsigned NumElts = 0; 12947 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 12948 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 12949 if (!ArgTy->isVectorTy()) 12950 break; 12951 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 12952 } 12953 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 12954 Info.ptrVal = I.getArgOperand(0); 12955 Info.offset = 0; 12956 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 12957 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 12958 Info.vol = false; // volatile stores with NEON intrinsics not supported 12959 Info.readMem = false; 12960 Info.writeMem = true; 12961 return true; 12962 } 12963 case Intrinsic::arm_ldaex: 12964 case Intrinsic::arm_ldrex: { 12965 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12966 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 12967 Info.opc = ISD::INTRINSIC_W_CHAIN; 12968 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12969 Info.ptrVal = I.getArgOperand(0); 12970 Info.offset = 0; 12971 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12972 Info.vol = true; 12973 Info.readMem = true; 12974 Info.writeMem = false; 12975 return true; 12976 } 12977 case Intrinsic::arm_stlex: 12978 case Intrinsic::arm_strex: { 12979 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 12980 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 12981 Info.opc = ISD::INTRINSIC_W_CHAIN; 12982 Info.memVT = MVT::getVT(PtrTy->getElementType()); 12983 Info.ptrVal = I.getArgOperand(1); 12984 Info.offset = 0; 12985 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 12986 Info.vol = true; 12987 Info.readMem = false; 12988 Info.writeMem = true; 12989 return true; 12990 } 12991 case Intrinsic::arm_stlexd: 12992 case Intrinsic::arm_strexd: 12993 Info.opc = ISD::INTRINSIC_W_CHAIN; 12994 Info.memVT = MVT::i64; 12995 Info.ptrVal = I.getArgOperand(2); 12996 Info.offset = 0; 12997 Info.align = 8; 12998 Info.vol = true; 12999 Info.readMem = false; 13000 Info.writeMem = true; 13001 return true; 13002 13003 case Intrinsic::arm_ldaexd: 13004 case Intrinsic::arm_ldrexd: 13005 Info.opc = ISD::INTRINSIC_W_CHAIN; 13006 Info.memVT = MVT::i64; 13007 Info.ptrVal = I.getArgOperand(0); 13008 Info.offset = 0; 13009 Info.align = 8; 13010 Info.vol = true; 13011 Info.readMem = true; 13012 Info.writeMem = false; 13013 return true; 13014 13015 default: 13016 break; 13017 } 13018 13019 return false; 13020 } 13021 13022 /// \brief Returns true if it is beneficial to convert a load of a constant 13023 /// to just the constant itself. 13024 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13025 Type *Ty) const { 13026 assert(Ty->isIntegerTy()); 13027 13028 unsigned Bits = Ty->getPrimitiveSizeInBits(); 13029 if (Bits == 0 || Bits > 32) 13030 return false; 13031 return true; 13032 } 13033 13034 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, 13035 unsigned Index) const { 13036 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 13037 return false; 13038 13039 return (Index == 0 || Index == ResVT.getVectorNumElements()); 13040 } 13041 13042 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 13043 ARM_MB::MemBOpt Domain) const { 13044 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13045 13046 // First, if the target has no DMB, see what fallback we can use. 13047 if (!Subtarget->hasDataBarrier()) { 13048 // Some ARMv6 cpus can support data barriers with an mcr instruction. 13049 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 13050 // here. 13051 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 13052 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 13053 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 13054 Builder.getInt32(0), Builder.getInt32(7), 13055 Builder.getInt32(10), Builder.getInt32(5)}; 13056 return Builder.CreateCall(MCR, args); 13057 } else { 13058 // Instead of using barriers, atomic accesses on these subtargets use 13059 // libcalls. 13060 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 13061 } 13062 } else { 13063 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 13064 // Only a full system barrier exists in the M-class architectures. 13065 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 13066 Constant *CDomain = Builder.getInt32(Domain); 13067 return Builder.CreateCall(DMB, CDomain); 13068 } 13069 } 13070 13071 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 13072 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 13073 AtomicOrdering Ord, bool IsStore, 13074 bool IsLoad) const { 13075 switch (Ord) { 13076 case AtomicOrdering::NotAtomic: 13077 case AtomicOrdering::Unordered: 13078 llvm_unreachable("Invalid fence: unordered/non-atomic"); 13079 case AtomicOrdering::Monotonic: 13080 case AtomicOrdering::Acquire: 13081 return nullptr; // Nothing to do 13082 case AtomicOrdering::SequentiallyConsistent: 13083 if (!IsStore) 13084 return nullptr; // Nothing to do 13085 /*FALLTHROUGH*/ 13086 case AtomicOrdering::Release: 13087 case AtomicOrdering::AcquireRelease: 13088 if (Subtarget->preferISHSTBarriers()) 13089 return makeDMB(Builder, ARM_MB::ISHST); 13090 // FIXME: add a comment with a link to documentation justifying this. 13091 else 13092 return makeDMB(Builder, ARM_MB::ISH); 13093 } 13094 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 13095 } 13096 13097 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 13098 AtomicOrdering Ord, bool IsStore, 13099 bool IsLoad) const { 13100 switch (Ord) { 13101 case AtomicOrdering::NotAtomic: 13102 case AtomicOrdering::Unordered: 13103 llvm_unreachable("Invalid fence: unordered/not-atomic"); 13104 case AtomicOrdering::Monotonic: 13105 case AtomicOrdering::Release: 13106 return nullptr; // Nothing to do 13107 case AtomicOrdering::Acquire: 13108 case AtomicOrdering::AcquireRelease: 13109 case AtomicOrdering::SequentiallyConsistent: 13110 return makeDMB(Builder, ARM_MB::ISH); 13111 } 13112 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 13113 } 13114 13115 // Loads and stores less than 64-bits are already atomic; ones above that 13116 // are doomed anyway, so defer to the default libcall and blame the OS when 13117 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13118 // anything for those. 13119 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 13120 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 13121 return (Size == 64) && !Subtarget->isMClass(); 13122 } 13123 13124 // Loads and stores less than 64-bits are already atomic; ones above that 13125 // are doomed anyway, so defer to the default libcall and blame the OS when 13126 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13127 // anything for those. 13128 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 13129 // guarantee, see DDI0406C ARM architecture reference manual, 13130 // sections A8.8.72-74 LDRD) 13131 TargetLowering::AtomicExpansionKind 13132 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 13133 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 13134 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 13135 : AtomicExpansionKind::None; 13136 } 13137 13138 // For the real atomic operations, we have ldrex/strex up to 32 bits, 13139 // and up to 64 bits on the non-M profiles 13140 TargetLowering::AtomicExpansionKind 13141 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 13142 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 13143 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13144 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 13145 ? AtomicExpansionKind::LLSC 13146 : AtomicExpansionKind::None; 13147 } 13148 13149 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 13150 AtomicCmpXchgInst *AI) const { 13151 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 13152 // implement cmpxchg without spilling. If the address being exchanged is also 13153 // on the stack and close enough to the spill slot, this can lead to a 13154 // situation where the monitor always gets cleared and the atomic operation 13155 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 13156 bool hasAtomicCmpXchg = 13157 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13158 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 13159 } 13160 13161 bool ARMTargetLowering::shouldInsertFencesForAtomic( 13162 const Instruction *I) const { 13163 return InsertFencesForAtomic; 13164 } 13165 13166 // This has so far only been implemented for MachO. 13167 bool ARMTargetLowering::useLoadStackGuardNode() const { 13168 return Subtarget->isTargetMachO(); 13169 } 13170 13171 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 13172 unsigned &Cost) const { 13173 // If we do not have NEON, vector types are not natively supported. 13174 if (!Subtarget->hasNEON()) 13175 return false; 13176 13177 // Floating point values and vector values map to the same register file. 13178 // Therefore, although we could do a store extract of a vector type, this is 13179 // better to leave at float as we have more freedom in the addressing mode for 13180 // those. 13181 if (VectorTy->isFPOrFPVectorTy()) 13182 return false; 13183 13184 // If the index is unknown at compile time, this is very expensive to lower 13185 // and it is not possible to combine the store with the extract. 13186 if (!isa<ConstantInt>(Idx)) 13187 return false; 13188 13189 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 13190 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 13191 // We can do a store + vector extract on any vector that fits perfectly in a D 13192 // or Q register. 13193 if (BitWidth == 64 || BitWidth == 128) { 13194 Cost = 0; 13195 return true; 13196 } 13197 return false; 13198 } 13199 13200 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 13201 return Subtarget->hasV6T2Ops(); 13202 } 13203 13204 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 13205 return Subtarget->hasV6T2Ops(); 13206 } 13207 13208 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 13209 AtomicOrdering Ord) const { 13210 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13211 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 13212 bool IsAcquire = isAcquireOrStronger(Ord); 13213 13214 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 13215 // intrinsic must return {i32, i32} and we have to recombine them into a 13216 // single i64 here. 13217 if (ValTy->getPrimitiveSizeInBits() == 64) { 13218 Intrinsic::ID Int = 13219 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 13220 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 13221 13222 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13223 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 13224 13225 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 13226 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 13227 if (!Subtarget->isLittle()) 13228 std::swap (Lo, Hi); 13229 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 13230 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 13231 return Builder.CreateOr( 13232 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 13233 } 13234 13235 Type *Tys[] = { Addr->getType() }; 13236 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 13237 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 13238 13239 return Builder.CreateTruncOrBitCast( 13240 Builder.CreateCall(Ldrex, Addr), 13241 cast<PointerType>(Addr->getType())->getElementType()); 13242 } 13243 13244 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 13245 IRBuilder<> &Builder) const { 13246 if (!Subtarget->hasV7Ops()) 13247 return; 13248 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13249 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 13250 } 13251 13252 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 13253 Value *Addr, 13254 AtomicOrdering Ord) const { 13255 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13256 bool IsRelease = isReleaseOrStronger(Ord); 13257 13258 // Since the intrinsics must have legal type, the i64 intrinsics take two 13259 // parameters: "i32, i32". We must marshal Val into the appropriate form 13260 // before the call. 13261 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 13262 Intrinsic::ID Int = 13263 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 13264 Function *Strex = Intrinsic::getDeclaration(M, Int); 13265 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 13266 13267 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 13268 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 13269 if (!Subtarget->isLittle()) 13270 std::swap (Lo, Hi); 13271 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13272 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 13273 } 13274 13275 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 13276 Type *Tys[] = { Addr->getType() }; 13277 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 13278 13279 return Builder.CreateCall( 13280 Strex, {Builder.CreateZExtOrBitCast( 13281 Val, Strex->getFunctionType()->getParamType(0)), 13282 Addr}); 13283 } 13284 13285 /// \brief Lower an interleaved load into a vldN intrinsic. 13286 /// 13287 /// E.g. Lower an interleaved load (Factor = 2): 13288 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 13289 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 13290 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 13291 /// 13292 /// Into: 13293 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 13294 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 13295 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 13296 bool ARMTargetLowering::lowerInterleavedLoad( 13297 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 13298 ArrayRef<unsigned> Indices, unsigned Factor) const { 13299 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 13300 "Invalid interleave factor"); 13301 assert(!Shuffles.empty() && "Empty shufflevector input"); 13302 assert(Shuffles.size() == Indices.size() && 13303 "Unmatched number of shufflevectors and indices"); 13304 13305 VectorType *VecTy = Shuffles[0]->getType(); 13306 Type *EltTy = VecTy->getVectorElementType(); 13307 13308 const DataLayout &DL = LI->getModule()->getDataLayout(); 13309 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 13310 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 13311 13312 // Skip if we do not have NEON and skip illegal vector types and vector types 13313 // with i64/f64 elements (vldN doesn't support i64/f64 elements). 13314 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits) 13315 return false; 13316 13317 // Skip if the vector has f16 elements: even though we could do an i16 vldN, 13318 // we can't hold the f16 vectors and will end up converting via f32. 13319 if (EltTy->isHalfTy()) 13320 return false; 13321 13322 // A pointer vector can not be the return type of the ldN intrinsics. Need to 13323 // load integer vectors first and then convert to pointer vectors. 13324 if (EltTy->isPointerTy()) 13325 VecTy = 13326 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 13327 13328 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 13329 Intrinsic::arm_neon_vld3, 13330 Intrinsic::arm_neon_vld4}; 13331 13332 IRBuilder<> Builder(LI); 13333 SmallVector<Value *, 2> Ops; 13334 13335 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 13336 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr)); 13337 Ops.push_back(Builder.getInt32(LI->getAlignment())); 13338 13339 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 13340 13341 Type *Tys[] = { VecTy, Int8Ptr }; 13342 Function *VldnFunc = 13343 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 13344 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 13345 13346 // Replace uses of each shufflevector with the corresponding vector loaded 13347 // by ldN. 13348 for (unsigned i = 0; i < Shuffles.size(); i++) { 13349 ShuffleVectorInst *SV = Shuffles[i]; 13350 unsigned Index = Indices[i]; 13351 13352 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 13353 13354 // Convert the integer vector to pointer vector if the element is pointer. 13355 if (EltTy->isPointerTy()) 13356 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType()); 13357 13358 SV->replaceAllUsesWith(SubVec); 13359 } 13360 13361 return true; 13362 } 13363 13364 /// \brief Lower an interleaved store into a vstN intrinsic. 13365 /// 13366 /// E.g. Lower an interleaved store (Factor = 3): 13367 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 13368 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 13369 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 13370 /// 13371 /// Into: 13372 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 13373 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 13374 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 13375 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 13376 /// 13377 /// Note that the new shufflevectors will be removed and we'll only generate one 13378 /// vst3 instruction in CodeGen. 13379 /// 13380 /// Example for a more general valid mask (Factor 3). Lower: 13381 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 13382 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 13383 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 13384 /// 13385 /// Into: 13386 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 13387 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 13388 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 13389 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 13390 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 13391 ShuffleVectorInst *SVI, 13392 unsigned Factor) const { 13393 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 13394 "Invalid interleave factor"); 13395 13396 VectorType *VecTy = SVI->getType(); 13397 assert(VecTy->getVectorNumElements() % Factor == 0 && 13398 "Invalid interleaved store"); 13399 13400 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 13401 Type *EltTy = VecTy->getVectorElementType(); 13402 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 13403 13404 const DataLayout &DL = SI->getModule()->getDataLayout(); 13405 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 13406 bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64; 13407 13408 // Skip if we do not have NEON and skip illegal vector types and vector types 13409 // with i64/f64 elements (vstN doesn't support i64/f64 elements). 13410 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) || 13411 EltIs64Bits) 13412 return false; 13413 13414 // Skip if the vector has f16 elements: even though we could do an i16 vldN, 13415 // we can't hold the f16 vectors and will end up converting via f32. 13416 if (EltTy->isHalfTy()) 13417 return false; 13418 13419 Value *Op0 = SVI->getOperand(0); 13420 Value *Op1 = SVI->getOperand(1); 13421 IRBuilder<> Builder(SI); 13422 13423 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 13424 // vectors to integer vectors. 13425 if (EltTy->isPointerTy()) { 13426 Type *IntTy = DL.getIntPtrType(EltTy); 13427 13428 // Convert to the corresponding integer vector. 13429 Type *IntVecTy = 13430 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 13431 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 13432 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 13433 13434 SubVecTy = VectorType::get(IntTy, LaneLen); 13435 } 13436 13437 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 13438 Intrinsic::arm_neon_vst3, 13439 Intrinsic::arm_neon_vst4}; 13440 SmallVector<Value *, 6> Ops; 13441 13442 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 13443 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr)); 13444 13445 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 13446 13447 Type *Tys[] = { Int8Ptr, SubVecTy }; 13448 Function *VstNFunc = Intrinsic::getDeclaration( 13449 SI->getModule(), StoreInts[Factor - 2], Tys); 13450 13451 // Split the shufflevector operands into sub vectors for the new vstN call. 13452 auto Mask = SVI->getShuffleMask(); 13453 for (unsigned i = 0; i < Factor; i++) { 13454 if (Mask[i] >= 0) { 13455 Ops.push_back(Builder.CreateShuffleVector( 13456 Op0, Op1, createSequentialMask(Builder, Mask[i], LaneLen, 0))); 13457 } else { 13458 unsigned StartMask = 0; 13459 for (unsigned j = 1; j < LaneLen; j++) { 13460 if (Mask[j*Factor + i] >= 0) { 13461 StartMask = Mask[j*Factor + i] - j; 13462 break; 13463 } 13464 } 13465 // Note: If all elements in a chunk are undefs, StartMask=0! 13466 // Note: Filling undef gaps with random elements is ok, since 13467 // those elements were being written anyway (with undefs). 13468 // In the case of all undefs we're defaulting to using elems from 0 13469 // Note: StartMask cannot be negative, it's checked in isReInterleaveMask 13470 Ops.push_back(Builder.CreateShuffleVector( 13471 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 13472 } 13473 } 13474 13475 Ops.push_back(Builder.getInt32(SI->getAlignment())); 13476 Builder.CreateCall(VstNFunc, Ops); 13477 return true; 13478 } 13479 13480 enum HABaseType { 13481 HA_UNKNOWN = 0, 13482 HA_FLOAT, 13483 HA_DOUBLE, 13484 HA_VECT64, 13485 HA_VECT128 13486 }; 13487 13488 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 13489 uint64_t &Members) { 13490 if (auto *ST = dyn_cast<StructType>(Ty)) { 13491 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 13492 uint64_t SubMembers = 0; 13493 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 13494 return false; 13495 Members += SubMembers; 13496 } 13497 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 13498 uint64_t SubMembers = 0; 13499 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 13500 return false; 13501 Members += SubMembers * AT->getNumElements(); 13502 } else if (Ty->isFloatTy()) { 13503 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 13504 return false; 13505 Members = 1; 13506 Base = HA_FLOAT; 13507 } else if (Ty->isDoubleTy()) { 13508 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 13509 return false; 13510 Members = 1; 13511 Base = HA_DOUBLE; 13512 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 13513 Members = 1; 13514 switch (Base) { 13515 case HA_FLOAT: 13516 case HA_DOUBLE: 13517 return false; 13518 case HA_VECT64: 13519 return VT->getBitWidth() == 64; 13520 case HA_VECT128: 13521 return VT->getBitWidth() == 128; 13522 case HA_UNKNOWN: 13523 switch (VT->getBitWidth()) { 13524 case 64: 13525 Base = HA_VECT64; 13526 return true; 13527 case 128: 13528 Base = HA_VECT128; 13529 return true; 13530 default: 13531 return false; 13532 } 13533 } 13534 } 13535 13536 return (Members > 0 && Members <= 4); 13537 } 13538 13539 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 13540 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 13541 /// passing according to AAPCS rules. 13542 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 13543 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 13544 if (getEffectiveCallingConv(CallConv, isVarArg) != 13545 CallingConv::ARM_AAPCS_VFP) 13546 return false; 13547 13548 HABaseType Base = HA_UNKNOWN; 13549 uint64_t Members = 0; 13550 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 13551 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 13552 13553 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 13554 return IsHA || IsIntArray; 13555 } 13556 13557 unsigned ARMTargetLowering::getExceptionPointerRegister( 13558 const Constant *PersonalityFn) const { 13559 // Platforms which do not use SjLj EH may return values in these registers 13560 // via the personality function. 13561 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 13562 } 13563 13564 unsigned ARMTargetLowering::getExceptionSelectorRegister( 13565 const Constant *PersonalityFn) const { 13566 // Platforms which do not use SjLj EH may return values in these registers 13567 // via the personality function. 13568 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 13569 } 13570 13571 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13572 // Update IsSplitCSR in ARMFunctionInfo. 13573 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 13574 AFI->setIsSplitCSR(true); 13575 } 13576 13577 void ARMTargetLowering::insertCopiesSplitCSR( 13578 MachineBasicBlock *Entry, 13579 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13580 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 13581 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13582 if (!IStart) 13583 return; 13584 13585 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 13586 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13587 MachineBasicBlock::iterator MBBI = Entry->begin(); 13588 for (const MCPhysReg *I = IStart; *I; ++I) { 13589 const TargetRegisterClass *RC = nullptr; 13590 if (ARM::GPRRegClass.contains(*I)) 13591 RC = &ARM::GPRRegClass; 13592 else if (ARM::DPRRegClass.contains(*I)) 13593 RC = &ARM::DPRRegClass; 13594 else 13595 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13596 13597 unsigned NewVR = MRI->createVirtualRegister(RC); 13598 // Create copy from CSR to a virtual register. 13599 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13600 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13601 // nounwind. If we want to generalize this later, we may need to emit 13602 // CFI pseudo-instructions. 13603 assert(Entry->getParent()->getFunction()->hasFnAttribute( 13604 Attribute::NoUnwind) && 13605 "Function should be nounwind in insertCopiesSplitCSR!"); 13606 Entry->addLiveIn(*I); 13607 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13608 .addReg(*I); 13609 13610 // Insert the copy-back instructions right before the terminator. 13611 for (auto *Exit : Exits) 13612 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13613 TII->get(TargetOpcode::COPY), *I) 13614 .addReg(NewVR); 13615 } 13616 } 13617