1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMISelLowering.h" 16 #include "ARMBaseInstrInfo.h" 17 #include "ARMBaseRegisterInfo.h" 18 #include "ARMCallingConv.h" 19 #include "ARMConstantPoolValue.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 "Utils/ARMBaseInfo.h" 28 #include "llvm/ADT/APFloat.h" 29 #include "llvm/ADT/APInt.h" 30 #include "llvm/ADT/ArrayRef.h" 31 #include "llvm/ADT/BitVector.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallVector.h" 36 #include "llvm/ADT/Statistic.h" 37 #include "llvm/ADT/StringExtras.h" 38 #include "llvm/ADT/StringRef.h" 39 #include "llvm/ADT/StringSwitch.h" 40 #include "llvm/ADT/Triple.h" 41 #include "llvm/ADT/Twine.h" 42 #include "llvm/Analysis/VectorUtils.h" 43 #include "llvm/CodeGen/CallingConvLower.h" 44 #include "llvm/CodeGen/ISDOpcodes.h" 45 #include "llvm/CodeGen/IntrinsicLowering.h" 46 #include "llvm/CodeGen/MachineBasicBlock.h" 47 #include "llvm/CodeGen/MachineConstantPool.h" 48 #include "llvm/CodeGen/MachineFrameInfo.h" 49 #include "llvm/CodeGen/MachineFunction.h" 50 #include "llvm/CodeGen/MachineInstr.h" 51 #include "llvm/CodeGen/MachineInstrBuilder.h" 52 #include "llvm/CodeGen/MachineJumpTableInfo.h" 53 #include "llvm/CodeGen/MachineMemOperand.h" 54 #include "llvm/CodeGen/MachineOperand.h" 55 #include "llvm/CodeGen/MachineRegisterInfo.h" 56 #include "llvm/CodeGen/RuntimeLibcalls.h" 57 #include "llvm/CodeGen/SelectionDAG.h" 58 #include "llvm/CodeGen/SelectionDAGNodes.h" 59 #include "llvm/CodeGen/TargetInstrInfo.h" 60 #include "llvm/CodeGen/TargetLowering.h" 61 #include "llvm/CodeGen/TargetOpcodes.h" 62 #include "llvm/CodeGen/TargetRegisterInfo.h" 63 #include "llvm/CodeGen/TargetSubtargetInfo.h" 64 #include "llvm/CodeGen/ValueTypes.h" 65 #include "llvm/IR/Attributes.h" 66 #include "llvm/IR/CallingConv.h" 67 #include "llvm/IR/Constant.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugLoc.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GlobalAlias.h" 74 #include "llvm/IR/GlobalValue.h" 75 #include "llvm/IR/GlobalVariable.h" 76 #include "llvm/IR/IRBuilder.h" 77 #include "llvm/IR/InlineAsm.h" 78 #include "llvm/IR/Instruction.h" 79 #include "llvm/IR/Instructions.h" 80 #include "llvm/IR/IntrinsicInst.h" 81 #include "llvm/IR/Intrinsics.h" 82 #include "llvm/IR/Module.h" 83 #include "llvm/IR/Type.h" 84 #include "llvm/IR/User.h" 85 #include "llvm/IR/Value.h" 86 #include "llvm/MC/MCInstrDesc.h" 87 #include "llvm/MC/MCInstrItineraries.h" 88 #include "llvm/MC/MCRegisterInfo.h" 89 #include "llvm/MC/MCSchedule.h" 90 #include "llvm/Support/AtomicOrdering.h" 91 #include "llvm/Support/BranchProbability.h" 92 #include "llvm/Support/Casting.h" 93 #include "llvm/Support/CodeGen.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/ErrorHandling.h" 98 #include "llvm/Support/KnownBits.h" 99 #include "llvm/Support/MachineValueType.h" 100 #include "llvm/Support/MathExtras.h" 101 #include "llvm/Support/raw_ostream.h" 102 #include "llvm/Target/TargetMachine.h" 103 #include "llvm/Target/TargetOptions.h" 104 #include <algorithm> 105 #include <cassert> 106 #include <cstdint> 107 #include <cstdlib> 108 #include <iterator> 109 #include <limits> 110 #include <string> 111 #include <tuple> 112 #include <utility> 113 #include <vector> 114 115 using namespace llvm; 116 117 #define DEBUG_TYPE "arm-isel" 118 119 STATISTIC(NumTailCalls, "Number of tail calls"); 120 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 121 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 122 STATISTIC(NumConstpoolPromoted, 123 "Number of constants with their storage promoted into constant pools"); 124 125 static cl::opt<bool> 126 ARMInterworking("arm-interworking", cl::Hidden, 127 cl::desc("Enable / disable ARM interworking (for debugging only)"), 128 cl::init(true)); 129 130 static cl::opt<bool> EnableConstpoolPromotion( 131 "arm-promote-constant", cl::Hidden, 132 cl::desc("Enable / disable promotion of unnamed_addr constants into " 133 "constant pools"), 134 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed 135 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 136 "arm-promote-constant-max-size", cl::Hidden, 137 cl::desc("Maximum size of constant to promote into a constant pool"), 138 cl::init(64)); 139 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 140 "arm-promote-constant-max-total", cl::Hidden, 141 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 142 cl::init(128)); 143 144 // The APCS parameter registers. 145 static const MCPhysReg GPRArgRegs[] = { 146 ARM::R0, ARM::R1, ARM::R2, ARM::R3 147 }; 148 149 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 150 MVT PromotedBitwiseVT) { 151 if (VT != PromotedLdStVT) { 152 setOperationAction(ISD::LOAD, VT, Promote); 153 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 154 155 setOperationAction(ISD::STORE, VT, Promote); 156 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 157 } 158 159 MVT ElemTy = VT.getVectorElementType(); 160 if (ElemTy != MVT::f64) 161 setOperationAction(ISD::SETCC, VT, Custom); 162 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 163 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 164 if (ElemTy == MVT::i32) { 165 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 166 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 167 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 168 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 169 } else { 170 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 171 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 172 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 173 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 174 } 175 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 176 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 177 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 178 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 179 setOperationAction(ISD::SELECT, VT, Expand); 180 setOperationAction(ISD::SELECT_CC, VT, Expand); 181 setOperationAction(ISD::VSELECT, VT, Expand); 182 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 183 if (VT.isInteger()) { 184 setOperationAction(ISD::SHL, VT, Custom); 185 setOperationAction(ISD::SRA, VT, Custom); 186 setOperationAction(ISD::SRL, VT, Custom); 187 } 188 189 // Promote all bit-wise operations. 190 if (VT.isInteger() && VT != PromotedBitwiseVT) { 191 setOperationAction(ISD::AND, VT, Promote); 192 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 193 setOperationAction(ISD::OR, VT, Promote); 194 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 195 setOperationAction(ISD::XOR, VT, Promote); 196 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 197 } 198 199 // Neon does not support vector divide/remainder operations. 200 setOperationAction(ISD::SDIV, VT, Expand); 201 setOperationAction(ISD::UDIV, VT, Expand); 202 setOperationAction(ISD::FDIV, VT, Expand); 203 setOperationAction(ISD::SREM, VT, Expand); 204 setOperationAction(ISD::UREM, VT, Expand); 205 setOperationAction(ISD::FREM, VT, Expand); 206 207 if (!VT.isFloatingPoint() && 208 VT != MVT::v2i64 && VT != MVT::v1i64) 209 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 210 setOperationAction(Opcode, VT, Legal); 211 } 212 213 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 214 addRegisterClass(VT, &ARM::DPRRegClass); 215 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 216 } 217 218 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 219 addRegisterClass(VT, &ARM::DPairRegClass); 220 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 221 } 222 223 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 224 const ARMSubtarget &STI) 225 : TargetLowering(TM), Subtarget(&STI) { 226 RegInfo = Subtarget->getRegisterInfo(); 227 Itins = Subtarget->getInstrItineraryData(); 228 229 setBooleanContents(ZeroOrOneBooleanContent); 230 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 231 232 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 233 !Subtarget->isTargetWatchOS()) { 234 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 235 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 236 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 237 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 238 : CallingConv::ARM_AAPCS); 239 } 240 241 if (Subtarget->isTargetMachO()) { 242 // Uses VFP for Thumb libfuncs if available. 243 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 244 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 245 static const struct { 246 const RTLIB::Libcall Op; 247 const char * const Name; 248 const ISD::CondCode Cond; 249 } LibraryCalls[] = { 250 // Single-precision floating-point arithmetic. 251 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 252 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 253 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 254 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 255 256 // Double-precision floating-point arithmetic. 257 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 258 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 259 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 260 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 261 262 // Single-precision comparisons. 263 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 264 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 265 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 266 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 267 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 268 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 269 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 270 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 271 272 // Double-precision comparisons. 273 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 274 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 275 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 276 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 277 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 278 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 279 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 280 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 281 282 // Floating-point to integer conversions. 283 // i64 conversions are done via library routines even when generating VFP 284 // instructions, so use the same ones. 285 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 286 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 287 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 288 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 289 290 // Conversions between floating types. 291 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 292 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 293 294 // Integer to floating-point conversions. 295 // i64 conversions are done via library routines even when generating VFP 296 // instructions, so use the same ones. 297 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 298 // e.g., __floatunsidf vs. __floatunssidfvfp. 299 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 300 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 301 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 302 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 303 }; 304 305 for (const auto &LC : LibraryCalls) { 306 setLibcallName(LC.Op, LC.Name); 307 if (LC.Cond != ISD::SETCC_INVALID) 308 setCmpLibcallCC(LC.Op, LC.Cond); 309 } 310 } 311 312 // Set the correct calling convention for ARMv7k WatchOS. It's just 313 // AAPCS_VFP for functions as simple as libcalls. 314 if (Subtarget->isTargetWatchABI()) { 315 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 316 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 317 } 318 } 319 320 // These libcalls are not available in 32-bit. 321 setLibcallName(RTLIB::SHL_I128, nullptr); 322 setLibcallName(RTLIB::SRL_I128, nullptr); 323 setLibcallName(RTLIB::SRA_I128, nullptr); 324 325 // RTLIB 326 if (Subtarget->isAAPCS_ABI() && 327 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 328 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 329 static const struct { 330 const RTLIB::Libcall Op; 331 const char * const Name; 332 const CallingConv::ID CC; 333 const ISD::CondCode Cond; 334 } LibraryCalls[] = { 335 // Double-precision floating-point arithmetic helper functions 336 // RTABI chapter 4.1.2, Table 2 337 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 338 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 342 // Double-precision floating-point comparison helper functions 343 // RTABI chapter 4.1.2, Table 3 344 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 345 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 346 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 347 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 348 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 349 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 350 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 351 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 352 353 // Single-precision floating-point arithmetic helper functions 354 // RTABI chapter 4.1.2, Table 4 355 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 356 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 357 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 358 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 359 360 // Single-precision floating-point comparison helper functions 361 // RTABI chapter 4.1.2, Table 5 362 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 363 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 364 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 365 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 366 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 367 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 368 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 369 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 370 371 // Floating-point to integer conversions. 372 // RTABI chapter 4.1.2, Table 6 373 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 374 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 375 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 376 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 377 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 378 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 379 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 380 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 381 382 // Conversions between floating types. 383 // RTABI chapter 4.1.2, Table 7 384 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 385 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 386 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 387 388 // Integer to floating-point conversions. 389 // RTABI chapter 4.1.2, Table 8 390 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 391 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 392 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 393 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 394 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 395 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 396 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 397 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 398 399 // Long long helper functions 400 // RTABI chapter 4.2, Table 9 401 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 402 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 403 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 404 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 405 406 // Integer division functions 407 // RTABI chapter 4.3.1 408 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 409 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 410 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 411 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 412 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 413 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 414 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 415 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 416 }; 417 418 for (const auto &LC : LibraryCalls) { 419 setLibcallName(LC.Op, LC.Name); 420 setLibcallCallingConv(LC.Op, LC.CC); 421 if (LC.Cond != ISD::SETCC_INVALID) 422 setCmpLibcallCC(LC.Op, LC.Cond); 423 } 424 425 // EABI dependent RTLIB 426 if (TM.Options.EABIVersion == EABI::EABI4 || 427 TM.Options.EABIVersion == EABI::EABI5) { 428 static const struct { 429 const RTLIB::Libcall Op; 430 const char *const Name; 431 const CallingConv::ID CC; 432 const ISD::CondCode Cond; 433 } MemOpsLibraryCalls[] = { 434 // Memory operations 435 // RTABI chapter 4.3.4 436 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 437 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 438 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 439 }; 440 441 for (const auto &LC : MemOpsLibraryCalls) { 442 setLibcallName(LC.Op, LC.Name); 443 setLibcallCallingConv(LC.Op, LC.CC); 444 if (LC.Cond != ISD::SETCC_INVALID) 445 setCmpLibcallCC(LC.Op, LC.Cond); 446 } 447 } 448 } 449 450 if (Subtarget->isTargetWindows()) { 451 static const struct { 452 const RTLIB::Libcall Op; 453 const char * const Name; 454 const CallingConv::ID CC; 455 } LibraryCalls[] = { 456 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 457 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 458 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 459 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 460 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 461 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 462 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 463 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 464 }; 465 466 for (const auto &LC : LibraryCalls) { 467 setLibcallName(LC.Op, LC.Name); 468 setLibcallCallingConv(LC.Op, LC.CC); 469 } 470 } 471 472 // Use divmod compiler-rt calls for iOS 5.0 and later. 473 if (Subtarget->isTargetMachO() && 474 !(Subtarget->isTargetIOS() && 475 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 476 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 477 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 478 } 479 480 // The half <-> float conversion functions are always soft-float on 481 // non-watchos platforms, but are needed for some targets which use a 482 // hard-float calling convention by default. 483 if (!Subtarget->isTargetWatchABI()) { 484 if (Subtarget->isAAPCS_ABI()) { 485 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 486 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 487 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 488 } else { 489 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 490 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 491 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 492 } 493 } 494 495 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 496 // a __gnu_ prefix (which is the default). 497 if (Subtarget->isTargetAEABI()) { 498 static const struct { 499 const RTLIB::Libcall Op; 500 const char * const Name; 501 const CallingConv::ID CC; 502 } LibraryCalls[] = { 503 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 504 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 505 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 506 }; 507 508 for (const auto &LC : LibraryCalls) { 509 setLibcallName(LC.Op, LC.Name); 510 setLibcallCallingConv(LC.Op, LC.CC); 511 } 512 } 513 514 if (Subtarget->isThumb1Only()) 515 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 516 else 517 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 518 519 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 520 !Subtarget->isThumb1Only()) { 521 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 522 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 523 } 524 525 if (Subtarget->hasFullFP16()) { 526 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 527 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 528 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 529 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 530 531 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 532 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 533 } 534 535 for (MVT VT : MVT::vector_valuetypes()) { 536 for (MVT InnerVT : MVT::vector_valuetypes()) { 537 setTruncStoreAction(VT, InnerVT, Expand); 538 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 539 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 540 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 541 } 542 543 setOperationAction(ISD::MULHS, VT, Expand); 544 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 545 setOperationAction(ISD::MULHU, VT, Expand); 546 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 547 548 setOperationAction(ISD::BSWAP, VT, Expand); 549 } 550 551 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 552 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 553 554 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 555 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 556 557 if (Subtarget->hasNEON()) { 558 addDRTypeForNEON(MVT::v2f32); 559 addDRTypeForNEON(MVT::v8i8); 560 addDRTypeForNEON(MVT::v4i16); 561 addDRTypeForNEON(MVT::v2i32); 562 addDRTypeForNEON(MVT::v1i64); 563 564 addQRTypeForNEON(MVT::v4f32); 565 addQRTypeForNEON(MVT::v2f64); 566 addQRTypeForNEON(MVT::v16i8); 567 addQRTypeForNEON(MVT::v8i16); 568 addQRTypeForNEON(MVT::v4i32); 569 addQRTypeForNEON(MVT::v2i64); 570 571 if (Subtarget->hasFullFP16()) { 572 addQRTypeForNEON(MVT::v8f16); 573 addDRTypeForNEON(MVT::v4f16); 574 } 575 576 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 577 // neither Neon nor VFP support any arithmetic operations on it. 578 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 579 // supported for v4f32. 580 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 581 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 582 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 583 // FIXME: Code duplication: FDIV and FREM are expanded always, see 584 // ARMTargetLowering::addTypeForNEON method for details. 585 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 586 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 587 // FIXME: Create unittest. 588 // In another words, find a way when "copysign" appears in DAG with vector 589 // operands. 590 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 591 // FIXME: Code duplication: SETCC has custom operation action, see 592 // ARMTargetLowering::addTypeForNEON method for details. 593 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 594 // FIXME: Create unittest for FNEG and for FABS. 595 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 596 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 597 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 598 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 599 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 600 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 601 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 602 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 603 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 604 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 605 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 606 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 607 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 608 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 609 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 610 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 611 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 612 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 613 614 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 615 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 616 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 617 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 618 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 619 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 620 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 621 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 622 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 623 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 624 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 625 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 626 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 627 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 628 629 // Mark v2f32 intrinsics. 630 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 631 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 632 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 633 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 634 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 635 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 636 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 637 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 638 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 639 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 640 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 641 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 642 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 643 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 644 645 // Neon does not support some operations on v1i64 and v2i64 types. 646 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 647 // Custom handling for some quad-vector types to detect VMULL. 648 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 649 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 650 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 651 // Custom handling for some vector types to avoid expensive expansions 652 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 653 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 654 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 655 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 656 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 657 // a destination type that is wider than the source, and nor does 658 // it have a FP_TO_[SU]INT instruction with a narrower destination than 659 // source. 660 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 661 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 662 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 663 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 664 665 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 666 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 667 668 // NEON does not have single instruction CTPOP for vectors with element 669 // types wider than 8-bits. However, custom lowering can leverage the 670 // v8i8/v16i8 vcnt instruction. 671 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 672 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 673 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 674 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 675 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 676 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 677 678 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 679 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 680 681 // NEON does not have single instruction CTTZ for vectors. 682 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 683 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 684 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 685 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 686 687 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 688 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 689 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 690 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 691 692 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 693 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 694 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 695 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 696 697 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 698 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 699 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 700 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 701 702 // NEON only has FMA instructions as of VFP4. 703 if (!Subtarget->hasVFP4()) { 704 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 705 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 706 } 707 708 setTargetDAGCombine(ISD::INTRINSIC_VOID); 709 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 710 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 711 setTargetDAGCombine(ISD::SHL); 712 setTargetDAGCombine(ISD::SRL); 713 setTargetDAGCombine(ISD::SRA); 714 setTargetDAGCombine(ISD::SIGN_EXTEND); 715 setTargetDAGCombine(ISD::ZERO_EXTEND); 716 setTargetDAGCombine(ISD::ANY_EXTEND); 717 setTargetDAGCombine(ISD::BUILD_VECTOR); 718 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 719 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 720 setTargetDAGCombine(ISD::STORE); 721 setTargetDAGCombine(ISD::FP_TO_SINT); 722 setTargetDAGCombine(ISD::FP_TO_UINT); 723 setTargetDAGCombine(ISD::FDIV); 724 setTargetDAGCombine(ISD::LOAD); 725 726 // It is legal to extload from v4i8 to v4i16 or v4i32. 727 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 728 MVT::v2i32}) { 729 for (MVT VT : MVT::integer_vector_valuetypes()) { 730 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 731 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 732 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 733 } 734 } 735 } 736 737 if (Subtarget->isFPOnlySP()) { 738 // When targeting a floating-point unit with only single-precision 739 // operations, f64 is legal for the few double-precision instructions which 740 // are present However, no double-precision operations other than moves, 741 // loads and stores are provided by the hardware. 742 setOperationAction(ISD::FADD, MVT::f64, Expand); 743 setOperationAction(ISD::FSUB, MVT::f64, Expand); 744 setOperationAction(ISD::FMUL, MVT::f64, Expand); 745 setOperationAction(ISD::FMA, MVT::f64, Expand); 746 setOperationAction(ISD::FDIV, MVT::f64, Expand); 747 setOperationAction(ISD::FREM, MVT::f64, Expand); 748 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 749 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 750 setOperationAction(ISD::FNEG, MVT::f64, Expand); 751 setOperationAction(ISD::FABS, MVT::f64, Expand); 752 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 753 setOperationAction(ISD::FSIN, MVT::f64, Expand); 754 setOperationAction(ISD::FCOS, MVT::f64, Expand); 755 setOperationAction(ISD::FPOW, MVT::f64, Expand); 756 setOperationAction(ISD::FLOG, MVT::f64, Expand); 757 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 758 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 759 setOperationAction(ISD::FEXP, MVT::f64, Expand); 760 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 761 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 762 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 763 setOperationAction(ISD::FRINT, MVT::f64, Expand); 764 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 765 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 766 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 767 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 768 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 769 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 770 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 771 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 772 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 773 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 774 } 775 776 computeRegisterProperties(Subtarget->getRegisterInfo()); 777 778 // ARM does not have floating-point extending loads. 779 for (MVT VT : MVT::fp_valuetypes()) { 780 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 781 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 782 } 783 784 // ... or truncating stores 785 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 786 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 787 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 788 789 // ARM does not have i1 sign extending load. 790 for (MVT VT : MVT::integer_valuetypes()) 791 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 792 793 // ARM supports all 4 flavors of integer indexed load / store. 794 if (!Subtarget->isThumb1Only()) { 795 for (unsigned im = (unsigned)ISD::PRE_INC; 796 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 797 setIndexedLoadAction(im, MVT::i1, Legal); 798 setIndexedLoadAction(im, MVT::i8, Legal); 799 setIndexedLoadAction(im, MVT::i16, Legal); 800 setIndexedLoadAction(im, MVT::i32, Legal); 801 setIndexedStoreAction(im, MVT::i1, Legal); 802 setIndexedStoreAction(im, MVT::i8, Legal); 803 setIndexedStoreAction(im, MVT::i16, Legal); 804 setIndexedStoreAction(im, MVT::i32, Legal); 805 } 806 } else { 807 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 808 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 809 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 810 } 811 812 setOperationAction(ISD::SADDO, MVT::i32, Custom); 813 setOperationAction(ISD::UADDO, MVT::i32, Custom); 814 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 815 setOperationAction(ISD::USUBO, MVT::i32, Custom); 816 817 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 818 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 819 820 // i64 operation support. 821 setOperationAction(ISD::MUL, MVT::i64, Expand); 822 setOperationAction(ISD::MULHU, MVT::i32, Expand); 823 if (Subtarget->isThumb1Only()) { 824 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 825 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 826 } 827 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 828 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 829 setOperationAction(ISD::MULHS, MVT::i32, Expand); 830 831 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 832 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 833 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 834 setOperationAction(ISD::SRL, MVT::i64, Custom); 835 setOperationAction(ISD::SRA, MVT::i64, Custom); 836 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 837 838 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 839 if (Subtarget->isThumb1Only()) { 840 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 841 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 842 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 843 } 844 845 setOperationAction(ISD::ADDC, MVT::i32, Custom); 846 setOperationAction(ISD::ADDE, MVT::i32, Custom); 847 setOperationAction(ISD::SUBC, MVT::i32, Custom); 848 setOperationAction(ISD::SUBE, MVT::i32, Custom); 849 850 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 851 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 852 853 // ARM does not have ROTL. 854 setOperationAction(ISD::ROTL, MVT::i32, Expand); 855 for (MVT VT : MVT::vector_valuetypes()) { 856 setOperationAction(ISD::ROTL, VT, Expand); 857 setOperationAction(ISD::ROTR, VT, Expand); 858 } 859 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 860 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 861 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 862 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 863 864 // @llvm.readcyclecounter requires the Performance Monitors extension. 865 // Default to the 0 expansion on unsupported platforms. 866 // FIXME: Technically there are older ARM CPUs that have 867 // implementation-specific ways of obtaining this information. 868 if (Subtarget->hasPerfMon()) 869 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 870 871 // Only ARMv6 has BSWAP. 872 if (!Subtarget->hasV6Ops()) 873 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 874 875 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 876 : Subtarget->hasDivideInARMMode(); 877 if (!hasDivide) { 878 // These are expanded into libcalls if the cpu doesn't have HW divider. 879 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 880 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 881 } 882 883 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 884 setOperationAction(ISD::SDIV, MVT::i32, Custom); 885 setOperationAction(ISD::UDIV, MVT::i32, Custom); 886 887 setOperationAction(ISD::SDIV, MVT::i64, Custom); 888 setOperationAction(ISD::UDIV, MVT::i64, Custom); 889 } 890 891 setOperationAction(ISD::SREM, MVT::i32, Expand); 892 setOperationAction(ISD::UREM, MVT::i32, Expand); 893 894 // Register based DivRem for AEABI (RTABI 4.2) 895 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 896 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 897 Subtarget->isTargetWindows()) { 898 setOperationAction(ISD::SREM, MVT::i64, Custom); 899 setOperationAction(ISD::UREM, MVT::i64, Custom); 900 HasStandaloneRem = false; 901 902 if (Subtarget->isTargetWindows()) { 903 const struct { 904 const RTLIB::Libcall Op; 905 const char * const Name; 906 const CallingConv::ID CC; 907 } LibraryCalls[] = { 908 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 909 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 910 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 911 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 912 913 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 914 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 915 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 916 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 917 }; 918 919 for (const auto &LC : LibraryCalls) { 920 setLibcallName(LC.Op, LC.Name); 921 setLibcallCallingConv(LC.Op, LC.CC); 922 } 923 } else { 924 const struct { 925 const RTLIB::Libcall Op; 926 const char * const Name; 927 const CallingConv::ID CC; 928 } LibraryCalls[] = { 929 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 930 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 931 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 932 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 933 934 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 935 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 936 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 937 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 938 }; 939 940 for (const auto &LC : LibraryCalls) { 941 setLibcallName(LC.Op, LC.Name); 942 setLibcallCallingConv(LC.Op, LC.CC); 943 } 944 } 945 946 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 947 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 948 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 949 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 950 } else { 951 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 952 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 953 } 954 955 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 956 for (auto &VT : {MVT::f32, MVT::f64}) 957 setOperationAction(ISD::FPOWI, VT, Custom); 958 959 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 960 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 961 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 962 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 963 964 setOperationAction(ISD::TRAP, MVT::Other, Legal); 965 966 // Use the default implementation. 967 setOperationAction(ISD::VASTART, MVT::Other, Custom); 968 setOperationAction(ISD::VAARG, MVT::Other, Expand); 969 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 970 setOperationAction(ISD::VAEND, MVT::Other, Expand); 971 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 972 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 973 974 if (Subtarget->isTargetWindows()) 975 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 976 else 977 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 978 979 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 980 // the default expansion. 981 InsertFencesForAtomic = false; 982 if (Subtarget->hasAnyDataBarrier() && 983 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 984 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 985 // to ldrex/strex loops already. 986 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 987 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 988 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 989 990 // On v8, we have particularly efficient implementations of atomic fences 991 // if they can be combined with nearby atomic loads and stores. 992 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 993 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 994 InsertFencesForAtomic = true; 995 } 996 } else { 997 // If there's anything we can use as a barrier, go through custom lowering 998 // for ATOMIC_FENCE. 999 // If target has DMB in thumb, Fences can be inserted. 1000 if (Subtarget->hasDataBarrier()) 1001 InsertFencesForAtomic = true; 1002 1003 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 1004 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1005 1006 // Set them all for expansion, which will force libcalls. 1007 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1008 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1009 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1010 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1011 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1012 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1013 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1014 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1015 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1016 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1017 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1018 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1019 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1020 // Unordered/Monotonic case. 1021 if (!InsertFencesForAtomic) { 1022 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1023 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1024 } 1025 } 1026 1027 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1028 1029 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1030 if (!Subtarget->hasV6Ops()) { 1031 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1032 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1033 } 1034 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1035 1036 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1037 !Subtarget->isThumb1Only()) { 1038 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1039 // iff target supports vfp2. 1040 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1041 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1042 } 1043 1044 // We want to custom lower some of our intrinsics. 1045 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1046 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1047 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1048 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1049 if (Subtarget->useSjLjEH()) 1050 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1051 1052 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1053 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1054 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1055 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1056 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1057 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1058 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1059 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1060 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1061 if (Subtarget->hasFullFP16()) { 1062 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1063 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1064 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1065 } 1066 1067 // Thumb-1 cannot currently select ARMISD::SUBE. 1068 if (!Subtarget->isThumb1Only()) 1069 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1070 1071 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1072 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1073 if (Subtarget->hasFullFP16()) 1074 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1075 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1076 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1077 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1078 1079 // We don't support sin/cos/fmod/copysign/pow 1080 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1081 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1082 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1083 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1084 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1085 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1086 setOperationAction(ISD::FREM, MVT::f64, Expand); 1087 setOperationAction(ISD::FREM, MVT::f32, Expand); 1088 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1089 !Subtarget->isThumb1Only()) { 1090 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1091 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1092 } 1093 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1094 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1095 1096 if (!Subtarget->hasVFP4()) { 1097 setOperationAction(ISD::FMA, MVT::f64, Expand); 1098 setOperationAction(ISD::FMA, MVT::f32, Expand); 1099 } 1100 1101 // Various VFP goodness 1102 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1103 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1104 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1105 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1106 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1107 } 1108 1109 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1110 if (!Subtarget->hasFP16()) { 1111 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1112 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1113 } 1114 } 1115 1116 // Use __sincos_stret if available. 1117 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1118 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1119 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1120 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1121 } 1122 1123 // FP-ARMv8 implements a lot of rounding-like FP operations. 1124 if (Subtarget->hasFPARMv8()) { 1125 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1126 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1127 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1128 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1129 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1130 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1131 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1132 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1133 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1134 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1135 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1136 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1137 1138 if (!Subtarget->isFPOnlySP()) { 1139 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1140 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1141 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1142 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1143 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1144 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1145 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1146 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1147 } 1148 } 1149 1150 if (Subtarget->hasNEON()) { 1151 // vmin and vmax aren't available in a scalar form, so we use 1152 // a NEON instruction with an undef lane instead. 1153 setOperationAction(ISD::FMINNAN, MVT::f16, Legal); 1154 setOperationAction(ISD::FMAXNAN, MVT::f16, Legal); 1155 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1156 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1157 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1158 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1159 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1160 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1161 } 1162 1163 // We have target-specific dag combine patterns for the following nodes: 1164 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1165 setTargetDAGCombine(ISD::ADD); 1166 setTargetDAGCombine(ISD::SUB); 1167 setTargetDAGCombine(ISD::MUL); 1168 setTargetDAGCombine(ISD::AND); 1169 setTargetDAGCombine(ISD::OR); 1170 setTargetDAGCombine(ISD::XOR); 1171 1172 if (Subtarget->hasV6Ops()) 1173 setTargetDAGCombine(ISD::SRL); 1174 1175 setStackPointerRegisterToSaveRestore(ARM::SP); 1176 1177 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1178 !Subtarget->hasVFP2()) 1179 setSchedulingPreference(Sched::RegPressure); 1180 else 1181 setSchedulingPreference(Sched::Hybrid); 1182 1183 //// temporary - rewrite interface to use type 1184 MaxStoresPerMemset = 8; 1185 MaxStoresPerMemsetOptSize = 4; 1186 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1187 MaxStoresPerMemcpyOptSize = 2; 1188 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1189 MaxStoresPerMemmoveOptSize = 2; 1190 1191 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1192 // are at least 4 bytes aligned. 1193 setMinStackArgumentAlignment(4); 1194 1195 // Prefer likely predicted branches to selects on out-of-order cores. 1196 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1197 1198 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1199 } 1200 1201 bool ARMTargetLowering::useSoftFloat() const { 1202 return Subtarget->useSoftFloat(); 1203 } 1204 1205 // FIXME: It might make sense to define the representative register class as the 1206 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1207 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1208 // SPR's representative would be DPR_VFP2. This should work well if register 1209 // pressure tracking were modified such that a register use would increment the 1210 // pressure of the register class's representative and all of it's super 1211 // classes' representatives transitively. We have not implemented this because 1212 // of the difficulty prior to coalescing of modeling operand register classes 1213 // due to the common occurrence of cross class copies and subregister insertions 1214 // and extractions. 1215 std::pair<const TargetRegisterClass *, uint8_t> 1216 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1217 MVT VT) const { 1218 const TargetRegisterClass *RRC = nullptr; 1219 uint8_t Cost = 1; 1220 switch (VT.SimpleTy) { 1221 default: 1222 return TargetLowering::findRepresentativeClass(TRI, VT); 1223 // Use DPR as representative register class for all floating point 1224 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1225 // the cost is 1 for both f32 and f64. 1226 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1227 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1228 RRC = &ARM::DPRRegClass; 1229 // When NEON is used for SP, only half of the register file is available 1230 // because operations that define both SP and DP results will be constrained 1231 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1232 // coalescing by double-counting the SP regs. See the FIXME above. 1233 if (Subtarget->useNEONForSinglePrecisionFP()) 1234 Cost = 2; 1235 break; 1236 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1237 case MVT::v4f32: case MVT::v2f64: 1238 RRC = &ARM::DPRRegClass; 1239 Cost = 2; 1240 break; 1241 case MVT::v4i64: 1242 RRC = &ARM::DPRRegClass; 1243 Cost = 4; 1244 break; 1245 case MVT::v8i64: 1246 RRC = &ARM::DPRRegClass; 1247 Cost = 8; 1248 break; 1249 } 1250 return std::make_pair(RRC, Cost); 1251 } 1252 1253 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1254 switch ((ARMISD::NodeType)Opcode) { 1255 case ARMISD::FIRST_NUMBER: break; 1256 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1257 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1258 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1259 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1260 case ARMISD::CALL: return "ARMISD::CALL"; 1261 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1262 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1263 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1264 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1265 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1266 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1267 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1268 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1269 case ARMISD::CMP: return "ARMISD::CMP"; 1270 case ARMISD::CMN: return "ARMISD::CMN"; 1271 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1272 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1273 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1274 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1275 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1276 1277 case ARMISD::CMOV: return "ARMISD::CMOV"; 1278 1279 case ARMISD::SSAT: return "ARMISD::SSAT"; 1280 case ARMISD::USAT: return "ARMISD::USAT"; 1281 1282 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1283 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1284 case ARMISD::RRX: return "ARMISD::RRX"; 1285 1286 case ARMISD::ADDC: return "ARMISD::ADDC"; 1287 case ARMISD::ADDE: return "ARMISD::ADDE"; 1288 case ARMISD::SUBC: return "ARMISD::SUBC"; 1289 case ARMISD::SUBE: return "ARMISD::SUBE"; 1290 1291 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1292 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1293 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1294 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1295 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1296 1297 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1298 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1299 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1300 1301 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1302 1303 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1304 1305 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1306 1307 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1308 1309 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1310 1311 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1312 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1313 1314 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1315 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1316 case ARMISD::VCGE: return "ARMISD::VCGE"; 1317 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1318 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1319 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1320 case ARMISD::VCGT: return "ARMISD::VCGT"; 1321 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1322 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1323 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1324 case ARMISD::VTST: return "ARMISD::VTST"; 1325 1326 case ARMISD::VSHL: return "ARMISD::VSHL"; 1327 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1328 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1329 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1330 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1331 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1332 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1333 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1334 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1335 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1336 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1337 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1338 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1339 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1340 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1341 case ARMISD::VSLI: return "ARMISD::VSLI"; 1342 case ARMISD::VSRI: return "ARMISD::VSRI"; 1343 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1344 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1345 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1346 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1347 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1348 case ARMISD::VDUP: return "ARMISD::VDUP"; 1349 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1350 case ARMISD::VEXT: return "ARMISD::VEXT"; 1351 case ARMISD::VREV64: return "ARMISD::VREV64"; 1352 case ARMISD::VREV32: return "ARMISD::VREV32"; 1353 case ARMISD::VREV16: return "ARMISD::VREV16"; 1354 case ARMISD::VZIP: return "ARMISD::VZIP"; 1355 case ARMISD::VUZP: return "ARMISD::VUZP"; 1356 case ARMISD::VTRN: return "ARMISD::VTRN"; 1357 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1358 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1359 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1360 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1361 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1362 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1363 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1364 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1365 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1366 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1367 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1368 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1369 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1370 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1371 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1372 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1373 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1374 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1375 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1376 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1377 case ARMISD::BFI: return "ARMISD::BFI"; 1378 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1379 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1380 case ARMISD::VBSL: return "ARMISD::VBSL"; 1381 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1382 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1383 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1384 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1385 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1386 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1387 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1388 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1389 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1390 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1391 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1392 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1393 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1394 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1395 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1396 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1397 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1398 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1399 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1400 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1401 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1402 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1403 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1404 } 1405 return nullptr; 1406 } 1407 1408 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1409 EVT VT) const { 1410 if (!VT.isVector()) 1411 return getPointerTy(DL); 1412 return VT.changeVectorElementTypeToInteger(); 1413 } 1414 1415 /// getRegClassFor - Return the register class that should be used for the 1416 /// specified value type. 1417 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1418 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1419 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1420 // load / store 4 to 8 consecutive D registers. 1421 if (Subtarget->hasNEON()) { 1422 if (VT == MVT::v4i64) 1423 return &ARM::QQPRRegClass; 1424 if (VT == MVT::v8i64) 1425 return &ARM::QQQQPRRegClass; 1426 } 1427 return TargetLowering::getRegClassFor(VT); 1428 } 1429 1430 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1431 // source/dest is aligned and the copy size is large enough. We therefore want 1432 // to align such objects passed to memory intrinsics. 1433 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1434 unsigned &PrefAlign) const { 1435 if (!isa<MemIntrinsic>(CI)) 1436 return false; 1437 MinSize = 8; 1438 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1439 // cycle faster than 4-byte aligned LDM. 1440 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1441 return true; 1442 } 1443 1444 // Create a fast isel object. 1445 FastISel * 1446 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1447 const TargetLibraryInfo *libInfo) const { 1448 return ARM::createFastISel(funcInfo, libInfo); 1449 } 1450 1451 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1452 unsigned NumVals = N->getNumValues(); 1453 if (!NumVals) 1454 return Sched::RegPressure; 1455 1456 for (unsigned i = 0; i != NumVals; ++i) { 1457 EVT VT = N->getValueType(i); 1458 if (VT == MVT::Glue || VT == MVT::Other) 1459 continue; 1460 if (VT.isFloatingPoint() || VT.isVector()) 1461 return Sched::ILP; 1462 } 1463 1464 if (!N->isMachineOpcode()) 1465 return Sched::RegPressure; 1466 1467 // Load are scheduled for latency even if there instruction itinerary 1468 // is not available. 1469 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1470 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1471 1472 if (MCID.getNumDefs() == 0) 1473 return Sched::RegPressure; 1474 if (!Itins->isEmpty() && 1475 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1476 return Sched::ILP; 1477 1478 return Sched::RegPressure; 1479 } 1480 1481 //===----------------------------------------------------------------------===// 1482 // Lowering Code 1483 //===----------------------------------------------------------------------===// 1484 1485 static bool isSRL16(const SDValue &Op) { 1486 if (Op.getOpcode() != ISD::SRL) 1487 return false; 1488 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1489 return Const->getZExtValue() == 16; 1490 return false; 1491 } 1492 1493 static bool isSRA16(const SDValue &Op) { 1494 if (Op.getOpcode() != ISD::SRA) 1495 return false; 1496 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1497 return Const->getZExtValue() == 16; 1498 return false; 1499 } 1500 1501 static bool isSHL16(const SDValue &Op) { 1502 if (Op.getOpcode() != ISD::SHL) 1503 return false; 1504 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1505 return Const->getZExtValue() == 16; 1506 return false; 1507 } 1508 1509 // Check for a signed 16-bit value. We special case SRA because it makes it 1510 // more simple when also looking for SRAs that aren't sign extending a 1511 // smaller value. Without the check, we'd need to take extra care with 1512 // checking order for some operations. 1513 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1514 if (isSRA16(Op)) 1515 return isSHL16(Op.getOperand(0)); 1516 return DAG.ComputeNumSignBits(Op) == 17; 1517 } 1518 1519 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1520 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1521 switch (CC) { 1522 default: llvm_unreachable("Unknown condition code!"); 1523 case ISD::SETNE: return ARMCC::NE; 1524 case ISD::SETEQ: return ARMCC::EQ; 1525 case ISD::SETGT: return ARMCC::GT; 1526 case ISD::SETGE: return ARMCC::GE; 1527 case ISD::SETLT: return ARMCC::LT; 1528 case ISD::SETLE: return ARMCC::LE; 1529 case ISD::SETUGT: return ARMCC::HI; 1530 case ISD::SETUGE: return ARMCC::HS; 1531 case ISD::SETULT: return ARMCC::LO; 1532 case ISD::SETULE: return ARMCC::LS; 1533 } 1534 } 1535 1536 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1537 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1538 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1539 CondCode2 = ARMCC::AL; 1540 InvalidOnQNaN = true; 1541 switch (CC) { 1542 default: llvm_unreachable("Unknown FP condition!"); 1543 case ISD::SETEQ: 1544 case ISD::SETOEQ: 1545 CondCode = ARMCC::EQ; 1546 InvalidOnQNaN = false; 1547 break; 1548 case ISD::SETGT: 1549 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1550 case ISD::SETGE: 1551 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1552 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1553 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1554 case ISD::SETONE: 1555 CondCode = ARMCC::MI; 1556 CondCode2 = ARMCC::GT; 1557 InvalidOnQNaN = false; 1558 break; 1559 case ISD::SETO: CondCode = ARMCC::VC; break; 1560 case ISD::SETUO: CondCode = ARMCC::VS; break; 1561 case ISD::SETUEQ: 1562 CondCode = ARMCC::EQ; 1563 CondCode2 = ARMCC::VS; 1564 InvalidOnQNaN = false; 1565 break; 1566 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1567 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1568 case ISD::SETLT: 1569 case ISD::SETULT: CondCode = ARMCC::LT; break; 1570 case ISD::SETLE: 1571 case ISD::SETULE: CondCode = ARMCC::LE; break; 1572 case ISD::SETNE: 1573 case ISD::SETUNE: 1574 CondCode = ARMCC::NE; 1575 InvalidOnQNaN = false; 1576 break; 1577 } 1578 } 1579 1580 //===----------------------------------------------------------------------===// 1581 // Calling Convention Implementation 1582 //===----------------------------------------------------------------------===// 1583 1584 #include "ARMGenCallingConv.inc" 1585 1586 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1587 /// account presence of floating point hardware and calling convention 1588 /// limitations, such as support for variadic functions. 1589 CallingConv::ID 1590 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1591 bool isVarArg) const { 1592 switch (CC) { 1593 default: 1594 report_fatal_error("Unsupported calling convention"); 1595 case CallingConv::ARM_AAPCS: 1596 case CallingConv::ARM_APCS: 1597 case CallingConv::GHC: 1598 return CC; 1599 case CallingConv::PreserveMost: 1600 return CallingConv::PreserveMost; 1601 case CallingConv::ARM_AAPCS_VFP: 1602 case CallingConv::Swift: 1603 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1604 case CallingConv::C: 1605 if (!Subtarget->isAAPCS_ABI()) 1606 return CallingConv::ARM_APCS; 1607 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1608 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1609 !isVarArg) 1610 return CallingConv::ARM_AAPCS_VFP; 1611 else 1612 return CallingConv::ARM_AAPCS; 1613 case CallingConv::Fast: 1614 case CallingConv::CXX_FAST_TLS: 1615 if (!Subtarget->isAAPCS_ABI()) { 1616 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1617 return CallingConv::Fast; 1618 return CallingConv::ARM_APCS; 1619 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1620 return CallingConv::ARM_AAPCS_VFP; 1621 else 1622 return CallingConv::ARM_AAPCS; 1623 } 1624 } 1625 1626 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1627 bool isVarArg) const { 1628 return CCAssignFnForNode(CC, false, isVarArg); 1629 } 1630 1631 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1632 bool isVarArg) const { 1633 return CCAssignFnForNode(CC, true, isVarArg); 1634 } 1635 1636 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1637 /// CallingConvention. 1638 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1639 bool Return, 1640 bool isVarArg) const { 1641 switch (getEffectiveCallingConv(CC, isVarArg)) { 1642 default: 1643 report_fatal_error("Unsupported calling convention"); 1644 case CallingConv::ARM_APCS: 1645 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1646 case CallingConv::ARM_AAPCS: 1647 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1648 case CallingConv::ARM_AAPCS_VFP: 1649 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1650 case CallingConv::Fast: 1651 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1652 case CallingConv::GHC: 1653 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1654 case CallingConv::PreserveMost: 1655 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1656 } 1657 } 1658 1659 /// LowerCallResult - Lower the result values of a call into the 1660 /// appropriate copies out of appropriate physical registers. 1661 SDValue ARMTargetLowering::LowerCallResult( 1662 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1663 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1664 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1665 SDValue ThisVal) const { 1666 // Assign locations to each value returned by this call. 1667 SmallVector<CCValAssign, 16> RVLocs; 1668 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1669 *DAG.getContext()); 1670 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1671 1672 // Copy all of the result registers out of their specified physreg. 1673 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1674 CCValAssign VA = RVLocs[i]; 1675 1676 // Pass 'this' value directly from the argument to return value, to avoid 1677 // reg unit interference 1678 if (i == 0 && isThisReturn) { 1679 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1680 "unexpected return calling convention register assignment"); 1681 InVals.push_back(ThisVal); 1682 continue; 1683 } 1684 1685 SDValue Val; 1686 if (VA.needsCustom()) { 1687 // Handle f64 or half of a v2f64. 1688 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1689 InFlag); 1690 Chain = Lo.getValue(1); 1691 InFlag = Lo.getValue(2); 1692 VA = RVLocs[++i]; // skip ahead to next loc 1693 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1694 InFlag); 1695 Chain = Hi.getValue(1); 1696 InFlag = Hi.getValue(2); 1697 if (!Subtarget->isLittle()) 1698 std::swap (Lo, Hi); 1699 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1700 1701 if (VA.getLocVT() == MVT::v2f64) { 1702 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1703 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1704 DAG.getConstant(0, dl, MVT::i32)); 1705 1706 VA = RVLocs[++i]; // skip ahead to next loc 1707 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1708 Chain = Lo.getValue(1); 1709 InFlag = Lo.getValue(2); 1710 VA = RVLocs[++i]; // skip ahead to next loc 1711 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1712 Chain = Hi.getValue(1); 1713 InFlag = Hi.getValue(2); 1714 if (!Subtarget->isLittle()) 1715 std::swap (Lo, Hi); 1716 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1717 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1718 DAG.getConstant(1, dl, MVT::i32)); 1719 } 1720 } else { 1721 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1722 InFlag); 1723 Chain = Val.getValue(1); 1724 InFlag = Val.getValue(2); 1725 } 1726 1727 switch (VA.getLocInfo()) { 1728 default: llvm_unreachable("Unknown loc info!"); 1729 case CCValAssign::Full: break; 1730 case CCValAssign::BCvt: 1731 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1732 break; 1733 } 1734 1735 InVals.push_back(Val); 1736 } 1737 1738 return Chain; 1739 } 1740 1741 /// LowerMemOpCallTo - Store the argument to the stack. 1742 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1743 SDValue Arg, const SDLoc &dl, 1744 SelectionDAG &DAG, 1745 const CCValAssign &VA, 1746 ISD::ArgFlagsTy Flags) const { 1747 unsigned LocMemOffset = VA.getLocMemOffset(); 1748 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1749 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1750 StackPtr, PtrOff); 1751 return DAG.getStore( 1752 Chain, dl, Arg, PtrOff, 1753 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1754 } 1755 1756 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1757 SDValue Chain, SDValue &Arg, 1758 RegsToPassVector &RegsToPass, 1759 CCValAssign &VA, CCValAssign &NextVA, 1760 SDValue &StackPtr, 1761 SmallVectorImpl<SDValue> &MemOpChains, 1762 ISD::ArgFlagsTy Flags) const { 1763 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1764 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1765 unsigned id = Subtarget->isLittle() ? 0 : 1; 1766 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1767 1768 if (NextVA.isRegLoc()) 1769 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1770 else { 1771 assert(NextVA.isMemLoc()); 1772 if (!StackPtr.getNode()) 1773 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1774 getPointerTy(DAG.getDataLayout())); 1775 1776 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1777 dl, DAG, NextVA, 1778 Flags)); 1779 } 1780 } 1781 1782 /// LowerCall - Lowering a call into a callseq_start <- 1783 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1784 /// nodes. 1785 SDValue 1786 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1787 SmallVectorImpl<SDValue> &InVals) const { 1788 SelectionDAG &DAG = CLI.DAG; 1789 SDLoc &dl = CLI.DL; 1790 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1791 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1792 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1793 SDValue Chain = CLI.Chain; 1794 SDValue Callee = CLI.Callee; 1795 bool &isTailCall = CLI.IsTailCall; 1796 CallingConv::ID CallConv = CLI.CallConv; 1797 bool doesNotRet = CLI.DoesNotReturn; 1798 bool isVarArg = CLI.IsVarArg; 1799 1800 MachineFunction &MF = DAG.getMachineFunction(); 1801 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1802 bool isThisReturn = false; 1803 bool isSibCall = false; 1804 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 1805 1806 // Disable tail calls if they're not supported. 1807 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1808 isTailCall = false; 1809 1810 if (isTailCall) { 1811 // Check if it's really possible to do a tail call. 1812 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1813 isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(), 1814 Outs, OutVals, Ins, DAG); 1815 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1816 report_fatal_error("failed to perform tail call elimination on a call " 1817 "site marked musttail"); 1818 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1819 // detected sibcalls. 1820 if (isTailCall) { 1821 ++NumTailCalls; 1822 isSibCall = true; 1823 } 1824 } 1825 1826 // Analyze operands of the call, assigning locations to each operand. 1827 SmallVector<CCValAssign, 16> ArgLocs; 1828 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1829 *DAG.getContext()); 1830 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1831 1832 // Get a count of how many bytes are to be pushed on the stack. 1833 unsigned NumBytes = CCInfo.getNextStackOffset(); 1834 1835 // For tail calls, memory operands are available in our caller's stack. 1836 if (isSibCall) 1837 NumBytes = 0; 1838 1839 // Adjust the stack pointer for the new arguments... 1840 // These operations are automatically eliminated by the prolog/epilog pass 1841 if (!isSibCall) 1842 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 1843 1844 SDValue StackPtr = 1845 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1846 1847 RegsToPassVector RegsToPass; 1848 SmallVector<SDValue, 8> MemOpChains; 1849 1850 // Walk the register/memloc assignments, inserting copies/loads. In the case 1851 // of tail call optimization, arguments are handled later. 1852 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1853 i != e; 1854 ++i, ++realArgIdx) { 1855 CCValAssign &VA = ArgLocs[i]; 1856 SDValue Arg = OutVals[realArgIdx]; 1857 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1858 bool isByVal = Flags.isByVal(); 1859 1860 // Promote the value if needed. 1861 switch (VA.getLocInfo()) { 1862 default: llvm_unreachable("Unknown loc info!"); 1863 case CCValAssign::Full: break; 1864 case CCValAssign::SExt: 1865 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1866 break; 1867 case CCValAssign::ZExt: 1868 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1869 break; 1870 case CCValAssign::AExt: 1871 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1872 break; 1873 case CCValAssign::BCvt: 1874 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1875 break; 1876 } 1877 1878 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1879 if (VA.needsCustom()) { 1880 if (VA.getLocVT() == MVT::v2f64) { 1881 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1882 DAG.getConstant(0, dl, MVT::i32)); 1883 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1884 DAG.getConstant(1, dl, MVT::i32)); 1885 1886 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1887 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1888 1889 VA = ArgLocs[++i]; // skip ahead to next loc 1890 if (VA.isRegLoc()) { 1891 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1892 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1893 } else { 1894 assert(VA.isMemLoc()); 1895 1896 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1897 dl, DAG, VA, Flags)); 1898 } 1899 } else { 1900 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1901 StackPtr, MemOpChains, Flags); 1902 } 1903 } else if (VA.isRegLoc()) { 1904 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1905 Outs[0].VT == MVT::i32) { 1906 assert(VA.getLocVT() == MVT::i32 && 1907 "unexpected calling convention register assignment"); 1908 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1909 "unexpected use of 'returned'"); 1910 isThisReturn = true; 1911 } 1912 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1913 } else if (isByVal) { 1914 assert(VA.isMemLoc()); 1915 unsigned offset = 0; 1916 1917 // True if this byval aggregate will be split between registers 1918 // and memory. 1919 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1920 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1921 1922 if (CurByValIdx < ByValArgsCount) { 1923 1924 unsigned RegBegin, RegEnd; 1925 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1926 1927 EVT PtrVT = 1928 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1929 unsigned int i, j; 1930 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1931 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1932 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1933 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1934 MachinePointerInfo(), 1935 DAG.InferPtrAlignment(AddArg)); 1936 MemOpChains.push_back(Load.getValue(1)); 1937 RegsToPass.push_back(std::make_pair(j, Load)); 1938 } 1939 1940 // If parameter size outsides register area, "offset" value 1941 // helps us to calculate stack slot for remained part properly. 1942 offset = RegEnd - RegBegin; 1943 1944 CCInfo.nextInRegsParam(); 1945 } 1946 1947 if (Flags.getByValSize() > 4*offset) { 1948 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1949 unsigned LocMemOffset = VA.getLocMemOffset(); 1950 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1951 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1952 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1953 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1954 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1955 MVT::i32); 1956 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1957 MVT::i32); 1958 1959 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1960 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1961 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1962 Ops)); 1963 } 1964 } else if (!isSibCall) { 1965 assert(VA.isMemLoc()); 1966 1967 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1968 dl, DAG, VA, Flags)); 1969 } 1970 } 1971 1972 if (!MemOpChains.empty()) 1973 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1974 1975 // Build a sequence of copy-to-reg nodes chained together with token chain 1976 // and flag operands which copy the outgoing args into the appropriate regs. 1977 SDValue InFlag; 1978 // Tail call byval lowering might overwrite argument registers so in case of 1979 // tail call optimization the copies to registers are lowered later. 1980 if (!isTailCall) 1981 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1982 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1983 RegsToPass[i].second, InFlag); 1984 InFlag = Chain.getValue(1); 1985 } 1986 1987 // For tail calls lower the arguments to the 'real' stack slot. 1988 if (isTailCall) { 1989 // Force all the incoming stack arguments to be loaded from the stack 1990 // before any new outgoing arguments are stored to the stack, because the 1991 // outgoing stack slots may alias the incoming argument stack slots, and 1992 // the alias isn't otherwise explicit. This is slightly more conservative 1993 // than necessary, because it means that each store effectively depends 1994 // on every argument instead of just those arguments it would clobber. 1995 1996 // Do not flag preceding copytoreg stuff together with the following stuff. 1997 InFlag = SDValue(); 1998 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1999 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2000 RegsToPass[i].second, InFlag); 2001 InFlag = Chain.getValue(1); 2002 } 2003 InFlag = SDValue(); 2004 } 2005 2006 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2007 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2008 // node so that legalize doesn't hack it. 2009 bool isDirect = false; 2010 2011 const TargetMachine &TM = getTargetMachine(); 2012 const Module *Mod = MF.getFunction().getParent(); 2013 const GlobalValue *GV = nullptr; 2014 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2015 GV = G->getGlobal(); 2016 bool isStub = 2017 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2018 2019 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2020 bool isLocalARMFunc = false; 2021 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2022 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2023 2024 if (Subtarget->genLongCalls()) { 2025 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2026 "long-calls codegen is not position independent!"); 2027 // Handle a global address or an external symbol. If it's not one of 2028 // those, the target's already in a register, so we don't need to do 2029 // anything extra. 2030 if (isa<GlobalAddressSDNode>(Callee)) { 2031 // Create a constant pool entry for the callee address 2032 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2033 ARMConstantPoolValue *CPV = 2034 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2035 2036 // Get the address of the callee into a register 2037 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2038 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2039 Callee = DAG.getLoad( 2040 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2041 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2042 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2043 const char *Sym = S->getSymbol(); 2044 2045 // Create a constant pool entry for the callee address 2046 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2047 ARMConstantPoolValue *CPV = 2048 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2049 ARMPCLabelIndex, 0); 2050 // Get the address of the callee into a register 2051 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2052 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2053 Callee = DAG.getLoad( 2054 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2055 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2056 } 2057 } else if (isa<GlobalAddressSDNode>(Callee)) { 2058 // If we're optimizing for minimum size and the function is called three or 2059 // more times in this block, we can improve codesize by calling indirectly 2060 // as BLXr has a 16-bit encoding. 2061 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2062 auto *BB = CLI.CS.getParent(); 2063 bool PreferIndirect = 2064 Subtarget->isThumb() && MF.getFunction().optForMinSize() && 2065 count_if(GV->users(), [&BB](const User *U) { 2066 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2067 }) > 2; 2068 2069 if (!PreferIndirect) { 2070 isDirect = true; 2071 bool isDef = GV->isStrongDefinitionForLinker(); 2072 2073 // ARM call to a local ARM function is predicable. 2074 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2075 // tBX takes a register source operand. 2076 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2077 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2078 Callee = DAG.getNode( 2079 ARMISD::WrapperPIC, dl, PtrVt, 2080 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2081 Callee = DAG.getLoad( 2082 PtrVt, dl, DAG.getEntryNode(), Callee, 2083 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2084 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2085 MachineMemOperand::MOInvariant); 2086 } else if (Subtarget->isTargetCOFF()) { 2087 assert(Subtarget->isTargetWindows() && 2088 "Windows is the only supported COFF target"); 2089 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2090 ? ARMII::MO_DLLIMPORT 2091 : ARMII::MO_NO_FLAG; 2092 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2093 TargetFlags); 2094 if (GV->hasDLLImportStorageClass()) 2095 Callee = 2096 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2097 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2098 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2099 } else { 2100 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2101 } 2102 } 2103 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2104 isDirect = true; 2105 // tBX takes a register source operand. 2106 const char *Sym = S->getSymbol(); 2107 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2108 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2109 ARMConstantPoolValue *CPV = 2110 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2111 ARMPCLabelIndex, 4); 2112 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2113 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2114 Callee = DAG.getLoad( 2115 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2116 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2117 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2118 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2119 } else { 2120 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2121 } 2122 } 2123 2124 // FIXME: handle tail calls differently. 2125 unsigned CallOpc; 2126 if (Subtarget->isThumb()) { 2127 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2128 CallOpc = ARMISD::CALL_NOLINK; 2129 else 2130 CallOpc = ARMISD::CALL; 2131 } else { 2132 if (!isDirect && !Subtarget->hasV5TOps()) 2133 CallOpc = ARMISD::CALL_NOLINK; 2134 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2135 // Emit regular call when code size is the priority 2136 !MF.getFunction().optForMinSize()) 2137 // "mov lr, pc; b _foo" to avoid confusing the RSP 2138 CallOpc = ARMISD::CALL_NOLINK; 2139 else 2140 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2141 } 2142 2143 std::vector<SDValue> Ops; 2144 Ops.push_back(Chain); 2145 Ops.push_back(Callee); 2146 2147 // Add argument registers to the end of the list so that they are known live 2148 // into the call. 2149 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2150 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2151 RegsToPass[i].second.getValueType())); 2152 2153 // Add a register mask operand representing the call-preserved registers. 2154 if (!isTailCall) { 2155 const uint32_t *Mask; 2156 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2157 if (isThisReturn) { 2158 // For 'this' returns, use the R0-preserving mask if applicable 2159 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2160 if (!Mask) { 2161 // Set isThisReturn to false if the calling convention is not one that 2162 // allows 'returned' to be modeled in this way, so LowerCallResult does 2163 // not try to pass 'this' straight through 2164 isThisReturn = false; 2165 Mask = ARI->getCallPreservedMask(MF, CallConv); 2166 } 2167 } else 2168 Mask = ARI->getCallPreservedMask(MF, CallConv); 2169 2170 assert(Mask && "Missing call preserved mask for calling convention"); 2171 Ops.push_back(DAG.getRegisterMask(Mask)); 2172 } 2173 2174 if (InFlag.getNode()) 2175 Ops.push_back(InFlag); 2176 2177 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2178 if (isTailCall) { 2179 MF.getFrameInfo().setHasTailCall(); 2180 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2181 } 2182 2183 // Returns a chain and a flag for retval copy to use. 2184 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2185 InFlag = Chain.getValue(1); 2186 2187 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2188 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2189 if (!Ins.empty()) 2190 InFlag = Chain.getValue(1); 2191 2192 // Handle result values, copying them out of physregs into vregs that we 2193 // return. 2194 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2195 InVals, isThisReturn, 2196 isThisReturn ? OutVals[0] : SDValue()); 2197 } 2198 2199 /// HandleByVal - Every parameter *after* a byval parameter is passed 2200 /// on the stack. Remember the next parameter register to allocate, 2201 /// and then confiscate the rest of the parameter registers to insure 2202 /// this. 2203 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2204 unsigned Align) const { 2205 // Byval (as with any stack) slots are always at least 4 byte aligned. 2206 Align = std::max(Align, 4U); 2207 2208 unsigned Reg = State->AllocateReg(GPRArgRegs); 2209 if (!Reg) 2210 return; 2211 2212 unsigned AlignInRegs = Align / 4; 2213 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2214 for (unsigned i = 0; i < Waste; ++i) 2215 Reg = State->AllocateReg(GPRArgRegs); 2216 2217 if (!Reg) 2218 return; 2219 2220 unsigned Excess = 4 * (ARM::R4 - Reg); 2221 2222 // Special case when NSAA != SP and parameter size greater than size of 2223 // all remained GPR regs. In that case we can't split parameter, we must 2224 // send it to stack. We also must set NCRN to R4, so waste all 2225 // remained registers. 2226 const unsigned NSAAOffset = State->getNextStackOffset(); 2227 if (NSAAOffset != 0 && Size > Excess) { 2228 while (State->AllocateReg(GPRArgRegs)) 2229 ; 2230 return; 2231 } 2232 2233 // First register for byval parameter is the first register that wasn't 2234 // allocated before this method call, so it would be "reg". 2235 // If parameter is small enough to be saved in range [reg, r4), then 2236 // the end (first after last) register would be reg + param-size-in-regs, 2237 // else parameter would be splitted between registers and stack, 2238 // end register would be r4 in this case. 2239 unsigned ByValRegBegin = Reg; 2240 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2241 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2242 // Note, first register is allocated in the beginning of function already, 2243 // allocate remained amount of registers we need. 2244 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2245 State->AllocateReg(GPRArgRegs); 2246 // A byval parameter that is split between registers and memory needs its 2247 // size truncated here. 2248 // In the case where the entire structure fits in registers, we set the 2249 // size in memory to zero. 2250 Size = std::max<int>(Size - Excess, 0); 2251 } 2252 2253 /// MatchingStackOffset - Return true if the given stack call argument is 2254 /// already available in the same position (relatively) of the caller's 2255 /// incoming argument stack. 2256 static 2257 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2258 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2259 const TargetInstrInfo *TII) { 2260 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2261 int FI = std::numeric_limits<int>::max(); 2262 if (Arg.getOpcode() == ISD::CopyFromReg) { 2263 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2264 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2265 return false; 2266 MachineInstr *Def = MRI->getVRegDef(VR); 2267 if (!Def) 2268 return false; 2269 if (!Flags.isByVal()) { 2270 if (!TII->isLoadFromStackSlot(*Def, FI)) 2271 return false; 2272 } else { 2273 return false; 2274 } 2275 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2276 if (Flags.isByVal()) 2277 // ByVal argument is passed in as a pointer but it's now being 2278 // dereferenced. e.g. 2279 // define @foo(%struct.X* %A) { 2280 // tail call @bar(%struct.X* byval %A) 2281 // } 2282 return false; 2283 SDValue Ptr = Ld->getBasePtr(); 2284 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2285 if (!FINode) 2286 return false; 2287 FI = FINode->getIndex(); 2288 } else 2289 return false; 2290 2291 assert(FI != std::numeric_limits<int>::max()); 2292 if (!MFI.isFixedObjectIndex(FI)) 2293 return false; 2294 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2295 } 2296 2297 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2298 /// for tail call optimization. Targets which want to do tail call 2299 /// optimization should implement this function. 2300 bool 2301 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2302 CallingConv::ID CalleeCC, 2303 bool isVarArg, 2304 bool isCalleeStructRet, 2305 bool isCallerStructRet, 2306 const SmallVectorImpl<ISD::OutputArg> &Outs, 2307 const SmallVectorImpl<SDValue> &OutVals, 2308 const SmallVectorImpl<ISD::InputArg> &Ins, 2309 SelectionDAG& DAG) const { 2310 MachineFunction &MF = DAG.getMachineFunction(); 2311 const Function &CallerF = MF.getFunction(); 2312 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2313 2314 assert(Subtarget->supportsTailCall()); 2315 2316 // Tail calls to function pointers cannot be optimized for Thumb1 if the args 2317 // to the call take up r0-r3. The reason is that there are no legal registers 2318 // left to hold the pointer to the function to be called. 2319 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2320 !isa<GlobalAddressSDNode>(Callee.getNode())) 2321 return false; 2322 2323 // Look for obvious safe cases to perform tail call optimization that do not 2324 // require ABI changes. This is what gcc calls sibcall. 2325 2326 // Exception-handling functions need a special set of instructions to indicate 2327 // a return to the hardware. Tail-calling another function would probably 2328 // break this. 2329 if (CallerF.hasFnAttribute("interrupt")) 2330 return false; 2331 2332 // Also avoid sibcall optimization if either caller or callee uses struct 2333 // return semantics. 2334 if (isCalleeStructRet || isCallerStructRet) 2335 return false; 2336 2337 // Externally-defined functions with weak linkage should not be 2338 // tail-called on ARM when the OS does not support dynamic 2339 // pre-emption of symbols, as the AAELF spec requires normal calls 2340 // to undefined weak functions to be replaced with a NOP or jump to the 2341 // next instruction. The behaviour of branch instructions in this 2342 // situation (as used for tail calls) is implementation-defined, so we 2343 // cannot rely on the linker replacing the tail call with a return. 2344 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2345 const GlobalValue *GV = G->getGlobal(); 2346 const Triple &TT = getTargetMachine().getTargetTriple(); 2347 if (GV->hasExternalWeakLinkage() && 2348 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2349 return false; 2350 } 2351 2352 // Check that the call results are passed in the same way. 2353 LLVMContext &C = *DAG.getContext(); 2354 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2355 CCAssignFnForReturn(CalleeCC, isVarArg), 2356 CCAssignFnForReturn(CallerCC, isVarArg))) 2357 return false; 2358 // The callee has to preserve all registers the caller needs to preserve. 2359 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2360 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2361 if (CalleeCC != CallerCC) { 2362 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2363 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2364 return false; 2365 } 2366 2367 // If Caller's vararg or byval argument has been split between registers and 2368 // stack, do not perform tail call, since part of the argument is in caller's 2369 // local frame. 2370 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2371 if (AFI_Caller->getArgRegsSaveSize()) 2372 return false; 2373 2374 // If the callee takes no arguments then go on to check the results of the 2375 // call. 2376 if (!Outs.empty()) { 2377 // Check if stack adjustment is needed. For now, do not do this if any 2378 // argument is passed on the stack. 2379 SmallVector<CCValAssign, 16> ArgLocs; 2380 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2381 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2382 if (CCInfo.getNextStackOffset()) { 2383 // Check if the arguments are already laid out in the right way as 2384 // the caller's fixed stack objects. 2385 MachineFrameInfo &MFI = MF.getFrameInfo(); 2386 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2387 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2388 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2389 i != e; 2390 ++i, ++realArgIdx) { 2391 CCValAssign &VA = ArgLocs[i]; 2392 EVT RegVT = VA.getLocVT(); 2393 SDValue Arg = OutVals[realArgIdx]; 2394 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2395 if (VA.getLocInfo() == CCValAssign::Indirect) 2396 return false; 2397 if (VA.needsCustom()) { 2398 // f64 and vector types are split into multiple registers or 2399 // register/stack-slot combinations. The types will not match 2400 // the registers; give up on memory f64 refs until we figure 2401 // out what to do about this. 2402 if (!VA.isRegLoc()) 2403 return false; 2404 if (!ArgLocs[++i].isRegLoc()) 2405 return false; 2406 if (RegVT == MVT::v2f64) { 2407 if (!ArgLocs[++i].isRegLoc()) 2408 return false; 2409 if (!ArgLocs[++i].isRegLoc()) 2410 return false; 2411 } 2412 } else if (!VA.isRegLoc()) { 2413 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2414 MFI, MRI, TII)) 2415 return false; 2416 } 2417 } 2418 } 2419 2420 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2421 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2422 return false; 2423 } 2424 2425 return true; 2426 } 2427 2428 bool 2429 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2430 MachineFunction &MF, bool isVarArg, 2431 const SmallVectorImpl<ISD::OutputArg> &Outs, 2432 LLVMContext &Context) const { 2433 SmallVector<CCValAssign, 16> RVLocs; 2434 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2435 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2436 } 2437 2438 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2439 const SDLoc &DL, SelectionDAG &DAG) { 2440 const MachineFunction &MF = DAG.getMachineFunction(); 2441 const Function &F = MF.getFunction(); 2442 2443 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2444 2445 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2446 // version of the "preferred return address". These offsets affect the return 2447 // instruction if this is a return from PL1 without hypervisor extensions. 2448 // IRQ/FIQ: +4 "subs pc, lr, #4" 2449 // SWI: 0 "subs pc, lr, #0" 2450 // ABORT: +4 "subs pc, lr, #4" 2451 // UNDEF: +4/+2 "subs pc, lr, #0" 2452 // UNDEF varies depending on where the exception came from ARM or Thumb 2453 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2454 2455 int64_t LROffset; 2456 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2457 IntKind == "ABORT") 2458 LROffset = 4; 2459 else if (IntKind == "SWI" || IntKind == "UNDEF") 2460 LROffset = 0; 2461 else 2462 report_fatal_error("Unsupported interrupt attribute. If present, value " 2463 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2464 2465 RetOps.insert(RetOps.begin() + 1, 2466 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2467 2468 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2469 } 2470 2471 SDValue 2472 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2473 bool isVarArg, 2474 const SmallVectorImpl<ISD::OutputArg> &Outs, 2475 const SmallVectorImpl<SDValue> &OutVals, 2476 const SDLoc &dl, SelectionDAG &DAG) const { 2477 // CCValAssign - represent the assignment of the return value to a location. 2478 SmallVector<CCValAssign, 16> RVLocs; 2479 2480 // CCState - Info about the registers and stack slots. 2481 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2482 *DAG.getContext()); 2483 2484 // Analyze outgoing return values. 2485 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2486 2487 SDValue Flag; 2488 SmallVector<SDValue, 4> RetOps; 2489 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2490 bool isLittleEndian = Subtarget->isLittle(); 2491 2492 MachineFunction &MF = DAG.getMachineFunction(); 2493 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2494 AFI->setReturnRegsCount(RVLocs.size()); 2495 2496 // Copy the result values into the output registers. 2497 for (unsigned i = 0, realRVLocIdx = 0; 2498 i != RVLocs.size(); 2499 ++i, ++realRVLocIdx) { 2500 CCValAssign &VA = RVLocs[i]; 2501 assert(VA.isRegLoc() && "Can only return in registers!"); 2502 2503 SDValue Arg = OutVals[realRVLocIdx]; 2504 bool ReturnF16 = false; 2505 2506 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2507 // Half-precision return values can be returned like this: 2508 // 2509 // t11 f16 = fadd ... 2510 // t12: i16 = bitcast t11 2511 // t13: i32 = zero_extend t12 2512 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2513 // 2514 // to avoid code generation for bitcasts, we simply set Arg to the node 2515 // that produces the f16 value, t11 in this case. 2516 // 2517 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2518 SDValue ZE = Arg.getOperand(0); 2519 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2520 SDValue BC = ZE.getOperand(0); 2521 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2522 Arg = BC.getOperand(0); 2523 ReturnF16 = true; 2524 } 2525 } 2526 } 2527 } 2528 2529 switch (VA.getLocInfo()) { 2530 default: llvm_unreachable("Unknown loc info!"); 2531 case CCValAssign::Full: break; 2532 case CCValAssign::BCvt: 2533 if (!ReturnF16) 2534 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2535 break; 2536 } 2537 2538 if (VA.needsCustom()) { 2539 if (VA.getLocVT() == MVT::v2f64) { 2540 // Extract the first half and return it in two registers. 2541 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2542 DAG.getConstant(0, dl, MVT::i32)); 2543 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2544 DAG.getVTList(MVT::i32, MVT::i32), Half); 2545 2546 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2547 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2548 Flag); 2549 Flag = Chain.getValue(1); 2550 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2551 VA = RVLocs[++i]; // skip ahead to next loc 2552 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2553 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2554 Flag); 2555 Flag = Chain.getValue(1); 2556 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2557 VA = RVLocs[++i]; // skip ahead to next loc 2558 2559 // Extract the 2nd half and fall through to handle it as an f64 value. 2560 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2561 DAG.getConstant(1, dl, MVT::i32)); 2562 } 2563 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2564 // available. 2565 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2566 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2567 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2568 fmrrd.getValue(isLittleEndian ? 0 : 1), 2569 Flag); 2570 Flag = Chain.getValue(1); 2571 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2572 VA = RVLocs[++i]; // skip ahead to next loc 2573 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2574 fmrrd.getValue(isLittleEndian ? 1 : 0), 2575 Flag); 2576 } else 2577 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2578 2579 // Guarantee that all emitted copies are 2580 // stuck together, avoiding something bad. 2581 Flag = Chain.getValue(1); 2582 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2583 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2584 } 2585 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2586 const MCPhysReg *I = 2587 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2588 if (I) { 2589 for (; *I; ++I) { 2590 if (ARM::GPRRegClass.contains(*I)) 2591 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2592 else if (ARM::DPRRegClass.contains(*I)) 2593 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2594 else 2595 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2596 } 2597 } 2598 2599 // Update chain and glue. 2600 RetOps[0] = Chain; 2601 if (Flag.getNode()) 2602 RetOps.push_back(Flag); 2603 2604 // CPUs which aren't M-class use a special sequence to return from 2605 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2606 // though we use "subs pc, lr, #N"). 2607 // 2608 // M-class CPUs actually use a normal return sequence with a special 2609 // (hardware-provided) value in LR, so the normal code path works. 2610 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2611 !Subtarget->isMClass()) { 2612 if (Subtarget->isThumb1Only()) 2613 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2614 return LowerInterruptReturn(RetOps, dl, DAG); 2615 } 2616 2617 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2618 } 2619 2620 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2621 if (N->getNumValues() != 1) 2622 return false; 2623 if (!N->hasNUsesOfValue(1, 0)) 2624 return false; 2625 2626 SDValue TCChain = Chain; 2627 SDNode *Copy = *N->use_begin(); 2628 if (Copy->getOpcode() == ISD::CopyToReg) { 2629 // If the copy has a glue operand, we conservatively assume it isn't safe to 2630 // perform a tail call. 2631 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2632 return false; 2633 TCChain = Copy->getOperand(0); 2634 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2635 SDNode *VMov = Copy; 2636 // f64 returned in a pair of GPRs. 2637 SmallPtrSet<SDNode*, 2> Copies; 2638 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2639 UI != UE; ++UI) { 2640 if (UI->getOpcode() != ISD::CopyToReg) 2641 return false; 2642 Copies.insert(*UI); 2643 } 2644 if (Copies.size() > 2) 2645 return false; 2646 2647 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2648 UI != UE; ++UI) { 2649 SDValue UseChain = UI->getOperand(0); 2650 if (Copies.count(UseChain.getNode())) 2651 // Second CopyToReg 2652 Copy = *UI; 2653 else { 2654 // We are at the top of this chain. 2655 // If the copy has a glue operand, we conservatively assume it 2656 // isn't safe to perform a tail call. 2657 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2658 return false; 2659 // First CopyToReg 2660 TCChain = UseChain; 2661 } 2662 } 2663 } else if (Copy->getOpcode() == ISD::BITCAST) { 2664 // f32 returned in a single GPR. 2665 if (!Copy->hasOneUse()) 2666 return false; 2667 Copy = *Copy->use_begin(); 2668 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2669 return false; 2670 // If the copy has a glue operand, we conservatively assume it isn't safe to 2671 // perform a tail call. 2672 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2673 return false; 2674 TCChain = Copy->getOperand(0); 2675 } else { 2676 return false; 2677 } 2678 2679 bool HasRet = false; 2680 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2681 UI != UE; ++UI) { 2682 if (UI->getOpcode() != ARMISD::RET_FLAG && 2683 UI->getOpcode() != ARMISD::INTRET_FLAG) 2684 return false; 2685 HasRet = true; 2686 } 2687 2688 if (!HasRet) 2689 return false; 2690 2691 Chain = TCChain; 2692 return true; 2693 } 2694 2695 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2696 if (!Subtarget->supportsTailCall()) 2697 return false; 2698 2699 auto Attr = 2700 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2701 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2702 return false; 2703 2704 return true; 2705 } 2706 2707 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2708 // and pass the lower and high parts through. 2709 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2710 SDLoc DL(Op); 2711 SDValue WriteValue = Op->getOperand(2); 2712 2713 // This function is only supposed to be called for i64 type argument. 2714 assert(WriteValue.getValueType() == MVT::i64 2715 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2716 2717 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2718 DAG.getConstant(0, DL, MVT::i32)); 2719 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2720 DAG.getConstant(1, DL, MVT::i32)); 2721 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2722 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2723 } 2724 2725 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2726 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2727 // one of the above mentioned nodes. It has to be wrapped because otherwise 2728 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2729 // be used to form addressing mode. These wrapped nodes will be selected 2730 // into MOVi. 2731 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2732 SelectionDAG &DAG) const { 2733 EVT PtrVT = Op.getValueType(); 2734 // FIXME there is no actual debug info here 2735 SDLoc dl(Op); 2736 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2737 SDValue Res; 2738 2739 // When generating execute-only code Constant Pools must be promoted to the 2740 // global data section. It's a bit ugly that we can't share them across basic 2741 // blocks, but this way we guarantee that execute-only behaves correct with 2742 // position-independent addressing modes. 2743 if (Subtarget->genExecuteOnly()) { 2744 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2745 auto T = const_cast<Type*>(CP->getType()); 2746 auto C = const_cast<Constant*>(CP->getConstVal()); 2747 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2748 getFunction().getParent()); 2749 auto GV = new GlobalVariable( 2750 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2751 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2752 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2753 Twine(AFI->createPICLabelUId()) 2754 ); 2755 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2756 dl, PtrVT); 2757 return LowerGlobalAddress(GA, DAG); 2758 } 2759 2760 if (CP->isMachineConstantPoolEntry()) 2761 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2762 CP->getAlignment()); 2763 else 2764 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2765 CP->getAlignment()); 2766 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2767 } 2768 2769 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2770 return MachineJumpTableInfo::EK_Inline; 2771 } 2772 2773 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2774 SelectionDAG &DAG) const { 2775 MachineFunction &MF = DAG.getMachineFunction(); 2776 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2777 unsigned ARMPCLabelIndex = 0; 2778 SDLoc DL(Op); 2779 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2780 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2781 SDValue CPAddr; 2782 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2783 if (!IsPositionIndependent) { 2784 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2785 } else { 2786 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2787 ARMPCLabelIndex = AFI->createPICLabelUId(); 2788 ARMConstantPoolValue *CPV = 2789 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2790 ARMCP::CPBlockAddress, PCAdj); 2791 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2792 } 2793 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2794 SDValue Result = DAG.getLoad( 2795 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2796 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2797 if (!IsPositionIndependent) 2798 return Result; 2799 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2800 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2801 } 2802 2803 /// Convert a TLS address reference into the correct sequence of loads 2804 /// and calls to compute the variable's address for Darwin, and return an 2805 /// SDValue containing the final node. 2806 2807 /// Darwin only has one TLS scheme which must be capable of dealing with the 2808 /// fully general situation, in the worst case. This means: 2809 /// + "extern __thread" declaration. 2810 /// + Defined in a possibly unknown dynamic library. 2811 /// 2812 /// The general system is that each __thread variable has a [3 x i32] descriptor 2813 /// which contains information used by the runtime to calculate the address. The 2814 /// only part of this the compiler needs to know about is the first word, which 2815 /// contains a function pointer that must be called with the address of the 2816 /// entire descriptor in "r0". 2817 /// 2818 /// Since this descriptor may be in a different unit, in general access must 2819 /// proceed along the usual ARM rules. A common sequence to produce is: 2820 /// 2821 /// movw rT1, :lower16:_var$non_lazy_ptr 2822 /// movt rT1, :upper16:_var$non_lazy_ptr 2823 /// ldr r0, [rT1] 2824 /// ldr rT2, [r0] 2825 /// blx rT2 2826 /// [...address now in r0...] 2827 SDValue 2828 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2829 SelectionDAG &DAG) const { 2830 assert(Subtarget->isTargetDarwin() && 2831 "This function expects a Darwin target"); 2832 SDLoc DL(Op); 2833 2834 // First step is to get the address of the actua global symbol. This is where 2835 // the TLS descriptor lives. 2836 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2837 2838 // The first entry in the descriptor is a function pointer that we must call 2839 // to obtain the address of the variable. 2840 SDValue Chain = DAG.getEntryNode(); 2841 SDValue FuncTLVGet = DAG.getLoad( 2842 MVT::i32, DL, Chain, DescAddr, 2843 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2844 /* Alignment = */ 4, 2845 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2846 MachineMemOperand::MOInvariant); 2847 Chain = FuncTLVGet.getValue(1); 2848 2849 MachineFunction &F = DAG.getMachineFunction(); 2850 MachineFrameInfo &MFI = F.getFrameInfo(); 2851 MFI.setAdjustsStack(true); 2852 2853 // TLS calls preserve all registers except those that absolutely must be 2854 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2855 // silly). 2856 auto TRI = 2857 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 2858 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2859 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2860 2861 // Finally, we can make the call. This is just a degenerate version of a 2862 // normal AArch64 call node: r0 takes the address of the descriptor, and 2863 // returns the address of the variable in this thread. 2864 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2865 Chain = 2866 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2867 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2868 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2869 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2870 } 2871 2872 SDValue 2873 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2874 SelectionDAG &DAG) const { 2875 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2876 2877 SDValue Chain = DAG.getEntryNode(); 2878 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2879 SDLoc DL(Op); 2880 2881 // Load the current TEB (thread environment block) 2882 SDValue Ops[] = {Chain, 2883 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2884 DAG.getConstant(15, DL, MVT::i32), 2885 DAG.getConstant(0, DL, MVT::i32), 2886 DAG.getConstant(13, DL, MVT::i32), 2887 DAG.getConstant(0, DL, MVT::i32), 2888 DAG.getConstant(2, DL, MVT::i32)}; 2889 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2890 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2891 2892 SDValue TEB = CurrentTEB.getValue(0); 2893 Chain = CurrentTEB.getValue(1); 2894 2895 // Load the ThreadLocalStoragePointer from the TEB 2896 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2897 SDValue TLSArray = 2898 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2899 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2900 2901 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2902 // offset into the TLSArray. 2903 2904 // Load the TLS index from the C runtime 2905 SDValue TLSIndex = 2906 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2907 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2908 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2909 2910 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2911 DAG.getConstant(2, DL, MVT::i32)); 2912 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2913 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2914 MachinePointerInfo()); 2915 2916 // Get the offset of the start of the .tls section (section base) 2917 const auto *GA = cast<GlobalAddressSDNode>(Op); 2918 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2919 SDValue Offset = DAG.getLoad( 2920 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2921 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2922 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2923 2924 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2925 } 2926 2927 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2928 SDValue 2929 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2930 SelectionDAG &DAG) const { 2931 SDLoc dl(GA); 2932 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2933 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2934 MachineFunction &MF = DAG.getMachineFunction(); 2935 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2936 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2937 ARMConstantPoolValue *CPV = 2938 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2939 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2940 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2941 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2942 Argument = DAG.getLoad( 2943 PtrVT, dl, DAG.getEntryNode(), Argument, 2944 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2945 SDValue Chain = Argument.getValue(1); 2946 2947 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2948 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2949 2950 // call __tls_get_addr. 2951 ArgListTy Args; 2952 ArgListEntry Entry; 2953 Entry.Node = Argument; 2954 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2955 Args.push_back(Entry); 2956 2957 // FIXME: is there useful debug info available here? 2958 TargetLowering::CallLoweringInfo CLI(DAG); 2959 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2960 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2961 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2962 2963 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2964 return CallResult.first; 2965 } 2966 2967 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2968 // "local exec" model. 2969 SDValue 2970 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2971 SelectionDAG &DAG, 2972 TLSModel::Model model) const { 2973 const GlobalValue *GV = GA->getGlobal(); 2974 SDLoc dl(GA); 2975 SDValue Offset; 2976 SDValue Chain = DAG.getEntryNode(); 2977 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2978 // Get the Thread Pointer 2979 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2980 2981 if (model == TLSModel::InitialExec) { 2982 MachineFunction &MF = DAG.getMachineFunction(); 2983 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2984 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2985 // Initial exec model. 2986 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2987 ARMConstantPoolValue *CPV = 2988 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2989 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2990 true); 2991 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2992 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2993 Offset = DAG.getLoad( 2994 PtrVT, dl, Chain, Offset, 2995 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2996 Chain = Offset.getValue(1); 2997 2998 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2999 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 3000 3001 Offset = DAG.getLoad( 3002 PtrVT, dl, Chain, Offset, 3003 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3004 } else { 3005 // local exec model 3006 assert(model == TLSModel::LocalExec); 3007 ARMConstantPoolValue *CPV = 3008 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3009 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3010 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3011 Offset = DAG.getLoad( 3012 PtrVT, dl, Chain, Offset, 3013 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3014 } 3015 3016 // The address of the thread local variable is the add of the thread 3017 // pointer with the offset of the variable. 3018 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3019 } 3020 3021 SDValue 3022 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3023 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3024 if (DAG.getTarget().useEmulatedTLS()) 3025 return LowerToTLSEmulatedModel(GA, DAG); 3026 3027 if (Subtarget->isTargetDarwin()) 3028 return LowerGlobalTLSAddressDarwin(Op, DAG); 3029 3030 if (Subtarget->isTargetWindows()) 3031 return LowerGlobalTLSAddressWindows(Op, DAG); 3032 3033 // TODO: implement the "local dynamic" model 3034 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3035 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3036 3037 switch (model) { 3038 case TLSModel::GeneralDynamic: 3039 case TLSModel::LocalDynamic: 3040 return LowerToTLSGeneralDynamicModel(GA, DAG); 3041 case TLSModel::InitialExec: 3042 case TLSModel::LocalExec: 3043 return LowerToTLSExecModels(GA, DAG, model); 3044 } 3045 llvm_unreachable("bogus TLS model"); 3046 } 3047 3048 /// Return true if all users of V are within function F, looking through 3049 /// ConstantExprs. 3050 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3051 SmallVector<const User*,4> Worklist; 3052 for (auto *U : V->users()) 3053 Worklist.push_back(U); 3054 while (!Worklist.empty()) { 3055 auto *U = Worklist.pop_back_val(); 3056 if (isa<ConstantExpr>(U)) { 3057 for (auto *UU : U->users()) 3058 Worklist.push_back(UU); 3059 continue; 3060 } 3061 3062 auto *I = dyn_cast<Instruction>(U); 3063 if (!I || I->getParent()->getParent() != F) 3064 return false; 3065 } 3066 return true; 3067 } 3068 3069 /// Return true if all users of V are within some (any) function, looking through 3070 /// ConstantExprs. In other words, are there any global constant users? 3071 static bool allUsersAreInFunctions(const Value *V) { 3072 SmallVector<const User*,4> Worklist; 3073 for (auto *U : V->users()) 3074 Worklist.push_back(U); 3075 while (!Worklist.empty()) { 3076 auto *U = Worklist.pop_back_val(); 3077 if (isa<ConstantExpr>(U)) { 3078 for (auto *UU : U->users()) 3079 Worklist.push_back(UU); 3080 continue; 3081 } 3082 3083 if (!isa<Instruction>(U)) 3084 return false; 3085 } 3086 return true; 3087 } 3088 3089 // Return true if T is an integer, float or an array/vector of either. 3090 static bool isSimpleType(Type *T) { 3091 if (T->isIntegerTy() || T->isFloatingPointTy()) 3092 return true; 3093 Type *SubT = nullptr; 3094 if (T->isArrayTy()) 3095 SubT = T->getArrayElementType(); 3096 else if (T->isVectorTy()) 3097 SubT = T->getVectorElementType(); 3098 else 3099 return false; 3100 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 3101 } 3102 3103 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 3104 EVT PtrVT, const SDLoc &dl) { 3105 // If we're creating a pool entry for a constant global with unnamed address, 3106 // and the global is small enough, we can emit it inline into the constant pool 3107 // to save ourselves an indirection. 3108 // 3109 // This is a win if the constant is only used in one function (so it doesn't 3110 // need to be duplicated) or duplicating the constant wouldn't increase code 3111 // size (implying the constant is no larger than 4 bytes). 3112 const Function &F = DAG.getMachineFunction().getFunction(); 3113 3114 // We rely on this decision to inline being idemopotent and unrelated to the 3115 // use-site. We know that if we inline a variable at one use site, we'll 3116 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3117 // doesn't know about this optimization, so bail out if it's enabled else 3118 // we could decide to inline here (and thus never emit the GV) but require 3119 // the GV from fast-isel generated code. 3120 if (!EnableConstpoolPromotion || 3121 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3122 return SDValue(); 3123 3124 auto *GVar = dyn_cast<GlobalVariable>(GV); 3125 if (!GVar || !GVar->hasInitializer() || 3126 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3127 !GVar->hasLocalLinkage()) 3128 return SDValue(); 3129 3130 // Ensure that we don't try and inline any type that contains pointers. If 3131 // we inline a value that contains relocations, we move the relocations from 3132 // .data to .text which is not ideal. 3133 auto *Init = GVar->getInitializer(); 3134 if (!isSimpleType(Init->getType())) 3135 return SDValue(); 3136 3137 // The constant islands pass can only really deal with alignment requests 3138 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3139 // any type wanting greater alignment requirements than 4 bytes. We also 3140 // can only promote constants that are multiples of 4 bytes in size or 3141 // are paddable to a multiple of 4. Currently we only try and pad constants 3142 // that are strings for simplicity. 3143 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3144 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3145 unsigned Align = GVar->getAlignment(); 3146 unsigned RequiredPadding = 4 - (Size % 4); 3147 bool PaddingPossible = 3148 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3149 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3150 Size == 0) 3151 return SDValue(); 3152 3153 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3154 MachineFunction &MF = DAG.getMachineFunction(); 3155 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3156 3157 // We can't bloat the constant pool too much, else the ConstantIslands pass 3158 // may fail to converge. If we haven't promoted this global yet (it may have 3159 // multiple uses), and promoting it would increase the constant pool size (Sz 3160 // > 4), ensure we have space to do so up to MaxTotal. 3161 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3162 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3163 ConstpoolPromotionMaxTotal) 3164 return SDValue(); 3165 3166 // This is only valid if all users are in a single function OR it has users 3167 // in multiple functions but it no larger than a pointer. We also check if 3168 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3169 // address taken. 3170 if (!allUsersAreInFunction(GVar, &F) && 3171 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3172 return SDValue(); 3173 3174 // We're going to inline this global. Pad it out if needed. 3175 if (RequiredPadding != 4) { 3176 StringRef S = CDAInit->getAsString(); 3177 3178 SmallVector<uint8_t,16> V(S.size()); 3179 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3180 while (RequiredPadding--) 3181 V.push_back(0); 3182 Init = ConstantDataArray::get(*DAG.getContext(), V); 3183 } 3184 3185 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3186 SDValue CPAddr = 3187 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3188 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3189 AFI->markGlobalAsPromotedToConstantPool(GVar); 3190 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3191 PaddedSize - 4); 3192 } 3193 ++NumConstpoolPromoted; 3194 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3195 } 3196 3197 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3198 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3199 GV = GA->getBaseObject(); 3200 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3201 isa<Function>(GV); 3202 } 3203 3204 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3205 SelectionDAG &DAG) const { 3206 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3207 default: llvm_unreachable("unknown object format"); 3208 case Triple::COFF: 3209 return LowerGlobalAddressWindows(Op, DAG); 3210 case Triple::ELF: 3211 return LowerGlobalAddressELF(Op, DAG); 3212 case Triple::MachO: 3213 return LowerGlobalAddressDarwin(Op, DAG); 3214 } 3215 } 3216 3217 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3218 SelectionDAG &DAG) const { 3219 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3220 SDLoc dl(Op); 3221 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3222 const TargetMachine &TM = getTargetMachine(); 3223 bool IsRO = isReadOnly(GV); 3224 3225 // promoteToConstantPool only if not generating XO text section 3226 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3227 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3228 return V; 3229 3230 if (isPositionIndependent()) { 3231 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3232 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3233 UseGOT_PREL ? ARMII::MO_GOT : 0); 3234 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3235 if (UseGOT_PREL) 3236 Result = 3237 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3238 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3239 return Result; 3240 } else if (Subtarget->isROPI() && IsRO) { 3241 // PC-relative. 3242 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3243 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3244 return Result; 3245 } else if (Subtarget->isRWPI() && !IsRO) { 3246 // SB-relative. 3247 SDValue RelAddr; 3248 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3249 ++NumMovwMovt; 3250 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3251 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3252 } else { // use literal pool for address constant 3253 ARMConstantPoolValue *CPV = 3254 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3255 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3256 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3257 RelAddr = DAG.getLoad( 3258 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3259 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3260 } 3261 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3262 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3263 return Result; 3264 } 3265 3266 // If we have T2 ops, we can materialize the address directly via movt/movw 3267 // pair. This is always cheaper. 3268 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3269 ++NumMovwMovt; 3270 // FIXME: Once remat is capable of dealing with instructions with register 3271 // operands, expand this into two nodes. 3272 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3273 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3274 } else { 3275 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3276 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3277 return DAG.getLoad( 3278 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3279 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3280 } 3281 } 3282 3283 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3284 SelectionDAG &DAG) const { 3285 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3286 "ROPI/RWPI not currently supported for Darwin"); 3287 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3288 SDLoc dl(Op); 3289 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3290 3291 if (Subtarget->useMovt(DAG.getMachineFunction())) 3292 ++NumMovwMovt; 3293 3294 // FIXME: Once remat is capable of dealing with instructions with register 3295 // operands, expand this into multiple nodes 3296 unsigned Wrapper = 3297 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3298 3299 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3300 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3301 3302 if (Subtarget->isGVIndirectSymbol(GV)) 3303 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3304 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3305 return Result; 3306 } 3307 3308 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3309 SelectionDAG &DAG) const { 3310 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3311 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3312 "Windows on ARM expects to use movw/movt"); 3313 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3314 "ROPI/RWPI not currently supported for Windows"); 3315 3316 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3317 const ARMII::TOF TargetFlags = 3318 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3319 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3320 SDValue Result; 3321 SDLoc DL(Op); 3322 3323 ++NumMovwMovt; 3324 3325 // FIXME: Once remat is capable of dealing with instructions with register 3326 // operands, expand this into two nodes. 3327 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3328 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3329 TargetFlags)); 3330 if (GV->hasDLLImportStorageClass()) 3331 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3332 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3333 return Result; 3334 } 3335 3336 SDValue 3337 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3338 SDLoc dl(Op); 3339 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3340 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3341 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3342 Op.getOperand(1), Val); 3343 } 3344 3345 SDValue 3346 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3347 SDLoc dl(Op); 3348 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3349 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3350 } 3351 3352 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3353 SelectionDAG &DAG) const { 3354 SDLoc dl(Op); 3355 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3356 Op.getOperand(0)); 3357 } 3358 3359 SDValue 3360 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3361 const ARMSubtarget *Subtarget) const { 3362 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3363 SDLoc dl(Op); 3364 switch (IntNo) { 3365 default: return SDValue(); // Don't custom lower most intrinsics. 3366 case Intrinsic::thread_pointer: { 3367 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3368 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3369 } 3370 case Intrinsic::eh_sjlj_lsda: { 3371 MachineFunction &MF = DAG.getMachineFunction(); 3372 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3373 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3374 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3375 SDValue CPAddr; 3376 bool IsPositionIndependent = isPositionIndependent(); 3377 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3378 ARMConstantPoolValue *CPV = 3379 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3380 ARMCP::CPLSDA, PCAdj); 3381 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3382 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3383 SDValue Result = DAG.getLoad( 3384 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3385 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3386 3387 if (IsPositionIndependent) { 3388 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3389 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3390 } 3391 return Result; 3392 } 3393 case Intrinsic::arm_neon_vabs: 3394 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3395 Op.getOperand(1)); 3396 case Intrinsic::arm_neon_vmulls: 3397 case Intrinsic::arm_neon_vmullu: { 3398 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3399 ? ARMISD::VMULLs : ARMISD::VMULLu; 3400 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3401 Op.getOperand(1), Op.getOperand(2)); 3402 } 3403 case Intrinsic::arm_neon_vminnm: 3404 case Intrinsic::arm_neon_vmaxnm: { 3405 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3406 ? ISD::FMINNUM : ISD::FMAXNUM; 3407 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3408 Op.getOperand(1), Op.getOperand(2)); 3409 } 3410 case Intrinsic::arm_neon_vminu: 3411 case Intrinsic::arm_neon_vmaxu: { 3412 if (Op.getValueType().isFloatingPoint()) 3413 return SDValue(); 3414 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3415 ? ISD::UMIN : ISD::UMAX; 3416 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3417 Op.getOperand(1), Op.getOperand(2)); 3418 } 3419 case Intrinsic::arm_neon_vmins: 3420 case Intrinsic::arm_neon_vmaxs: { 3421 // v{min,max}s is overloaded between signed integers and floats. 3422 if (!Op.getValueType().isFloatingPoint()) { 3423 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3424 ? ISD::SMIN : ISD::SMAX; 3425 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3426 Op.getOperand(1), Op.getOperand(2)); 3427 } 3428 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3429 ? ISD::FMINNAN : ISD::FMAXNAN; 3430 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3431 Op.getOperand(1), Op.getOperand(2)); 3432 } 3433 case Intrinsic::arm_neon_vtbl1: 3434 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3435 Op.getOperand(1), Op.getOperand(2)); 3436 case Intrinsic::arm_neon_vtbl2: 3437 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3438 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3439 } 3440 } 3441 3442 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3443 const ARMSubtarget *Subtarget) { 3444 SDLoc dl(Op); 3445 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3446 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3447 if (SSID == SyncScope::SingleThread) 3448 return Op; 3449 3450 if (!Subtarget->hasDataBarrier()) { 3451 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3452 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3453 // here. 3454 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3455 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3456 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3457 DAG.getConstant(0, dl, MVT::i32)); 3458 } 3459 3460 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3461 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3462 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3463 if (Subtarget->isMClass()) { 3464 // Only a full system barrier exists in the M-class architectures. 3465 Domain = ARM_MB::SY; 3466 } else if (Subtarget->preferISHSTBarriers() && 3467 Ord == AtomicOrdering::Release) { 3468 // Swift happens to implement ISHST barriers in a way that's compatible with 3469 // Release semantics but weaker than ISH so we'd be fools not to use 3470 // it. Beware: other processors probably don't! 3471 Domain = ARM_MB::ISHST; 3472 } 3473 3474 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3475 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3476 DAG.getConstant(Domain, dl, MVT::i32)); 3477 } 3478 3479 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3480 const ARMSubtarget *Subtarget) { 3481 // ARM pre v5TE and Thumb1 does not have preload instructions. 3482 if (!(Subtarget->isThumb2() || 3483 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3484 // Just preserve the chain. 3485 return Op.getOperand(0); 3486 3487 SDLoc dl(Op); 3488 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3489 if (!isRead && 3490 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3491 // ARMv7 with MP extension has PLDW. 3492 return Op.getOperand(0); 3493 3494 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3495 if (Subtarget->isThumb()) { 3496 // Invert the bits. 3497 isRead = ~isRead & 1; 3498 isData = ~isData & 1; 3499 } 3500 3501 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3502 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3503 DAG.getConstant(isData, dl, MVT::i32)); 3504 } 3505 3506 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3507 MachineFunction &MF = DAG.getMachineFunction(); 3508 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3509 3510 // vastart just stores the address of the VarArgsFrameIndex slot into the 3511 // memory location argument. 3512 SDLoc dl(Op); 3513 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3514 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3515 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3516 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3517 MachinePointerInfo(SV)); 3518 } 3519 3520 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3521 CCValAssign &NextVA, 3522 SDValue &Root, 3523 SelectionDAG &DAG, 3524 const SDLoc &dl) const { 3525 MachineFunction &MF = DAG.getMachineFunction(); 3526 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3527 3528 const TargetRegisterClass *RC; 3529 if (AFI->isThumb1OnlyFunction()) 3530 RC = &ARM::tGPRRegClass; 3531 else 3532 RC = &ARM::GPRRegClass; 3533 3534 // Transform the arguments stored in physical registers into virtual ones. 3535 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3536 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3537 3538 SDValue ArgValue2; 3539 if (NextVA.isMemLoc()) { 3540 MachineFrameInfo &MFI = MF.getFrameInfo(); 3541 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3542 3543 // Create load node to retrieve arguments from the stack. 3544 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3545 ArgValue2 = DAG.getLoad( 3546 MVT::i32, dl, Root, FIN, 3547 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3548 } else { 3549 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3550 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3551 } 3552 if (!Subtarget->isLittle()) 3553 std::swap (ArgValue, ArgValue2); 3554 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3555 } 3556 3557 // The remaining GPRs hold either the beginning of variable-argument 3558 // data, or the beginning of an aggregate passed by value (usually 3559 // byval). Either way, we allocate stack slots adjacent to the data 3560 // provided by our caller, and store the unallocated registers there. 3561 // If this is a variadic function, the va_list pointer will begin with 3562 // these values; otherwise, this reassembles a (byval) structure that 3563 // was split between registers and memory. 3564 // Return: The frame index registers were stored into. 3565 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3566 const SDLoc &dl, SDValue &Chain, 3567 const Value *OrigArg, 3568 unsigned InRegsParamRecordIdx, 3569 int ArgOffset, unsigned ArgSize) const { 3570 // Currently, two use-cases possible: 3571 // Case #1. Non-var-args function, and we meet first byval parameter. 3572 // Setup first unallocated register as first byval register; 3573 // eat all remained registers 3574 // (these two actions are performed by HandleByVal method). 3575 // Then, here, we initialize stack frame with 3576 // "store-reg" instructions. 3577 // Case #2. Var-args function, that doesn't contain byval parameters. 3578 // The same: eat all remained unallocated registers, 3579 // initialize stack frame. 3580 3581 MachineFunction &MF = DAG.getMachineFunction(); 3582 MachineFrameInfo &MFI = MF.getFrameInfo(); 3583 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3584 unsigned RBegin, REnd; 3585 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3586 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3587 } else { 3588 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3589 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3590 REnd = ARM::R4; 3591 } 3592 3593 if (REnd != RBegin) 3594 ArgOffset = -4 * (ARM::R4 - RBegin); 3595 3596 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3597 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3598 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3599 3600 SmallVector<SDValue, 4> MemOps; 3601 const TargetRegisterClass *RC = 3602 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3603 3604 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3605 unsigned VReg = MF.addLiveIn(Reg, RC); 3606 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3607 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3608 MachinePointerInfo(OrigArg, 4 * i)); 3609 MemOps.push_back(Store); 3610 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3611 } 3612 3613 if (!MemOps.empty()) 3614 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3615 return FrameIndex; 3616 } 3617 3618 // Setup stack frame, the va_list pointer will start from. 3619 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3620 const SDLoc &dl, SDValue &Chain, 3621 unsigned ArgOffset, 3622 unsigned TotalArgRegsSaveSize, 3623 bool ForceMutable) const { 3624 MachineFunction &MF = DAG.getMachineFunction(); 3625 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3626 3627 // Try to store any remaining integer argument regs 3628 // to their spots on the stack so that they may be loaded by dereferencing 3629 // the result of va_next. 3630 // If there is no regs to be stored, just point address after last 3631 // argument passed via stack. 3632 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3633 CCInfo.getInRegsParamsCount(), 3634 CCInfo.getNextStackOffset(), 4); 3635 AFI->setVarArgsFrameIndex(FrameIndex); 3636 } 3637 3638 SDValue ARMTargetLowering::LowerFormalArguments( 3639 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3640 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3641 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3642 MachineFunction &MF = DAG.getMachineFunction(); 3643 MachineFrameInfo &MFI = MF.getFrameInfo(); 3644 3645 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3646 3647 // Assign locations to all of the incoming arguments. 3648 SmallVector<CCValAssign, 16> ArgLocs; 3649 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3650 *DAG.getContext()); 3651 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3652 3653 SmallVector<SDValue, 16> ArgValues; 3654 SDValue ArgValue; 3655 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3656 unsigned CurArgIdx = 0; 3657 3658 // Initially ArgRegsSaveSize is zero. 3659 // Then we increase this value each time we meet byval parameter. 3660 // We also increase this value in case of varargs function. 3661 AFI->setArgRegsSaveSize(0); 3662 3663 // Calculate the amount of stack space that we need to allocate to store 3664 // byval and variadic arguments that are passed in registers. 3665 // We need to know this before we allocate the first byval or variadic 3666 // argument, as they will be allocated a stack slot below the CFA (Canonical 3667 // Frame Address, the stack pointer at entry to the function). 3668 unsigned ArgRegBegin = ARM::R4; 3669 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3670 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3671 break; 3672 3673 CCValAssign &VA = ArgLocs[i]; 3674 unsigned Index = VA.getValNo(); 3675 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3676 if (!Flags.isByVal()) 3677 continue; 3678 3679 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3680 unsigned RBegin, REnd; 3681 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3682 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3683 3684 CCInfo.nextInRegsParam(); 3685 } 3686 CCInfo.rewindByValRegsInfo(); 3687 3688 int lastInsIndex = -1; 3689 if (isVarArg && MFI.hasVAStart()) { 3690 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3691 if (RegIdx != array_lengthof(GPRArgRegs)) 3692 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3693 } 3694 3695 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3696 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3697 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3698 3699 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3700 CCValAssign &VA = ArgLocs[i]; 3701 if (Ins[VA.getValNo()].isOrigArg()) { 3702 std::advance(CurOrigArg, 3703 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3704 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3705 } 3706 // Arguments stored in registers. 3707 if (VA.isRegLoc()) { 3708 EVT RegVT = VA.getLocVT(); 3709 3710 if (VA.needsCustom()) { 3711 // f64 and vector types are split up into multiple registers or 3712 // combinations of registers and stack slots. 3713 if (VA.getLocVT() == MVT::v2f64) { 3714 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3715 Chain, DAG, dl); 3716 VA = ArgLocs[++i]; // skip ahead to next loc 3717 SDValue ArgValue2; 3718 if (VA.isMemLoc()) { 3719 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3720 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3721 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3722 MachinePointerInfo::getFixedStack( 3723 DAG.getMachineFunction(), FI)); 3724 } else { 3725 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3726 Chain, DAG, dl); 3727 } 3728 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3729 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3730 ArgValue, ArgValue1, 3731 DAG.getIntPtrConstant(0, dl)); 3732 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3733 ArgValue, ArgValue2, 3734 DAG.getIntPtrConstant(1, dl)); 3735 } else 3736 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3737 } else { 3738 const TargetRegisterClass *RC; 3739 3740 3741 if (RegVT == MVT::f16) 3742 RC = &ARM::HPRRegClass; 3743 else if (RegVT == MVT::f32) 3744 RC = &ARM::SPRRegClass; 3745 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 3746 RC = &ARM::DPRRegClass; 3747 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 3748 RC = &ARM::QPRRegClass; 3749 else if (RegVT == MVT::i32) 3750 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3751 : &ARM::GPRRegClass; 3752 else 3753 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3754 3755 // Transform the arguments in physical registers into virtual ones. 3756 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3757 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3758 } 3759 3760 // If this is an 8 or 16-bit value, it is really passed promoted 3761 // to 32 bits. Insert an assert[sz]ext to capture this, then 3762 // truncate to the right size. 3763 switch (VA.getLocInfo()) { 3764 default: llvm_unreachable("Unknown loc info!"); 3765 case CCValAssign::Full: break; 3766 case CCValAssign::BCvt: 3767 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3768 break; 3769 case CCValAssign::SExt: 3770 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3771 DAG.getValueType(VA.getValVT())); 3772 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3773 break; 3774 case CCValAssign::ZExt: 3775 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3776 DAG.getValueType(VA.getValVT())); 3777 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3778 break; 3779 } 3780 3781 InVals.push_back(ArgValue); 3782 } else { // VA.isRegLoc() 3783 // sanity check 3784 assert(VA.isMemLoc()); 3785 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3786 3787 int index = VA.getValNo(); 3788 3789 // Some Ins[] entries become multiple ArgLoc[] entries. 3790 // Process them only once. 3791 if (index != lastInsIndex) 3792 { 3793 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3794 // FIXME: For now, all byval parameter objects are marked mutable. 3795 // This can be changed with more analysis. 3796 // In case of tail call optimization mark all arguments mutable. 3797 // Since they could be overwritten by lowering of arguments in case of 3798 // a tail call. 3799 if (Flags.isByVal()) { 3800 assert(Ins[index].isOrigArg() && 3801 "Byval arguments cannot be implicit"); 3802 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3803 3804 int FrameIndex = StoreByValRegs( 3805 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3806 VA.getLocMemOffset(), Flags.getByValSize()); 3807 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3808 CCInfo.nextInRegsParam(); 3809 } else { 3810 unsigned FIOffset = VA.getLocMemOffset(); 3811 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3812 FIOffset, true); 3813 3814 // Create load nodes to retrieve arguments from the stack. 3815 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3816 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3817 MachinePointerInfo::getFixedStack( 3818 DAG.getMachineFunction(), FI))); 3819 } 3820 lastInsIndex = index; 3821 } 3822 } 3823 } 3824 3825 // varargs 3826 if (isVarArg && MFI.hasVAStart()) 3827 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3828 CCInfo.getNextStackOffset(), 3829 TotalArgRegsSaveSize); 3830 3831 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3832 3833 return Chain; 3834 } 3835 3836 /// isFloatingPointZero - Return true if this is +0.0. 3837 static bool isFloatingPointZero(SDValue Op) { 3838 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3839 return CFP->getValueAPF().isPosZero(); 3840 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3841 // Maybe this has already been legalized into the constant pool? 3842 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3843 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3844 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3845 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3846 return CFP->getValueAPF().isPosZero(); 3847 } 3848 } else if (Op->getOpcode() == ISD::BITCAST && 3849 Op->getValueType(0) == MVT::f64) { 3850 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3851 // created by LowerConstantFP(). 3852 SDValue BitcastOp = Op->getOperand(0); 3853 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3854 isNullConstant(BitcastOp->getOperand(0))) 3855 return true; 3856 } 3857 return false; 3858 } 3859 3860 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3861 /// the given operands. 3862 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3863 SDValue &ARMcc, SelectionDAG &DAG, 3864 const SDLoc &dl) const { 3865 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3866 unsigned C = RHSC->getZExtValue(); 3867 if (!isLegalICmpImmediate(C)) { 3868 // Constant does not fit, try adjusting it by one? 3869 switch (CC) { 3870 default: break; 3871 case ISD::SETLT: 3872 case ISD::SETGE: 3873 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3874 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3875 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3876 } 3877 break; 3878 case ISD::SETULT: 3879 case ISD::SETUGE: 3880 if (C != 0 && isLegalICmpImmediate(C-1)) { 3881 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3882 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3883 } 3884 break; 3885 case ISD::SETLE: 3886 case ISD::SETGT: 3887 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3888 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3889 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3890 } 3891 break; 3892 case ISD::SETULE: 3893 case ISD::SETUGT: 3894 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3895 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3896 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3897 } 3898 break; 3899 } 3900 } 3901 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 3902 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 3903 // In ARM and Thumb-2, the compare instructions can shift their second 3904 // operand. 3905 CC = ISD::getSetCCSwappedOperands(CC); 3906 std::swap(LHS, RHS); 3907 } 3908 3909 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3910 ARMISD::NodeType CompareType; 3911 switch (CondCode) { 3912 default: 3913 CompareType = ARMISD::CMP; 3914 break; 3915 case ARMCC::EQ: 3916 case ARMCC::NE: 3917 // Uses only Z Flag 3918 CompareType = ARMISD::CMPZ; 3919 break; 3920 } 3921 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3922 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3923 } 3924 3925 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3926 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3927 SelectionDAG &DAG, const SDLoc &dl, 3928 bool InvalidOnQNaN) const { 3929 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3930 SDValue Cmp; 3931 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3932 if (!isFloatingPointZero(RHS)) 3933 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3934 else 3935 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3936 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3937 } 3938 3939 /// duplicateCmp - Glue values can have only one use, so this function 3940 /// duplicates a comparison node. 3941 SDValue 3942 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3943 unsigned Opc = Cmp.getOpcode(); 3944 SDLoc DL(Cmp); 3945 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3946 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3947 3948 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3949 Cmp = Cmp.getOperand(0); 3950 Opc = Cmp.getOpcode(); 3951 if (Opc == ARMISD::CMPFP) 3952 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3953 Cmp.getOperand(1), Cmp.getOperand(2)); 3954 else { 3955 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3956 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3957 Cmp.getOperand(1)); 3958 } 3959 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3960 } 3961 3962 // This function returns three things: the arithmetic computation itself 3963 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 3964 // comparison and the condition code define the case in which the arithmetic 3965 // computation *does not* overflow. 3966 std::pair<SDValue, SDValue> 3967 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3968 SDValue &ARMcc) const { 3969 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3970 3971 SDValue Value, OverflowCmp; 3972 SDValue LHS = Op.getOperand(0); 3973 SDValue RHS = Op.getOperand(1); 3974 SDLoc dl(Op); 3975 3976 // FIXME: We are currently always generating CMPs because we don't support 3977 // generating CMN through the backend. This is not as good as the natural 3978 // CMP case because it causes a register dependency and cannot be folded 3979 // later. 3980 3981 switch (Op.getOpcode()) { 3982 default: 3983 llvm_unreachable("Unknown overflow instruction!"); 3984 case ISD::SADDO: 3985 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3986 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3987 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3988 break; 3989 case ISD::UADDO: 3990 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3991 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 3992 // We do not use it in the USUBO case as Value may not be used. 3993 Value = DAG.getNode(ARMISD::ADDC, dl, 3994 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 3995 .getValue(0); 3996 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3997 break; 3998 case ISD::SSUBO: 3999 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 4000 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4001 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4002 break; 4003 case ISD::USUBO: 4004 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 4005 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 4006 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4007 break; 4008 case ISD::UMULO: 4009 // We generate a UMUL_LOHI and then check if the high word is 0. 4010 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4011 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4012 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4013 LHS, RHS); 4014 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4015 DAG.getConstant(0, dl, MVT::i32)); 4016 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4017 break; 4018 case ISD::SMULO: 4019 // We generate a SMUL_LOHI and then check if all the bits of the high word 4020 // are the same as the sign bit of the low word. 4021 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4022 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4023 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4024 LHS, RHS); 4025 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4026 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4027 Value.getValue(0), 4028 DAG.getConstant(31, dl, MVT::i32))); 4029 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4030 break; 4031 } // switch (...) 4032 4033 return std::make_pair(Value, OverflowCmp); 4034 } 4035 4036 SDValue 4037 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4038 // Let legalize expand this if it isn't a legal type yet. 4039 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4040 return SDValue(); 4041 4042 SDValue Value, OverflowCmp; 4043 SDValue ARMcc; 4044 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4045 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4046 SDLoc dl(Op); 4047 // We use 0 and 1 as false and true values. 4048 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4049 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4050 EVT VT = Op.getValueType(); 4051 4052 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4053 ARMcc, CCR, OverflowCmp); 4054 4055 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4056 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4057 } 4058 4059 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4060 SelectionDAG &DAG) { 4061 SDLoc DL(BoolCarry); 4062 EVT CarryVT = BoolCarry.getValueType(); 4063 4064 // This converts the boolean value carry into the carry flag by doing 4065 // ARMISD::SUBC Carry, 1 4066 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4067 DAG.getVTList(CarryVT, MVT::i32), 4068 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4069 return Carry.getValue(1); 4070 } 4071 4072 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4073 SelectionDAG &DAG) { 4074 SDLoc DL(Flags); 4075 4076 // Now convert the carry flag into a boolean carry. We do this 4077 // using ARMISD:ADDE 0, 0, Carry 4078 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4079 DAG.getConstant(0, DL, MVT::i32), 4080 DAG.getConstant(0, DL, MVT::i32), Flags); 4081 } 4082 4083 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4084 SelectionDAG &DAG) const { 4085 // Let legalize expand this if it isn't a legal type yet. 4086 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4087 return SDValue(); 4088 4089 SDValue LHS = Op.getOperand(0); 4090 SDValue RHS = Op.getOperand(1); 4091 SDLoc dl(Op); 4092 4093 EVT VT = Op.getValueType(); 4094 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4095 SDValue Value; 4096 SDValue Overflow; 4097 switch (Op.getOpcode()) { 4098 default: 4099 llvm_unreachable("Unknown overflow instruction!"); 4100 case ISD::UADDO: 4101 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4102 // Convert the carry flag into a boolean value. 4103 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4104 break; 4105 case ISD::USUBO: { 4106 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4107 // Convert the carry flag into a boolean value. 4108 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4109 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4110 // value. So compute 1 - C. 4111 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4112 DAG.getConstant(1, dl, MVT::i32), Overflow); 4113 break; 4114 } 4115 } 4116 4117 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4118 } 4119 4120 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4121 SDValue Cond = Op.getOperand(0); 4122 SDValue SelectTrue = Op.getOperand(1); 4123 SDValue SelectFalse = Op.getOperand(2); 4124 SDLoc dl(Op); 4125 unsigned Opc = Cond.getOpcode(); 4126 4127 if (Cond.getResNo() == 1 && 4128 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4129 Opc == ISD::USUBO)) { 4130 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4131 return SDValue(); 4132 4133 SDValue Value, OverflowCmp; 4134 SDValue ARMcc; 4135 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4136 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4137 EVT VT = Op.getValueType(); 4138 4139 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4140 OverflowCmp, DAG); 4141 } 4142 4143 // Convert: 4144 // 4145 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4146 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4147 // 4148 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4149 const ConstantSDNode *CMOVTrue = 4150 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4151 const ConstantSDNode *CMOVFalse = 4152 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4153 4154 if (CMOVTrue && CMOVFalse) { 4155 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4156 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4157 4158 SDValue True; 4159 SDValue False; 4160 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4161 True = SelectTrue; 4162 False = SelectFalse; 4163 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4164 True = SelectFalse; 4165 False = SelectTrue; 4166 } 4167 4168 if (True.getNode() && False.getNode()) { 4169 EVT VT = Op.getValueType(); 4170 SDValue ARMcc = Cond.getOperand(2); 4171 SDValue CCR = Cond.getOperand(3); 4172 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4173 assert(True.getValueType() == VT); 4174 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4175 } 4176 } 4177 } 4178 4179 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4180 // undefined bits before doing a full-word comparison with zero. 4181 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4182 DAG.getConstant(1, dl, Cond.getValueType())); 4183 4184 return DAG.getSelectCC(dl, Cond, 4185 DAG.getConstant(0, dl, Cond.getValueType()), 4186 SelectTrue, SelectFalse, ISD::SETNE); 4187 } 4188 4189 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4190 bool &swpCmpOps, bool &swpVselOps) { 4191 // Start by selecting the GE condition code for opcodes that return true for 4192 // 'equality' 4193 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4194 CC == ISD::SETULE) 4195 CondCode = ARMCC::GE; 4196 4197 // and GT for opcodes that return false for 'equality'. 4198 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4199 CC == ISD::SETULT) 4200 CondCode = ARMCC::GT; 4201 4202 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4203 // to swap the compare operands. 4204 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4205 CC == ISD::SETULT) 4206 swpCmpOps = true; 4207 4208 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4209 // If we have an unordered opcode, we need to swap the operands to the VSEL 4210 // instruction (effectively negating the condition). 4211 // 4212 // This also has the effect of swapping which one of 'less' or 'greater' 4213 // returns true, so we also swap the compare operands. It also switches 4214 // whether we return true for 'equality', so we compensate by picking the 4215 // opposite condition code to our original choice. 4216 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4217 CC == ISD::SETUGT) { 4218 swpCmpOps = !swpCmpOps; 4219 swpVselOps = !swpVselOps; 4220 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4221 } 4222 4223 // 'ordered' is 'anything but unordered', so use the VS condition code and 4224 // swap the VSEL operands. 4225 if (CC == ISD::SETO) { 4226 CondCode = ARMCC::VS; 4227 swpVselOps = true; 4228 } 4229 4230 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4231 // code and swap the VSEL operands. 4232 if (CC == ISD::SETUNE) { 4233 CondCode = ARMCC::EQ; 4234 swpVselOps = true; 4235 } 4236 } 4237 4238 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4239 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4240 SDValue Cmp, SelectionDAG &DAG) const { 4241 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4242 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4243 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4244 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4245 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4246 4247 SDValue TrueLow = TrueVal.getValue(0); 4248 SDValue TrueHigh = TrueVal.getValue(1); 4249 SDValue FalseLow = FalseVal.getValue(0); 4250 SDValue FalseHigh = FalseVal.getValue(1); 4251 4252 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4253 ARMcc, CCR, Cmp); 4254 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4255 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4256 4257 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4258 } else { 4259 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4260 Cmp); 4261 } 4262 } 4263 4264 static bool isGTorGE(ISD::CondCode CC) { 4265 return CC == ISD::SETGT || CC == ISD::SETGE; 4266 } 4267 4268 static bool isLTorLE(ISD::CondCode CC) { 4269 return CC == ISD::SETLT || CC == ISD::SETLE; 4270 } 4271 4272 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4273 // All of these conditions (and their <= and >= counterparts) will do: 4274 // x < k ? k : x 4275 // x > k ? x : k 4276 // k < x ? x : k 4277 // k > x ? k : x 4278 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4279 const SDValue TrueVal, const SDValue FalseVal, 4280 const ISD::CondCode CC, const SDValue K) { 4281 return (isGTorGE(CC) && 4282 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4283 (isLTorLE(CC) && 4284 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4285 } 4286 4287 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4288 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4289 const SDValue TrueVal, const SDValue FalseVal, 4290 const ISD::CondCode CC, const SDValue K) { 4291 return (isGTorGE(CC) && 4292 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4293 (isLTorLE(CC) && 4294 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4295 } 4296 4297 // Check if two chained conditionals could be converted into SSAT or USAT. 4298 // 4299 // SSAT can replace a set of two conditional selectors that bound a number to an 4300 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4301 // 4302 // x < -k ? -k : (x > k ? k : x) 4303 // x < -k ? -k : (x < k ? x : k) 4304 // x > -k ? (x > k ? k : x) : -k 4305 // x < k ? (x < -k ? -k : x) : k 4306 // etc. 4307 // 4308 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4309 // a power of 2. 4310 // 4311 // It returns true if the conversion can be done, false otherwise. 4312 // Additionally, the variable is returned in parameter V, the constant in K and 4313 // usat is set to true if the conditional represents an unsigned saturation 4314 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4315 uint64_t &K, bool &usat) { 4316 SDValue LHS1 = Op.getOperand(0); 4317 SDValue RHS1 = Op.getOperand(1); 4318 SDValue TrueVal1 = Op.getOperand(2); 4319 SDValue FalseVal1 = Op.getOperand(3); 4320 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4321 4322 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4323 if (Op2.getOpcode() != ISD::SELECT_CC) 4324 return false; 4325 4326 SDValue LHS2 = Op2.getOperand(0); 4327 SDValue RHS2 = Op2.getOperand(1); 4328 SDValue TrueVal2 = Op2.getOperand(2); 4329 SDValue FalseVal2 = Op2.getOperand(3); 4330 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4331 4332 // Find out which are the constants and which are the variables 4333 // in each conditional 4334 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4335 ? &RHS1 4336 : nullptr; 4337 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4338 ? &RHS2 4339 : nullptr; 4340 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4341 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4342 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4343 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4344 4345 // We must detect cases where the original operations worked with 16- or 4346 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4347 // must work with sign-extended values but the select operations return 4348 // the original non-extended value. 4349 SDValue V2TmpReg = V2Tmp; 4350 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4351 V2TmpReg = V2Tmp->getOperand(0); 4352 4353 // Check that the registers and the constants have the correct values 4354 // in both conditionals 4355 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4356 V2TmpReg != V2) 4357 return false; 4358 4359 // Figure out which conditional is saturating the lower/upper bound. 4360 const SDValue *LowerCheckOp = 4361 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4362 ? &Op 4363 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4364 ? &Op2 4365 : nullptr; 4366 const SDValue *UpperCheckOp = 4367 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4368 ? &Op 4369 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4370 ? &Op2 4371 : nullptr; 4372 4373 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4374 return false; 4375 4376 // Check that the constant in the lower-bound check is 4377 // the opposite of the constant in the upper-bound check 4378 // in 1's complement. 4379 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4380 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4381 int64_t PosVal = std::max(Val1, Val2); 4382 int64_t NegVal = std::min(Val1, Val2); 4383 4384 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4385 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4386 isPowerOf2_64(PosVal + 1)) { 4387 4388 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4389 if (Val1 == ~Val2) 4390 usat = false; 4391 else if (NegVal == 0) 4392 usat = true; 4393 else 4394 return false; 4395 4396 V = V2; 4397 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4398 4399 return true; 4400 } 4401 4402 return false; 4403 } 4404 4405 // Check if a condition of the type x < k ? k : x can be converted into a 4406 // bit operation instead of conditional moves. 4407 // Currently this is allowed given: 4408 // - The conditions and values match up 4409 // - k is 0 or -1 (all ones) 4410 // This function will not check the last condition, thats up to the caller 4411 // It returns true if the transformation can be made, and in such case 4412 // returns x in V, and k in SatK. 4413 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4414 SDValue &SatK) 4415 { 4416 SDValue LHS = Op.getOperand(0); 4417 SDValue RHS = Op.getOperand(1); 4418 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4419 SDValue TrueVal = Op.getOperand(2); 4420 SDValue FalseVal = Op.getOperand(3); 4421 4422 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4423 ? &RHS 4424 : nullptr; 4425 4426 // No constant operation in comparison, early out 4427 if (!K) 4428 return false; 4429 4430 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4431 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4432 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4433 4434 // If the constant on left and right side, or variable on left and right, 4435 // does not match, early out 4436 if (*K != KTmp || V != VTmp) 4437 return false; 4438 4439 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4440 SatK = *K; 4441 return true; 4442 } 4443 4444 return false; 4445 } 4446 4447 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4448 EVT VT = Op.getValueType(); 4449 SDLoc dl(Op); 4450 4451 // Try to convert two saturating conditional selects into a single SSAT 4452 SDValue SatValue; 4453 uint64_t SatConstant; 4454 bool SatUSat; 4455 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4456 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4457 if (SatUSat) 4458 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4459 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4460 else 4461 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4462 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4463 } 4464 4465 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4466 // into more efficient bit operations, which is possible when k is 0 or -1 4467 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4468 // single instructions. On Thumb the shift and the bit operation will be two 4469 // instructions. 4470 // Only allow this transformation on full-width (32-bit) operations 4471 SDValue LowerSatConstant; 4472 if (VT == MVT::i32 && 4473 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4474 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4475 DAG.getConstant(31, dl, VT)); 4476 if (isNullConstant(LowerSatConstant)) { 4477 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4478 DAG.getAllOnesConstant(dl, VT)); 4479 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4480 } else if (isAllOnesConstant(LowerSatConstant)) 4481 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4482 } 4483 4484 SDValue LHS = Op.getOperand(0); 4485 SDValue RHS = Op.getOperand(1); 4486 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4487 SDValue TrueVal = Op.getOperand(2); 4488 SDValue FalseVal = Op.getOperand(3); 4489 4490 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4491 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4492 dl); 4493 4494 // If softenSetCCOperands only returned one value, we should compare it to 4495 // zero. 4496 if (!RHS.getNode()) { 4497 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4498 CC = ISD::SETNE; 4499 } 4500 } 4501 4502 if (LHS.getValueType() == MVT::i32) { 4503 // Try to generate VSEL on ARMv8. 4504 // The VSEL instruction can't use all the usual ARM condition 4505 // codes: it only has two bits to select the condition code, so it's 4506 // constrained to use only GE, GT, VS and EQ. 4507 // 4508 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4509 // swap the operands of the previous compare instruction (effectively 4510 // inverting the compare condition, swapping 'less' and 'greater') and 4511 // sometimes need to swap the operands to the VSEL (which inverts the 4512 // condition in the sense of firing whenever the previous condition didn't) 4513 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4514 TrueVal.getValueType() == MVT::f64)) { 4515 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4516 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4517 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4518 CC = ISD::getSetCCInverse(CC, true); 4519 std::swap(TrueVal, FalseVal); 4520 } 4521 } 4522 4523 SDValue ARMcc; 4524 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4525 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4526 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4527 } 4528 4529 ARMCC::CondCodes CondCode, CondCode2; 4530 bool InvalidOnQNaN; 4531 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4532 4533 // Normalize the fp compare. If RHS is zero we keep it there so we match 4534 // CMPFPw0 instead of CMPFP. 4535 if (Subtarget->hasFPARMv8() && !isFloatingPointZero(RHS) && 4536 (TrueVal.getValueType() == MVT::f16 || 4537 TrueVal.getValueType() == MVT::f32 || 4538 TrueVal.getValueType() == MVT::f64)) { 4539 bool swpCmpOps = false; 4540 bool swpVselOps = false; 4541 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4542 4543 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4544 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4545 if (swpCmpOps) 4546 std::swap(LHS, RHS); 4547 if (swpVselOps) 4548 std::swap(TrueVal, FalseVal); 4549 } 4550 } 4551 4552 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4553 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4554 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4555 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4556 if (CondCode2 != ARMCC::AL) { 4557 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4558 // FIXME: Needs another CMP because flag can have but one use. 4559 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4560 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4561 } 4562 return Result; 4563 } 4564 4565 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4566 /// to morph to an integer compare sequence. 4567 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4568 const ARMSubtarget *Subtarget) { 4569 SDNode *N = Op.getNode(); 4570 if (!N->hasOneUse()) 4571 // Otherwise it requires moving the value from fp to integer registers. 4572 return false; 4573 if (!N->getNumValues()) 4574 return false; 4575 EVT VT = Op.getValueType(); 4576 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4577 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4578 // vmrs are very slow, e.g. cortex-a8. 4579 return false; 4580 4581 if (isFloatingPointZero(Op)) { 4582 SeenZero = true; 4583 return true; 4584 } 4585 return ISD::isNormalLoad(N); 4586 } 4587 4588 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4589 if (isFloatingPointZero(Op)) 4590 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4591 4592 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4593 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4594 Ld->getPointerInfo(), Ld->getAlignment(), 4595 Ld->getMemOperand()->getFlags()); 4596 4597 llvm_unreachable("Unknown VFP cmp argument!"); 4598 } 4599 4600 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4601 SDValue &RetVal1, SDValue &RetVal2) { 4602 SDLoc dl(Op); 4603 4604 if (isFloatingPointZero(Op)) { 4605 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4606 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4607 return; 4608 } 4609 4610 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4611 SDValue Ptr = Ld->getBasePtr(); 4612 RetVal1 = 4613 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4614 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4615 4616 EVT PtrType = Ptr.getValueType(); 4617 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4618 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4619 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4620 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4621 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4622 Ld->getMemOperand()->getFlags()); 4623 return; 4624 } 4625 4626 llvm_unreachable("Unknown VFP cmp argument!"); 4627 } 4628 4629 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4630 /// f32 and even f64 comparisons to integer ones. 4631 SDValue 4632 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4633 SDValue Chain = Op.getOperand(0); 4634 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4635 SDValue LHS = Op.getOperand(2); 4636 SDValue RHS = Op.getOperand(3); 4637 SDValue Dest = Op.getOperand(4); 4638 SDLoc dl(Op); 4639 4640 bool LHSSeenZero = false; 4641 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4642 bool RHSSeenZero = false; 4643 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4644 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4645 // If unsafe fp math optimization is enabled and there are no other uses of 4646 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4647 // to an integer comparison. 4648 if (CC == ISD::SETOEQ) 4649 CC = ISD::SETEQ; 4650 else if (CC == ISD::SETUNE) 4651 CC = ISD::SETNE; 4652 4653 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4654 SDValue ARMcc; 4655 if (LHS.getValueType() == MVT::f32) { 4656 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4657 bitcastf32Toi32(LHS, DAG), Mask); 4658 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4659 bitcastf32Toi32(RHS, DAG), Mask); 4660 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4661 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4662 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4663 Chain, Dest, ARMcc, CCR, Cmp); 4664 } 4665 4666 SDValue LHS1, LHS2; 4667 SDValue RHS1, RHS2; 4668 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4669 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4670 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4671 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4672 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4673 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4674 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4675 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4676 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4677 } 4678 4679 return SDValue(); 4680 } 4681 4682 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4683 SDValue Chain = Op.getOperand(0); 4684 SDValue Cond = Op.getOperand(1); 4685 SDValue Dest = Op.getOperand(2); 4686 SDLoc dl(Op); 4687 4688 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4689 // instruction. 4690 unsigned Opc = Cond.getOpcode(); 4691 if (Cond.getResNo() == 1 && 4692 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4693 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 4694 // Only lower legal XALUO ops. 4695 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4696 return SDValue(); 4697 4698 // The actual operation with overflow check. 4699 SDValue Value, OverflowCmp; 4700 SDValue ARMcc; 4701 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4702 4703 // Reverse the condition code. 4704 ARMCC::CondCodes CondCode = 4705 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4706 CondCode = ARMCC::getOppositeCondition(CondCode); 4707 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4708 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4709 4710 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4711 OverflowCmp); 4712 } 4713 4714 return SDValue(); 4715 } 4716 4717 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4718 SDValue Chain = Op.getOperand(0); 4719 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4720 SDValue LHS = Op.getOperand(2); 4721 SDValue RHS = Op.getOperand(3); 4722 SDValue Dest = Op.getOperand(4); 4723 SDLoc dl(Op); 4724 4725 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4726 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4727 dl); 4728 4729 // If softenSetCCOperands only returned one value, we should compare it to 4730 // zero. 4731 if (!RHS.getNode()) { 4732 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4733 CC = ISD::SETNE; 4734 } 4735 } 4736 4737 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4738 // instruction. 4739 unsigned Opc = LHS.getOpcode(); 4740 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 4741 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4742 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO) && 4743 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4744 // Only lower legal XALUO ops. 4745 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4746 return SDValue(); 4747 4748 // The actual operation with overflow check. 4749 SDValue Value, OverflowCmp; 4750 SDValue ARMcc; 4751 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 4752 4753 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 4754 // Reverse the condition code. 4755 ARMCC::CondCodes CondCode = 4756 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4757 CondCode = ARMCC::getOppositeCondition(CondCode); 4758 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4759 } 4760 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4761 4762 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4763 OverflowCmp); 4764 } 4765 4766 if (LHS.getValueType() == MVT::i32) { 4767 SDValue ARMcc; 4768 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4769 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4770 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4771 Chain, Dest, ARMcc, CCR, Cmp); 4772 } 4773 4774 if (getTargetMachine().Options.UnsafeFPMath && 4775 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4776 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4777 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4778 return Result; 4779 } 4780 4781 ARMCC::CondCodes CondCode, CondCode2; 4782 bool InvalidOnQNaN; 4783 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4784 4785 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4786 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4787 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4788 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4789 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4790 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4791 if (CondCode2 != ARMCC::AL) { 4792 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4793 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4794 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4795 } 4796 return Res; 4797 } 4798 4799 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4800 SDValue Chain = Op.getOperand(0); 4801 SDValue Table = Op.getOperand(1); 4802 SDValue Index = Op.getOperand(2); 4803 SDLoc dl(Op); 4804 4805 EVT PTy = getPointerTy(DAG.getDataLayout()); 4806 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4807 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4808 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4809 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4810 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 4811 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4812 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4813 // which does another jump to the destination. This also makes it easier 4814 // to translate it to TBB / TBH later (Thumb2 only). 4815 // FIXME: This might not work if the function is extremely large. 4816 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4817 Addr, Op.getOperand(2), JTI); 4818 } 4819 if (isPositionIndependent() || Subtarget->isROPI()) { 4820 Addr = 4821 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4822 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4823 Chain = Addr.getValue(1); 4824 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 4825 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4826 } else { 4827 Addr = 4828 DAG.getLoad(PTy, dl, Chain, Addr, 4829 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4830 Chain = Addr.getValue(1); 4831 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4832 } 4833 } 4834 4835 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4836 EVT VT = Op.getValueType(); 4837 SDLoc dl(Op); 4838 4839 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4840 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4841 return Op; 4842 return DAG.UnrollVectorOp(Op.getNode()); 4843 } 4844 4845 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4846 "Invalid type for custom lowering!"); 4847 if (VT != MVT::v4i16) 4848 return DAG.UnrollVectorOp(Op.getNode()); 4849 4850 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4851 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4852 } 4853 4854 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4855 EVT VT = Op.getValueType(); 4856 if (VT.isVector()) 4857 return LowerVectorFP_TO_INT(Op, DAG); 4858 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4859 RTLIB::Libcall LC; 4860 if (Op.getOpcode() == ISD::FP_TO_SINT) 4861 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4862 Op.getValueType()); 4863 else 4864 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4865 Op.getValueType()); 4866 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4867 /*isSigned*/ false, SDLoc(Op)).first; 4868 } 4869 4870 return Op; 4871 } 4872 4873 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4874 EVT VT = Op.getValueType(); 4875 SDLoc dl(Op); 4876 4877 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4878 if (VT.getVectorElementType() == MVT::f32) 4879 return Op; 4880 return DAG.UnrollVectorOp(Op.getNode()); 4881 } 4882 4883 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4884 "Invalid type for custom lowering!"); 4885 if (VT != MVT::v4f32) 4886 return DAG.UnrollVectorOp(Op.getNode()); 4887 4888 unsigned CastOpc; 4889 unsigned Opc; 4890 switch (Op.getOpcode()) { 4891 default: llvm_unreachable("Invalid opcode!"); 4892 case ISD::SINT_TO_FP: 4893 CastOpc = ISD::SIGN_EXTEND; 4894 Opc = ISD::SINT_TO_FP; 4895 break; 4896 case ISD::UINT_TO_FP: 4897 CastOpc = ISD::ZERO_EXTEND; 4898 Opc = ISD::UINT_TO_FP; 4899 break; 4900 } 4901 4902 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4903 return DAG.getNode(Opc, dl, VT, Op); 4904 } 4905 4906 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4907 EVT VT = Op.getValueType(); 4908 if (VT.isVector()) 4909 return LowerVectorINT_TO_FP(Op, DAG); 4910 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4911 RTLIB::Libcall LC; 4912 if (Op.getOpcode() == ISD::SINT_TO_FP) 4913 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4914 Op.getValueType()); 4915 else 4916 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4917 Op.getValueType()); 4918 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4919 /*isSigned*/ false, SDLoc(Op)).first; 4920 } 4921 4922 return Op; 4923 } 4924 4925 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4926 // Implement fcopysign with a fabs and a conditional fneg. 4927 SDValue Tmp0 = Op.getOperand(0); 4928 SDValue Tmp1 = Op.getOperand(1); 4929 SDLoc dl(Op); 4930 EVT VT = Op.getValueType(); 4931 EVT SrcVT = Tmp1.getValueType(); 4932 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4933 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4934 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4935 4936 if (UseNEON) { 4937 // Use VBSL to copy the sign bit. 4938 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4939 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4940 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4941 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4942 if (VT == MVT::f64) 4943 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4944 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4945 DAG.getConstant(32, dl, MVT::i32)); 4946 else /*if (VT == MVT::f32)*/ 4947 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4948 if (SrcVT == MVT::f32) { 4949 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4950 if (VT == MVT::f64) 4951 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4952 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4953 DAG.getConstant(32, dl, MVT::i32)); 4954 } else if (VT == MVT::f32) 4955 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4956 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4957 DAG.getConstant(32, dl, MVT::i32)); 4958 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4959 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4960 4961 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4962 dl, MVT::i32); 4963 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4964 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4965 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4966 4967 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4968 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4969 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4970 if (VT == MVT::f32) { 4971 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4972 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4973 DAG.getConstant(0, dl, MVT::i32)); 4974 } else { 4975 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4976 } 4977 4978 return Res; 4979 } 4980 4981 // Bitcast operand 1 to i32. 4982 if (SrcVT == MVT::f64) 4983 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4984 Tmp1).getValue(1); 4985 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4986 4987 // Or in the signbit with integer operations. 4988 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4989 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4990 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4991 if (VT == MVT::f32) { 4992 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4993 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4994 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4995 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4996 } 4997 4998 // f64: Or the high part with signbit and then combine two parts. 4999 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 5000 Tmp0); 5001 SDValue Lo = Tmp0.getValue(0); 5002 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 5003 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 5004 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 5005 } 5006 5007 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5008 MachineFunction &MF = DAG.getMachineFunction(); 5009 MachineFrameInfo &MFI = MF.getFrameInfo(); 5010 MFI.setReturnAddressIsTaken(true); 5011 5012 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5013 return SDValue(); 5014 5015 EVT VT = Op.getValueType(); 5016 SDLoc dl(Op); 5017 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5018 if (Depth) { 5019 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5020 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5021 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5022 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5023 MachinePointerInfo()); 5024 } 5025 5026 // Return LR, which contains the return address. Mark it an implicit live-in. 5027 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5028 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5029 } 5030 5031 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5032 const ARMBaseRegisterInfo &ARI = 5033 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5034 MachineFunction &MF = DAG.getMachineFunction(); 5035 MachineFrameInfo &MFI = MF.getFrameInfo(); 5036 MFI.setFrameAddressIsTaken(true); 5037 5038 EVT VT = Op.getValueType(); 5039 SDLoc dl(Op); // FIXME probably not meaningful 5040 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5041 unsigned FrameReg = ARI.getFrameRegister(MF); 5042 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5043 while (Depth--) 5044 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5045 MachinePointerInfo()); 5046 return FrameAddr; 5047 } 5048 5049 // FIXME? Maybe this could be a TableGen attribute on some registers and 5050 // this table could be generated automatically from RegInfo. 5051 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5052 SelectionDAG &DAG) const { 5053 unsigned Reg = StringSwitch<unsigned>(RegName) 5054 .Case("sp", ARM::SP) 5055 .Default(0); 5056 if (Reg) 5057 return Reg; 5058 report_fatal_error(Twine("Invalid register name \"" 5059 + StringRef(RegName) + "\".")); 5060 } 5061 5062 // Result is 64 bit value so split into two 32 bit values and return as a 5063 // pair of values. 5064 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5065 SelectionDAG &DAG) { 5066 SDLoc DL(N); 5067 5068 // This function is only supposed to be called for i64 type destination. 5069 assert(N->getValueType(0) == MVT::i64 5070 && "ExpandREAD_REGISTER called for non-i64 type result."); 5071 5072 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5073 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5074 N->getOperand(0), 5075 N->getOperand(1)); 5076 5077 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5078 Read.getValue(1))); 5079 Results.push_back(Read.getOperand(0)); 5080 } 5081 5082 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5083 /// When \p DstVT, the destination type of \p BC, is on the vector 5084 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5085 /// it might be possible to combine them, such that everything stays on the 5086 /// vector register bank. 5087 /// \p return The node that would replace \p BT, if the combine 5088 /// is possible. 5089 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5090 SelectionDAG &DAG) { 5091 SDValue Op = BC->getOperand(0); 5092 EVT DstVT = BC->getValueType(0); 5093 5094 // The only vector instruction that can produce a scalar (remember, 5095 // since the bitcast was about to be turned into VMOVDRR, the source 5096 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5097 // Moreover, we can do this combine only if there is one use. 5098 // Finally, if the destination type is not a vector, there is not 5099 // much point on forcing everything on the vector bank. 5100 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5101 !Op.hasOneUse()) 5102 return SDValue(); 5103 5104 // If the index is not constant, we will introduce an additional 5105 // multiply that will stick. 5106 // Give up in that case. 5107 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5108 if (!Index) 5109 return SDValue(); 5110 unsigned DstNumElt = DstVT.getVectorNumElements(); 5111 5112 // Compute the new index. 5113 const APInt &APIntIndex = Index->getAPIntValue(); 5114 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5115 NewIndex *= APIntIndex; 5116 // Check if the new constant index fits into i32. 5117 if (NewIndex.getBitWidth() > 32) 5118 return SDValue(); 5119 5120 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5121 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5122 SDLoc dl(Op); 5123 SDValue ExtractSrc = Op.getOperand(0); 5124 EVT VecVT = EVT::getVectorVT( 5125 *DAG.getContext(), DstVT.getScalarType(), 5126 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5127 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5128 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5129 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5130 } 5131 5132 /// ExpandBITCAST - If the target supports VFP, this function is called to 5133 /// expand a bit convert where either the source or destination type is i64 to 5134 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5135 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5136 /// vectors), since the legalizer won't know what to do with that. 5137 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5138 const ARMSubtarget *Subtarget) { 5139 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5140 SDLoc dl(N); 5141 SDValue Op = N->getOperand(0); 5142 5143 // This function is only supposed to be called for i64 types, either as the 5144 // source or destination of the bit convert. 5145 EVT SrcVT = Op.getValueType(); 5146 EVT DstVT = N->getValueType(0); 5147 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5148 5149 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5150 // FullFP16: half values are passed in S-registers, and we don't 5151 // need any of the bitcast and moves: 5152 // 5153 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5154 // t5: i32 = bitcast t2 5155 // t18: f16 = ARMISD::VMOVhr t5 5156 if (Op.getOpcode() != ISD::CopyFromReg || 5157 Op.getValueType() != MVT::f32) 5158 return SDValue(); 5159 5160 auto Move = N->use_begin(); 5161 if (Move->getOpcode() != ARMISD::VMOVhr) 5162 return SDValue(); 5163 5164 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5165 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5166 DAG.ReplaceAllUsesWith(*Move, &Copy); 5167 return Copy; 5168 } 5169 5170 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5171 if (!HasFullFP16) 5172 return SDValue(); 5173 // SoftFP: read half-precision arguments: 5174 // 5175 // t2: i32,ch = ... 5176 // t7: i16 = truncate t2 <~~~~ Op 5177 // t8: f16 = bitcast t7 <~~~~ N 5178 // 5179 if (Op.getOperand(0).getValueType() == MVT::i32) 5180 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5181 MVT::f16, Op.getOperand(0)); 5182 5183 return SDValue(); 5184 } 5185 5186 // Half-precision return values 5187 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5188 if (!HasFullFP16) 5189 return SDValue(); 5190 // 5191 // t11: f16 = fadd t8, t10 5192 // t12: i16 = bitcast t11 <~~~ SDNode N 5193 // t13: i32 = zero_extend t12 5194 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5195 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5196 // 5197 // transform this into: 5198 // 5199 // t20: i32 = ARMISD::VMOVrh t11 5200 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5201 // 5202 auto ZeroExtend = N->use_begin(); 5203 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5204 ZeroExtend->getValueType(0) != MVT::i32) 5205 return SDValue(); 5206 5207 auto Copy = ZeroExtend->use_begin(); 5208 if (Copy->getOpcode() == ISD::CopyToReg && 5209 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5210 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5211 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5212 return Cvt; 5213 } 5214 return SDValue(); 5215 } 5216 5217 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5218 return SDValue(); 5219 5220 // Turn i64->f64 into VMOVDRR. 5221 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5222 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5223 // if we can combine the bitcast with its source. 5224 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5225 return Val; 5226 5227 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5228 DAG.getConstant(0, dl, MVT::i32)); 5229 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5230 DAG.getConstant(1, dl, MVT::i32)); 5231 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5232 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5233 } 5234 5235 // Turn f64->i64 into VMOVRRD. 5236 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5237 SDValue Cvt; 5238 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5239 SrcVT.getVectorNumElements() > 1) 5240 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5241 DAG.getVTList(MVT::i32, MVT::i32), 5242 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5243 else 5244 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5245 DAG.getVTList(MVT::i32, MVT::i32), Op); 5246 // Merge the pieces into a single i64 value. 5247 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5248 } 5249 5250 return SDValue(); 5251 } 5252 5253 /// getZeroVector - Returns a vector of specified type with all zero elements. 5254 /// Zero vectors are used to represent vector negation and in those cases 5255 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5256 /// not support i64 elements, so sometimes the zero vectors will need to be 5257 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5258 /// zero vector. 5259 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5260 assert(VT.isVector() && "Expected a vector type"); 5261 // The canonical modified immediate encoding of a zero vector is....0! 5262 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5263 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5264 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5265 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5266 } 5267 5268 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5269 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5270 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5271 SelectionDAG &DAG) const { 5272 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5273 EVT VT = Op.getValueType(); 5274 unsigned VTBits = VT.getSizeInBits(); 5275 SDLoc dl(Op); 5276 SDValue ShOpLo = Op.getOperand(0); 5277 SDValue ShOpHi = Op.getOperand(1); 5278 SDValue ShAmt = Op.getOperand(2); 5279 SDValue ARMcc; 5280 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5281 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5282 5283 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5284 5285 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5286 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5287 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5288 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5289 DAG.getConstant(VTBits, dl, MVT::i32)); 5290 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5291 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5292 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5293 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5294 ISD::SETGE, ARMcc, DAG, dl); 5295 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5296 ARMcc, CCR, CmpLo); 5297 5298 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5299 SDValue HiBigShift = Opc == ISD::SRA 5300 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5301 DAG.getConstant(VTBits - 1, dl, VT)) 5302 : DAG.getConstant(0, dl, VT); 5303 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5304 ISD::SETGE, ARMcc, DAG, dl); 5305 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5306 ARMcc, CCR, CmpHi); 5307 5308 SDValue Ops[2] = { Lo, Hi }; 5309 return DAG.getMergeValues(Ops, dl); 5310 } 5311 5312 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5313 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5314 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5315 SelectionDAG &DAG) const { 5316 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5317 EVT VT = Op.getValueType(); 5318 unsigned VTBits = VT.getSizeInBits(); 5319 SDLoc dl(Op); 5320 SDValue ShOpLo = Op.getOperand(0); 5321 SDValue ShOpHi = Op.getOperand(1); 5322 SDValue ShAmt = Op.getOperand(2); 5323 SDValue ARMcc; 5324 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5325 5326 assert(Op.getOpcode() == ISD::SHL_PARTS); 5327 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5328 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5329 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5330 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5331 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5332 5333 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5334 DAG.getConstant(VTBits, dl, MVT::i32)); 5335 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5336 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5337 ISD::SETGE, ARMcc, DAG, dl); 5338 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5339 ARMcc, CCR, CmpHi); 5340 5341 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5342 ISD::SETGE, ARMcc, DAG, dl); 5343 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5344 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5345 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5346 5347 SDValue Ops[2] = { Lo, Hi }; 5348 return DAG.getMergeValues(Ops, dl); 5349 } 5350 5351 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5352 SelectionDAG &DAG) const { 5353 // The rounding mode is in bits 23:22 of the FPSCR. 5354 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5355 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5356 // so that the shift + and get folded into a bitfield extract. 5357 SDLoc dl(Op); 5358 SDValue Ops[] = { DAG.getEntryNode(), 5359 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5360 5361 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5362 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5363 DAG.getConstant(1U << 22, dl, MVT::i32)); 5364 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5365 DAG.getConstant(22, dl, MVT::i32)); 5366 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5367 DAG.getConstant(3, dl, MVT::i32)); 5368 } 5369 5370 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5371 const ARMSubtarget *ST) { 5372 SDLoc dl(N); 5373 EVT VT = N->getValueType(0); 5374 if (VT.isVector()) { 5375 assert(ST->hasNEON()); 5376 5377 // Compute the least significant set bit: LSB = X & -X 5378 SDValue X = N->getOperand(0); 5379 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5380 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5381 5382 EVT ElemTy = VT.getVectorElementType(); 5383 5384 if (ElemTy == MVT::i8) { 5385 // Compute with: cttz(x) = ctpop(lsb - 1) 5386 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5387 DAG.getTargetConstant(1, dl, ElemTy)); 5388 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5389 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5390 } 5391 5392 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5393 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5394 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5395 unsigned NumBits = ElemTy.getSizeInBits(); 5396 SDValue WidthMinus1 = 5397 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5398 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5399 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5400 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5401 } 5402 5403 // Compute with: cttz(x) = ctpop(lsb - 1) 5404 5405 // Since we can only compute the number of bits in a byte with vcnt.8, we 5406 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 5407 // and i64. 5408 5409 // Compute LSB - 1. 5410 SDValue Bits; 5411 if (ElemTy == MVT::i64) { 5412 // Load constant 0xffff'ffff'ffff'ffff to register. 5413 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5414 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5415 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5416 } else { 5417 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5418 DAG.getTargetConstant(1, dl, ElemTy)); 5419 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5420 } 5421 5422 // Count #bits with vcnt.8. 5423 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5424 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 5425 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 5426 5427 // Gather the #bits with vpaddl (pairwise add.) 5428 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5429 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 5430 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5431 Cnt8); 5432 if (ElemTy == MVT::i16) 5433 return Cnt16; 5434 5435 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 5436 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 5437 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5438 Cnt16); 5439 if (ElemTy == MVT::i32) 5440 return Cnt32; 5441 5442 assert(ElemTy == MVT::i64); 5443 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5444 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5445 Cnt32); 5446 return Cnt64; 5447 } 5448 5449 if (!ST->hasV6T2Ops()) 5450 return SDValue(); 5451 5452 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5453 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5454 } 5455 5456 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 5457 /// for each 16-bit element from operand, repeated. The basic idea is to 5458 /// leverage vcnt to get the 8-bit counts, gather and add the results. 5459 /// 5460 /// Trace for v4i16: 5461 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5462 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 5463 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 5464 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 5465 /// [b0 b1 b2 b3 b4 b5 b6 b7] 5466 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 5467 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 5468 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 5469 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 5470 EVT VT = N->getValueType(0); 5471 SDLoc DL(N); 5472 5473 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5474 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5475 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5476 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5477 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5478 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5479 } 5480 5481 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5482 /// bit-count for each 16-bit element from the operand. We need slightly 5483 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5484 /// 64/128-bit registers. 5485 /// 5486 /// Trace for v4i16: 5487 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5488 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5489 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5490 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5491 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5492 EVT VT = N->getValueType(0); 5493 SDLoc DL(N); 5494 5495 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5496 if (VT.is64BitVector()) { 5497 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5498 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5499 DAG.getIntPtrConstant(0, DL)); 5500 } else { 5501 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5502 BitCounts, DAG.getIntPtrConstant(0, DL)); 5503 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5504 } 5505 } 5506 5507 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5508 /// bit-count for each 32-bit element from the operand. The idea here is 5509 /// to split the vector into 16-bit elements, leverage the 16-bit count 5510 /// routine, and then combine the results. 5511 /// 5512 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5513 /// input = [v0 v1 ] (vi: 32-bit elements) 5514 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5515 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5516 /// vrev: N0 = [k1 k0 k3 k2 ] 5517 /// [k0 k1 k2 k3 ] 5518 /// N1 =+[k1 k0 k3 k2 ] 5519 /// [k0 k2 k1 k3 ] 5520 /// N2 =+[k1 k3 k0 k2 ] 5521 /// [k0 k2 k1 k3 ] 5522 /// Extended =+[k1 k3 k0 k2 ] 5523 /// [k0 k2 ] 5524 /// Extracted=+[k1 k3 ] 5525 /// 5526 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5527 EVT VT = N->getValueType(0); 5528 SDLoc DL(N); 5529 5530 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5531 5532 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5533 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5534 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5535 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5536 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5537 5538 if (VT.is64BitVector()) { 5539 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5540 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5541 DAG.getIntPtrConstant(0, DL)); 5542 } else { 5543 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5544 DAG.getIntPtrConstant(0, DL)); 5545 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5546 } 5547 } 5548 5549 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5550 const ARMSubtarget *ST) { 5551 EVT VT = N->getValueType(0); 5552 5553 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5554 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5555 VT == MVT::v4i16 || VT == MVT::v8i16) && 5556 "Unexpected type for custom ctpop lowering"); 5557 5558 if (VT.getVectorElementType() == MVT::i32) 5559 return lowerCTPOP32BitElements(N, DAG); 5560 else 5561 return lowerCTPOP16BitElements(N, DAG); 5562 } 5563 5564 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5565 const ARMSubtarget *ST) { 5566 EVT VT = N->getValueType(0); 5567 SDLoc dl(N); 5568 5569 if (!VT.isVector()) 5570 return SDValue(); 5571 5572 // Lower vector shifts on NEON to use VSHL. 5573 assert(ST->hasNEON() && "unexpected vector shift"); 5574 5575 // Left shifts translate directly to the vshiftu intrinsic. 5576 if (N->getOpcode() == ISD::SHL) 5577 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5578 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5579 MVT::i32), 5580 N->getOperand(0), N->getOperand(1)); 5581 5582 assert((N->getOpcode() == ISD::SRA || 5583 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5584 5585 // NEON uses the same intrinsics for both left and right shifts. For 5586 // right shifts, the shift amounts are negative, so negate the vector of 5587 // shift amounts. 5588 EVT ShiftVT = N->getOperand(1).getValueType(); 5589 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5590 getZeroVector(ShiftVT, DAG, dl), 5591 N->getOperand(1)); 5592 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5593 Intrinsic::arm_neon_vshifts : 5594 Intrinsic::arm_neon_vshiftu); 5595 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5596 DAG.getConstant(vshiftInt, dl, MVT::i32), 5597 N->getOperand(0), NegatedCount); 5598 } 5599 5600 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5601 const ARMSubtarget *ST) { 5602 EVT VT = N->getValueType(0); 5603 SDLoc dl(N); 5604 5605 // We can get here for a node like i32 = ISD::SHL i32, i64 5606 if (VT != MVT::i64) 5607 return SDValue(); 5608 5609 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5610 "Unknown shift to lower!"); 5611 5612 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5613 if (!isOneConstant(N->getOperand(1))) 5614 return SDValue(); 5615 5616 // If we are in thumb mode, we don't have RRX. 5617 if (ST->isThumb1Only()) return SDValue(); 5618 5619 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5620 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5621 DAG.getConstant(0, dl, MVT::i32)); 5622 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5623 DAG.getConstant(1, dl, MVT::i32)); 5624 5625 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5626 // captures the result into a carry flag. 5627 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5628 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5629 5630 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5631 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5632 5633 // Merge the pieces into a single i64 value. 5634 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5635 } 5636 5637 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5638 SDValue TmpOp0, TmpOp1; 5639 bool Invert = false; 5640 bool Swap = false; 5641 unsigned Opc = 0; 5642 5643 SDValue Op0 = Op.getOperand(0); 5644 SDValue Op1 = Op.getOperand(1); 5645 SDValue CC = Op.getOperand(2); 5646 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5647 EVT VT = Op.getValueType(); 5648 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5649 SDLoc dl(Op); 5650 5651 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5652 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5653 // Special-case integer 64-bit equality comparisons. They aren't legal, 5654 // but they can be lowered with a few vector instructions. 5655 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5656 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5657 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5658 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5659 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5660 DAG.getCondCode(ISD::SETEQ)); 5661 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5662 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5663 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5664 if (SetCCOpcode == ISD::SETNE) 5665 Merged = DAG.getNOT(dl, Merged, CmpVT); 5666 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5667 return Merged; 5668 } 5669 5670 if (CmpVT.getVectorElementType() == MVT::i64) 5671 // 64-bit comparisons are not legal in general. 5672 return SDValue(); 5673 5674 if (Op1.getValueType().isFloatingPoint()) { 5675 switch (SetCCOpcode) { 5676 default: llvm_unreachable("Illegal FP comparison"); 5677 case ISD::SETUNE: 5678 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5679 case ISD::SETOEQ: 5680 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5681 case ISD::SETOLT: 5682 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5683 case ISD::SETOGT: 5684 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5685 case ISD::SETOLE: 5686 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5687 case ISD::SETOGE: 5688 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5689 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5690 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5691 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5692 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5693 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5694 case ISD::SETONE: 5695 // Expand this to (OLT | OGT). 5696 TmpOp0 = Op0; 5697 TmpOp1 = Op1; 5698 Opc = ISD::OR; 5699 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5700 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5701 break; 5702 case ISD::SETUO: 5703 Invert = true; 5704 LLVM_FALLTHROUGH; 5705 case ISD::SETO: 5706 // Expand this to (OLT | OGE). 5707 TmpOp0 = Op0; 5708 TmpOp1 = Op1; 5709 Opc = ISD::OR; 5710 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5711 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5712 break; 5713 } 5714 } else { 5715 // Integer comparisons. 5716 switch (SetCCOpcode) { 5717 default: llvm_unreachable("Illegal integer comparison"); 5718 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5719 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5720 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5721 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5722 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5723 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5724 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5725 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5726 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5727 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5728 } 5729 5730 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5731 if (Opc == ARMISD::VCEQ) { 5732 SDValue AndOp; 5733 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5734 AndOp = Op0; 5735 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5736 AndOp = Op1; 5737 5738 // Ignore bitconvert. 5739 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5740 AndOp = AndOp.getOperand(0); 5741 5742 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5743 Opc = ARMISD::VTST; 5744 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5745 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5746 Invert = !Invert; 5747 } 5748 } 5749 } 5750 5751 if (Swap) 5752 std::swap(Op0, Op1); 5753 5754 // If one of the operands is a constant vector zero, attempt to fold the 5755 // comparison to a specialized compare-against-zero form. 5756 SDValue SingleOp; 5757 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5758 SingleOp = Op0; 5759 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5760 if (Opc == ARMISD::VCGE) 5761 Opc = ARMISD::VCLEZ; 5762 else if (Opc == ARMISD::VCGT) 5763 Opc = ARMISD::VCLTZ; 5764 SingleOp = Op1; 5765 } 5766 5767 SDValue Result; 5768 if (SingleOp.getNode()) { 5769 switch (Opc) { 5770 case ARMISD::VCEQ: 5771 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5772 case ARMISD::VCGE: 5773 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5774 case ARMISD::VCLEZ: 5775 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5776 case ARMISD::VCGT: 5777 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5778 case ARMISD::VCLTZ: 5779 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5780 default: 5781 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5782 } 5783 } else { 5784 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5785 } 5786 5787 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5788 5789 if (Invert) 5790 Result = DAG.getNOT(dl, Result, VT); 5791 5792 return Result; 5793 } 5794 5795 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 5796 SDValue LHS = Op.getOperand(0); 5797 SDValue RHS = Op.getOperand(1); 5798 SDValue Carry = Op.getOperand(2); 5799 SDValue Cond = Op.getOperand(3); 5800 SDLoc DL(Op); 5801 5802 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 5803 5804 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 5805 // have to invert the carry first. 5806 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 5807 DAG.getConstant(1, DL, MVT::i32), Carry); 5808 // This converts the boolean value carry into the carry flag. 5809 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 5810 5811 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5812 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5813 5814 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5815 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5816 SDValue ARMcc = DAG.getConstant( 5817 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5818 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5819 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5820 Cmp.getValue(1), SDValue()); 5821 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5822 CCR, Chain.getValue(1)); 5823 } 5824 5825 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5826 /// valid vector constant for a NEON instruction with a "modified immediate" 5827 /// operand (e.g., VMOV). If so, return the encoded value. 5828 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5829 unsigned SplatBitSize, SelectionDAG &DAG, 5830 const SDLoc &dl, EVT &VT, bool is128Bits, 5831 NEONModImmType type) { 5832 unsigned OpCmode, Imm; 5833 5834 // SplatBitSize is set to the smallest size that splats the vector, so a 5835 // zero vector will always have SplatBitSize == 8. However, NEON modified 5836 // immediate instructions others than VMOV do not support the 8-bit encoding 5837 // of a zero vector, and the default encoding of zero is supposed to be the 5838 // 32-bit version. 5839 if (SplatBits == 0) 5840 SplatBitSize = 32; 5841 5842 switch (SplatBitSize) { 5843 case 8: 5844 if (type != VMOVModImm) 5845 return SDValue(); 5846 // Any 1-byte value is OK. Op=0, Cmode=1110. 5847 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5848 OpCmode = 0xe; 5849 Imm = SplatBits; 5850 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5851 break; 5852 5853 case 16: 5854 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5855 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5856 if ((SplatBits & ~0xff) == 0) { 5857 // Value = 0x00nn: Op=x, Cmode=100x. 5858 OpCmode = 0x8; 5859 Imm = SplatBits; 5860 break; 5861 } 5862 if ((SplatBits & ~0xff00) == 0) { 5863 // Value = 0xnn00: Op=x, Cmode=101x. 5864 OpCmode = 0xa; 5865 Imm = SplatBits >> 8; 5866 break; 5867 } 5868 return SDValue(); 5869 5870 case 32: 5871 // NEON's 32-bit VMOV supports splat values where: 5872 // * only one byte is nonzero, or 5873 // * the least significant byte is 0xff and the second byte is nonzero, or 5874 // * the least significant 2 bytes are 0xff and the third is nonzero. 5875 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5876 if ((SplatBits & ~0xff) == 0) { 5877 // Value = 0x000000nn: Op=x, Cmode=000x. 5878 OpCmode = 0; 5879 Imm = SplatBits; 5880 break; 5881 } 5882 if ((SplatBits & ~0xff00) == 0) { 5883 // Value = 0x0000nn00: Op=x, Cmode=001x. 5884 OpCmode = 0x2; 5885 Imm = SplatBits >> 8; 5886 break; 5887 } 5888 if ((SplatBits & ~0xff0000) == 0) { 5889 // Value = 0x00nn0000: Op=x, Cmode=010x. 5890 OpCmode = 0x4; 5891 Imm = SplatBits >> 16; 5892 break; 5893 } 5894 if ((SplatBits & ~0xff000000) == 0) { 5895 // Value = 0xnn000000: Op=x, Cmode=011x. 5896 OpCmode = 0x6; 5897 Imm = SplatBits >> 24; 5898 break; 5899 } 5900 5901 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5902 if (type == OtherModImm) return SDValue(); 5903 5904 if ((SplatBits & ~0xffff) == 0 && 5905 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5906 // Value = 0x0000nnff: Op=x, Cmode=1100. 5907 OpCmode = 0xc; 5908 Imm = SplatBits >> 8; 5909 break; 5910 } 5911 5912 if ((SplatBits & ~0xffffff) == 0 && 5913 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5914 // Value = 0x00nnffff: Op=x, Cmode=1101. 5915 OpCmode = 0xd; 5916 Imm = SplatBits >> 16; 5917 break; 5918 } 5919 5920 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5921 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5922 // VMOV.I32. A (very) minor optimization would be to replicate the value 5923 // and fall through here to test for a valid 64-bit splat. But, then the 5924 // caller would also need to check and handle the change in size. 5925 return SDValue(); 5926 5927 case 64: { 5928 if (type != VMOVModImm) 5929 return SDValue(); 5930 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5931 uint64_t BitMask = 0xff; 5932 uint64_t Val = 0; 5933 unsigned ImmMask = 1; 5934 Imm = 0; 5935 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5936 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5937 Val |= BitMask; 5938 Imm |= ImmMask; 5939 } else if ((SplatBits & BitMask) != 0) { 5940 return SDValue(); 5941 } 5942 BitMask <<= 8; 5943 ImmMask <<= 1; 5944 } 5945 5946 if (DAG.getDataLayout().isBigEndian()) 5947 // swap higher and lower 32 bit word 5948 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5949 5950 // Op=1, Cmode=1110. 5951 OpCmode = 0x1e; 5952 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5953 break; 5954 } 5955 5956 default: 5957 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5958 } 5959 5960 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5961 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5962 } 5963 5964 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5965 const ARMSubtarget *ST) const { 5966 EVT VT = Op.getValueType(); 5967 bool IsDouble = (VT == MVT::f64); 5968 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5969 const APFloat &FPVal = CFP->getValueAPF(); 5970 5971 // Prevent floating-point constants from using literal loads 5972 // when execute-only is enabled. 5973 if (ST->genExecuteOnly()) { 5974 // If we can represent the constant as an immediate, don't lower it 5975 if (isFPImmLegal(FPVal, VT)) 5976 return Op; 5977 // Otherwise, construct as integer, and move to float register 5978 APInt INTVal = FPVal.bitcastToAPInt(); 5979 SDLoc DL(CFP); 5980 switch (VT.getSimpleVT().SimpleTy) { 5981 default: 5982 llvm_unreachable("Unknown floating point type!"); 5983 break; 5984 case MVT::f64: { 5985 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5986 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5987 if (!ST->isLittle()) 5988 std::swap(Lo, Hi); 5989 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5990 } 5991 case MVT::f32: 5992 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 5993 DAG.getConstant(INTVal, DL, MVT::i32)); 5994 } 5995 } 5996 5997 if (!ST->hasVFP3()) 5998 return SDValue(); 5999 6000 // Use the default (constant pool) lowering for double constants when we have 6001 // an SP-only FPU 6002 if (IsDouble && Subtarget->isFPOnlySP()) 6003 return SDValue(); 6004 6005 // Try splatting with a VMOV.f32... 6006 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6007 6008 if (ImmVal != -1) { 6009 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6010 // We have code in place to select a valid ConstantFP already, no need to 6011 // do any mangling. 6012 return Op; 6013 } 6014 6015 // It's a float and we are trying to use NEON operations where 6016 // possible. Lower it to a splat followed by an extract. 6017 SDLoc DL(Op); 6018 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6019 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6020 NewVal); 6021 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6022 DAG.getConstant(0, DL, MVT::i32)); 6023 } 6024 6025 // The rest of our options are NEON only, make sure that's allowed before 6026 // proceeding.. 6027 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6028 return SDValue(); 6029 6030 EVT VMovVT; 6031 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6032 6033 // It wouldn't really be worth bothering for doubles except for one very 6034 // important value, which does happen to match: 0.0. So make sure we don't do 6035 // anything stupid. 6036 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6037 return SDValue(); 6038 6039 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6040 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6041 VMovVT, false, VMOVModImm); 6042 if (NewVal != SDValue()) { 6043 SDLoc DL(Op); 6044 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6045 NewVal); 6046 if (IsDouble) 6047 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6048 6049 // It's a float: cast and extract a vector element. 6050 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6051 VecConstant); 6052 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6053 DAG.getConstant(0, DL, MVT::i32)); 6054 } 6055 6056 // Finally, try a VMVN.i32 6057 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6058 false, VMVNModImm); 6059 if (NewVal != SDValue()) { 6060 SDLoc DL(Op); 6061 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6062 6063 if (IsDouble) 6064 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6065 6066 // It's a float: cast and extract a vector element. 6067 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6068 VecConstant); 6069 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6070 DAG.getConstant(0, DL, MVT::i32)); 6071 } 6072 6073 return SDValue(); 6074 } 6075 6076 // check if an VEXT instruction can handle the shuffle mask when the 6077 // vector sources of the shuffle are the same. 6078 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6079 unsigned NumElts = VT.getVectorNumElements(); 6080 6081 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6082 if (M[0] < 0) 6083 return false; 6084 6085 Imm = M[0]; 6086 6087 // If this is a VEXT shuffle, the immediate value is the index of the first 6088 // element. The other shuffle indices must be the successive elements after 6089 // the first one. 6090 unsigned ExpectedElt = Imm; 6091 for (unsigned i = 1; i < NumElts; ++i) { 6092 // Increment the expected index. If it wraps around, just follow it 6093 // back to index zero and keep going. 6094 ++ExpectedElt; 6095 if (ExpectedElt == NumElts) 6096 ExpectedElt = 0; 6097 6098 if (M[i] < 0) continue; // ignore UNDEF indices 6099 if (ExpectedElt != static_cast<unsigned>(M[i])) 6100 return false; 6101 } 6102 6103 return true; 6104 } 6105 6106 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6107 bool &ReverseVEXT, unsigned &Imm) { 6108 unsigned NumElts = VT.getVectorNumElements(); 6109 ReverseVEXT = false; 6110 6111 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6112 if (M[0] < 0) 6113 return false; 6114 6115 Imm = M[0]; 6116 6117 // If this is a VEXT shuffle, the immediate value is the index of the first 6118 // element. The other shuffle indices must be the successive elements after 6119 // the first one. 6120 unsigned ExpectedElt = Imm; 6121 for (unsigned i = 1; i < NumElts; ++i) { 6122 // Increment the expected index. If it wraps around, it may still be 6123 // a VEXT but the source vectors must be swapped. 6124 ExpectedElt += 1; 6125 if (ExpectedElt == NumElts * 2) { 6126 ExpectedElt = 0; 6127 ReverseVEXT = true; 6128 } 6129 6130 if (M[i] < 0) continue; // ignore UNDEF indices 6131 if (ExpectedElt != static_cast<unsigned>(M[i])) 6132 return false; 6133 } 6134 6135 // Adjust the index value if the source operands will be swapped. 6136 if (ReverseVEXT) 6137 Imm -= NumElts; 6138 6139 return true; 6140 } 6141 6142 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6143 /// instruction with the specified blocksize. (The order of the elements 6144 /// within each block of the vector is reversed.) 6145 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6146 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6147 "Only possible block sizes for VREV are: 16, 32, 64"); 6148 6149 unsigned EltSz = VT.getScalarSizeInBits(); 6150 if (EltSz == 64) 6151 return false; 6152 6153 unsigned NumElts = VT.getVectorNumElements(); 6154 unsigned BlockElts = M[0] + 1; 6155 // If the first shuffle index is UNDEF, be optimistic. 6156 if (M[0] < 0) 6157 BlockElts = BlockSize / EltSz; 6158 6159 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6160 return false; 6161 6162 for (unsigned i = 0; i < NumElts; ++i) { 6163 if (M[i] < 0) continue; // ignore UNDEF indices 6164 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6165 return false; 6166 } 6167 6168 return true; 6169 } 6170 6171 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6172 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6173 // range, then 0 is placed into the resulting vector. So pretty much any mask 6174 // of 8 elements can work here. 6175 return VT == MVT::v8i8 && M.size() == 8; 6176 } 6177 6178 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6179 unsigned Index) { 6180 if (Mask.size() == Elements * 2) 6181 return Index / Elements; 6182 return Mask[Index] == 0 ? 0 : 1; 6183 } 6184 6185 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6186 // checking that pairs of elements in the shuffle mask represent the same index 6187 // in each vector, incrementing the expected index by 2 at each step. 6188 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6189 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6190 // v2={e,f,g,h} 6191 // WhichResult gives the offset for each element in the mask based on which 6192 // of the two results it belongs to. 6193 // 6194 // The transpose can be represented either as: 6195 // result1 = shufflevector v1, v2, result1_shuffle_mask 6196 // result2 = shufflevector v1, v2, result2_shuffle_mask 6197 // where v1/v2 and the shuffle masks have the same number of elements 6198 // (here WhichResult (see below) indicates which result is being checked) 6199 // 6200 // or as: 6201 // results = shufflevector v1, v2, shuffle_mask 6202 // where both results are returned in one vector and the shuffle mask has twice 6203 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6204 // want to check the low half and high half of the shuffle mask as if it were 6205 // the other case 6206 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6207 unsigned EltSz = VT.getScalarSizeInBits(); 6208 if (EltSz == 64) 6209 return false; 6210 6211 unsigned NumElts = VT.getVectorNumElements(); 6212 if (M.size() != NumElts && M.size() != NumElts*2) 6213 return false; 6214 6215 // If the mask is twice as long as the input vector then we need to check the 6216 // upper and lower parts of the mask with a matching value for WhichResult 6217 // FIXME: A mask with only even values will be rejected in case the first 6218 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6219 // M[0] is used to determine WhichResult 6220 for (unsigned i = 0; i < M.size(); i += NumElts) { 6221 WhichResult = SelectPairHalf(NumElts, M, i); 6222 for (unsigned j = 0; j < NumElts; j += 2) { 6223 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6224 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6225 return false; 6226 } 6227 } 6228 6229 if (M.size() == NumElts*2) 6230 WhichResult = 0; 6231 6232 return true; 6233 } 6234 6235 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6236 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6237 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6238 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6239 unsigned EltSz = VT.getScalarSizeInBits(); 6240 if (EltSz == 64) 6241 return false; 6242 6243 unsigned NumElts = VT.getVectorNumElements(); 6244 if (M.size() != NumElts && M.size() != NumElts*2) 6245 return false; 6246 6247 for (unsigned i = 0; i < M.size(); i += NumElts) { 6248 WhichResult = SelectPairHalf(NumElts, M, i); 6249 for (unsigned j = 0; j < NumElts; j += 2) { 6250 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6251 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6252 return false; 6253 } 6254 } 6255 6256 if (M.size() == NumElts*2) 6257 WhichResult = 0; 6258 6259 return true; 6260 } 6261 6262 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6263 // that the mask elements are either all even and in steps of size 2 or all odd 6264 // and in steps of size 2. 6265 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6266 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6267 // v2={e,f,g,h} 6268 // Requires similar checks to that of isVTRNMask with 6269 // respect the how results are returned. 6270 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6271 unsigned EltSz = VT.getScalarSizeInBits(); 6272 if (EltSz == 64) 6273 return false; 6274 6275 unsigned NumElts = VT.getVectorNumElements(); 6276 if (M.size() != NumElts && M.size() != NumElts*2) 6277 return false; 6278 6279 for (unsigned i = 0; i < M.size(); i += NumElts) { 6280 WhichResult = SelectPairHalf(NumElts, M, i); 6281 for (unsigned j = 0; j < NumElts; ++j) { 6282 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6283 return false; 6284 } 6285 } 6286 6287 if (M.size() == NumElts*2) 6288 WhichResult = 0; 6289 6290 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6291 if (VT.is64BitVector() && EltSz == 32) 6292 return false; 6293 6294 return true; 6295 } 6296 6297 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6298 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6299 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6300 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6301 unsigned EltSz = VT.getScalarSizeInBits(); 6302 if (EltSz == 64) 6303 return false; 6304 6305 unsigned NumElts = VT.getVectorNumElements(); 6306 if (M.size() != NumElts && M.size() != NumElts*2) 6307 return false; 6308 6309 unsigned Half = NumElts / 2; 6310 for (unsigned i = 0; i < M.size(); i += NumElts) { 6311 WhichResult = SelectPairHalf(NumElts, M, i); 6312 for (unsigned j = 0; j < NumElts; j += Half) { 6313 unsigned Idx = WhichResult; 6314 for (unsigned k = 0; k < Half; ++k) { 6315 int MIdx = M[i + j + k]; 6316 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6317 return false; 6318 Idx += 2; 6319 } 6320 } 6321 } 6322 6323 if (M.size() == NumElts*2) 6324 WhichResult = 0; 6325 6326 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6327 if (VT.is64BitVector() && EltSz == 32) 6328 return false; 6329 6330 return true; 6331 } 6332 6333 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6334 // that pairs of elements of the shufflemask represent the same index in each 6335 // vector incrementing sequentially through the vectors. 6336 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6337 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6338 // v2={e,f,g,h} 6339 // Requires similar checks to that of isVTRNMask with respect the how results 6340 // are returned. 6341 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6342 unsigned EltSz = VT.getScalarSizeInBits(); 6343 if (EltSz == 64) 6344 return false; 6345 6346 unsigned NumElts = VT.getVectorNumElements(); 6347 if (M.size() != NumElts && M.size() != NumElts*2) 6348 return false; 6349 6350 for (unsigned i = 0; i < M.size(); i += NumElts) { 6351 WhichResult = SelectPairHalf(NumElts, M, i); 6352 unsigned Idx = WhichResult * NumElts / 2; 6353 for (unsigned j = 0; j < NumElts; j += 2) { 6354 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6355 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6356 return false; 6357 Idx += 1; 6358 } 6359 } 6360 6361 if (M.size() == NumElts*2) 6362 WhichResult = 0; 6363 6364 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6365 if (VT.is64BitVector() && EltSz == 32) 6366 return false; 6367 6368 return true; 6369 } 6370 6371 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6372 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6373 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6374 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6375 unsigned EltSz = VT.getScalarSizeInBits(); 6376 if (EltSz == 64) 6377 return false; 6378 6379 unsigned NumElts = VT.getVectorNumElements(); 6380 if (M.size() != NumElts && M.size() != NumElts*2) 6381 return false; 6382 6383 for (unsigned i = 0; i < M.size(); i += NumElts) { 6384 WhichResult = SelectPairHalf(NumElts, M, i); 6385 unsigned Idx = WhichResult * NumElts / 2; 6386 for (unsigned j = 0; j < NumElts; j += 2) { 6387 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6388 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6389 return false; 6390 Idx += 1; 6391 } 6392 } 6393 6394 if (M.size() == NumElts*2) 6395 WhichResult = 0; 6396 6397 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6398 if (VT.is64BitVector() && EltSz == 32) 6399 return false; 6400 6401 return true; 6402 } 6403 6404 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6405 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6406 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6407 unsigned &WhichResult, 6408 bool &isV_UNDEF) { 6409 isV_UNDEF = false; 6410 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6411 return ARMISD::VTRN; 6412 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6413 return ARMISD::VUZP; 6414 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6415 return ARMISD::VZIP; 6416 6417 isV_UNDEF = true; 6418 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6419 return ARMISD::VTRN; 6420 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6421 return ARMISD::VUZP; 6422 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6423 return ARMISD::VZIP; 6424 6425 return 0; 6426 } 6427 6428 /// \return true if this is a reverse operation on an vector. 6429 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6430 unsigned NumElts = VT.getVectorNumElements(); 6431 // Make sure the mask has the right size. 6432 if (NumElts != M.size()) 6433 return false; 6434 6435 // Look for <15, ..., 3, -1, 1, 0>. 6436 for (unsigned i = 0; i != NumElts; ++i) 6437 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6438 return false; 6439 6440 return true; 6441 } 6442 6443 // If N is an integer constant that can be moved into a register in one 6444 // instruction, return an SDValue of such a constant (will become a MOV 6445 // instruction). Otherwise return null. 6446 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6447 const ARMSubtarget *ST, const SDLoc &dl) { 6448 uint64_t Val; 6449 if (!isa<ConstantSDNode>(N)) 6450 return SDValue(); 6451 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6452 6453 if (ST->isThumb1Only()) { 6454 if (Val <= 255 || ~Val <= 255) 6455 return DAG.getConstant(Val, dl, MVT::i32); 6456 } else { 6457 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6458 return DAG.getConstant(Val, dl, MVT::i32); 6459 } 6460 return SDValue(); 6461 } 6462 6463 // If this is a case we can't handle, return null and let the default 6464 // expansion code take care of it. 6465 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6466 const ARMSubtarget *ST) const { 6467 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6468 SDLoc dl(Op); 6469 EVT VT = Op.getValueType(); 6470 6471 APInt SplatBits, SplatUndef; 6472 unsigned SplatBitSize; 6473 bool HasAnyUndefs; 6474 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6475 if (SplatUndef.isAllOnesValue()) 6476 return DAG.getUNDEF(VT); 6477 6478 if (SplatBitSize <= 64) { 6479 // Check if an immediate VMOV works. 6480 EVT VmovVT; 6481 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6482 SplatUndef.getZExtValue(), SplatBitSize, 6483 DAG, dl, VmovVT, VT.is128BitVector(), 6484 VMOVModImm); 6485 if (Val.getNode()) { 6486 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6487 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6488 } 6489 6490 // Try an immediate VMVN. 6491 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6492 Val = isNEONModifiedImm(NegatedImm, 6493 SplatUndef.getZExtValue(), SplatBitSize, 6494 DAG, dl, VmovVT, VT.is128BitVector(), 6495 VMVNModImm); 6496 if (Val.getNode()) { 6497 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6498 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6499 } 6500 6501 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6502 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6503 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6504 if (ImmVal != -1) { 6505 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6506 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6507 } 6508 } 6509 } 6510 } 6511 6512 // Scan through the operands to see if only one value is used. 6513 // 6514 // As an optimisation, even if more than one value is used it may be more 6515 // profitable to splat with one value then change some lanes. 6516 // 6517 // Heuristically we decide to do this if the vector has a "dominant" value, 6518 // defined as splatted to more than half of the lanes. 6519 unsigned NumElts = VT.getVectorNumElements(); 6520 bool isOnlyLowElement = true; 6521 bool usesOnlyOneValue = true; 6522 bool hasDominantValue = false; 6523 bool isConstant = true; 6524 6525 // Map of the number of times a particular SDValue appears in the 6526 // element list. 6527 DenseMap<SDValue, unsigned> ValueCounts; 6528 SDValue Value; 6529 for (unsigned i = 0; i < NumElts; ++i) { 6530 SDValue V = Op.getOperand(i); 6531 if (V.isUndef()) 6532 continue; 6533 if (i > 0) 6534 isOnlyLowElement = false; 6535 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6536 isConstant = false; 6537 6538 ValueCounts.insert(std::make_pair(V, 0)); 6539 unsigned &Count = ValueCounts[V]; 6540 6541 // Is this value dominant? (takes up more than half of the lanes) 6542 if (++Count > (NumElts / 2)) { 6543 hasDominantValue = true; 6544 Value = V; 6545 } 6546 } 6547 if (ValueCounts.size() != 1) 6548 usesOnlyOneValue = false; 6549 if (!Value.getNode() && !ValueCounts.empty()) 6550 Value = ValueCounts.begin()->first; 6551 6552 if (ValueCounts.empty()) 6553 return DAG.getUNDEF(VT); 6554 6555 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6556 // Keep going if we are hitting this case. 6557 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6558 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6559 6560 unsigned EltSize = VT.getScalarSizeInBits(); 6561 6562 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6563 // i32 and try again. 6564 if (hasDominantValue && EltSize <= 32) { 6565 if (!isConstant) { 6566 SDValue N; 6567 6568 // If we are VDUPing a value that comes directly from a vector, that will 6569 // cause an unnecessary move to and from a GPR, where instead we could 6570 // just use VDUPLANE. We can only do this if the lane being extracted 6571 // is at a constant index, as the VDUP from lane instructions only have 6572 // constant-index forms. 6573 ConstantSDNode *constIndex; 6574 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6575 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6576 // We need to create a new undef vector to use for the VDUPLANE if the 6577 // size of the vector from which we get the value is different than the 6578 // size of the vector that we need to create. We will insert the element 6579 // such that the register coalescer will remove unnecessary copies. 6580 if (VT != Value->getOperand(0).getValueType()) { 6581 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6582 VT.getVectorNumElements(); 6583 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6584 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6585 Value, DAG.getConstant(index, dl, MVT::i32)), 6586 DAG.getConstant(index, dl, MVT::i32)); 6587 } else 6588 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6589 Value->getOperand(0), Value->getOperand(1)); 6590 } else 6591 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6592 6593 if (!usesOnlyOneValue) { 6594 // The dominant value was splatted as 'N', but we now have to insert 6595 // all differing elements. 6596 for (unsigned I = 0; I < NumElts; ++I) { 6597 if (Op.getOperand(I) == Value) 6598 continue; 6599 SmallVector<SDValue, 3> Ops; 6600 Ops.push_back(N); 6601 Ops.push_back(Op.getOperand(I)); 6602 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6603 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6604 } 6605 } 6606 return N; 6607 } 6608 if (VT.getVectorElementType().isFloatingPoint()) { 6609 SmallVector<SDValue, 8> Ops; 6610 for (unsigned i = 0; i < NumElts; ++i) 6611 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6612 Op.getOperand(i))); 6613 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6614 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6615 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6616 if (Val.getNode()) 6617 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6618 } 6619 if (usesOnlyOneValue) { 6620 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6621 if (isConstant && Val.getNode()) 6622 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6623 } 6624 } 6625 6626 // If all elements are constants and the case above didn't get hit, fall back 6627 // to the default expansion, which will generate a load from the constant 6628 // pool. 6629 if (isConstant) 6630 return SDValue(); 6631 6632 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6633 if (NumElts >= 4) { 6634 SDValue shuffle = ReconstructShuffle(Op, DAG); 6635 if (shuffle != SDValue()) 6636 return shuffle; 6637 } 6638 6639 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6640 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6641 // into two 64-bit vectors; we might discover a better way to lower it. 6642 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6643 EVT ExtVT = VT.getVectorElementType(); 6644 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6645 SDValue Lower = 6646 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6647 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6648 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6649 SDValue Upper = DAG.getBuildVector( 6650 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6651 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6652 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6653 if (Lower && Upper) 6654 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6655 } 6656 6657 // Vectors with 32- or 64-bit elements can be built by directly assigning 6658 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6659 // will be legalized. 6660 if (EltSize >= 32) { 6661 // Do the expansion with floating-point types, since that is what the VFP 6662 // registers are defined to use, and since i64 is not legal. 6663 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6664 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6665 SmallVector<SDValue, 8> Ops; 6666 for (unsigned i = 0; i < NumElts; ++i) 6667 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6668 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6669 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6670 } 6671 6672 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6673 // know the default expansion would otherwise fall back on something even 6674 // worse. For a vector with one or two non-undef values, that's 6675 // scalar_to_vector for the elements followed by a shuffle (provided the 6676 // shuffle is valid for the target) and materialization element by element 6677 // on the stack followed by a load for everything else. 6678 if (!isConstant && !usesOnlyOneValue) { 6679 SDValue Vec = DAG.getUNDEF(VT); 6680 for (unsigned i = 0 ; i < NumElts; ++i) { 6681 SDValue V = Op.getOperand(i); 6682 if (V.isUndef()) 6683 continue; 6684 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6685 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6686 } 6687 return Vec; 6688 } 6689 6690 return SDValue(); 6691 } 6692 6693 // Gather data to see if the operation can be modelled as a 6694 // shuffle in combination with VEXTs. 6695 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6696 SelectionDAG &DAG) const { 6697 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6698 SDLoc dl(Op); 6699 EVT VT = Op.getValueType(); 6700 unsigned NumElts = VT.getVectorNumElements(); 6701 6702 struct ShuffleSourceInfo { 6703 SDValue Vec; 6704 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6705 unsigned MaxElt = 0; 6706 6707 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6708 // be compatible with the shuffle we intend to construct. As a result 6709 // ShuffleVec will be some sliding window into the original Vec. 6710 SDValue ShuffleVec; 6711 6712 // Code should guarantee that element i in Vec starts at element "WindowBase 6713 // + i * WindowScale in ShuffleVec". 6714 int WindowBase = 0; 6715 int WindowScale = 1; 6716 6717 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6718 6719 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6720 }; 6721 6722 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6723 // node. 6724 SmallVector<ShuffleSourceInfo, 2> Sources; 6725 for (unsigned i = 0; i < NumElts; ++i) { 6726 SDValue V = Op.getOperand(i); 6727 if (V.isUndef()) 6728 continue; 6729 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6730 // A shuffle can only come from building a vector from various 6731 // elements of other vectors. 6732 return SDValue(); 6733 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6734 // Furthermore, shuffles require a constant mask, whereas extractelts 6735 // accept variable indices. 6736 return SDValue(); 6737 } 6738 6739 // Add this element source to the list if it's not already there. 6740 SDValue SourceVec = V.getOperand(0); 6741 auto Source = llvm::find(Sources, SourceVec); 6742 if (Source == Sources.end()) 6743 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6744 6745 // Update the minimum and maximum lane number seen. 6746 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6747 Source->MinElt = std::min(Source->MinElt, EltNo); 6748 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6749 } 6750 6751 // Currently only do something sane when at most two source vectors 6752 // are involved. 6753 if (Sources.size() > 2) 6754 return SDValue(); 6755 6756 // Find out the smallest element size among result and two sources, and use 6757 // it as element size to build the shuffle_vector. 6758 EVT SmallestEltTy = VT.getVectorElementType(); 6759 for (auto &Source : Sources) { 6760 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6761 if (SrcEltTy.bitsLT(SmallestEltTy)) 6762 SmallestEltTy = SrcEltTy; 6763 } 6764 unsigned ResMultiplier = 6765 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6766 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6767 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6768 6769 // If the source vector is too wide or too narrow, we may nevertheless be able 6770 // to construct a compatible shuffle either by concatenating it with UNDEF or 6771 // extracting a suitable range of elements. 6772 for (auto &Src : Sources) { 6773 EVT SrcVT = Src.ShuffleVec.getValueType(); 6774 6775 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6776 continue; 6777 6778 // This stage of the search produces a source with the same element type as 6779 // the original, but with a total width matching the BUILD_VECTOR output. 6780 EVT EltVT = SrcVT.getVectorElementType(); 6781 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6782 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6783 6784 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6785 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6786 return SDValue(); 6787 // We can pad out the smaller vector for free, so if it's part of a 6788 // shuffle... 6789 Src.ShuffleVec = 6790 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6791 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6792 continue; 6793 } 6794 6795 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6796 return SDValue(); 6797 6798 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6799 // Span too large for a VEXT to cope 6800 return SDValue(); 6801 } 6802 6803 if (Src.MinElt >= NumSrcElts) { 6804 // The extraction can just take the second half 6805 Src.ShuffleVec = 6806 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6807 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6808 Src.WindowBase = -NumSrcElts; 6809 } else if (Src.MaxElt < NumSrcElts) { 6810 // The extraction can just take the first half 6811 Src.ShuffleVec = 6812 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6813 DAG.getConstant(0, dl, MVT::i32)); 6814 } else { 6815 // An actual VEXT is needed 6816 SDValue VEXTSrc1 = 6817 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6818 DAG.getConstant(0, dl, MVT::i32)); 6819 SDValue VEXTSrc2 = 6820 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6821 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6822 6823 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6824 VEXTSrc2, 6825 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6826 Src.WindowBase = -Src.MinElt; 6827 } 6828 } 6829 6830 // Another possible incompatibility occurs from the vector element types. We 6831 // can fix this by bitcasting the source vectors to the same type we intend 6832 // for the shuffle. 6833 for (auto &Src : Sources) { 6834 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6835 if (SrcEltTy == SmallestEltTy) 6836 continue; 6837 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6838 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6839 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6840 Src.WindowBase *= Src.WindowScale; 6841 } 6842 6843 // Final sanity check before we try to actually produce a shuffle. 6844 DEBUG( 6845 for (auto Src : Sources) 6846 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6847 ); 6848 6849 // The stars all align, our next step is to produce the mask for the shuffle. 6850 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6851 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6852 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6853 SDValue Entry = Op.getOperand(i); 6854 if (Entry.isUndef()) 6855 continue; 6856 6857 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6858 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6859 6860 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6861 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6862 // segment. 6863 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6864 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6865 VT.getScalarSizeInBits()); 6866 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6867 6868 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6869 // starting at the appropriate offset. 6870 int *LaneMask = &Mask[i * ResMultiplier]; 6871 6872 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6873 ExtractBase += NumElts * (Src - Sources.begin()); 6874 for (int j = 0; j < LanesDefined; ++j) 6875 LaneMask[j] = ExtractBase + j; 6876 } 6877 6878 // Final check before we try to produce nonsense... 6879 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6880 return SDValue(); 6881 6882 // We can't handle more than two sources. This should have already 6883 // been checked before this point. 6884 assert(Sources.size() <= 2 && "Too many sources!"); 6885 6886 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6887 for (unsigned i = 0; i < Sources.size(); ++i) 6888 ShuffleOps[i] = Sources[i].ShuffleVec; 6889 6890 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6891 ShuffleOps[1], Mask); 6892 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6893 } 6894 6895 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6896 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6897 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6898 /// are assumed to be legal. 6899 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 6900 if (VT.getVectorNumElements() == 4 && 6901 (VT.is128BitVector() || VT.is64BitVector())) { 6902 unsigned PFIndexes[4]; 6903 for (unsigned i = 0; i != 4; ++i) { 6904 if (M[i] < 0) 6905 PFIndexes[i] = 8; 6906 else 6907 PFIndexes[i] = M[i]; 6908 } 6909 6910 // Compute the index in the perfect shuffle table. 6911 unsigned PFTableIndex = 6912 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6913 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6914 unsigned Cost = (PFEntry >> 30); 6915 6916 if (Cost <= 4) 6917 return true; 6918 } 6919 6920 bool ReverseVEXT, isV_UNDEF; 6921 unsigned Imm, WhichResult; 6922 6923 unsigned EltSize = VT.getScalarSizeInBits(); 6924 return (EltSize >= 32 || 6925 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6926 isVREVMask(M, VT, 64) || 6927 isVREVMask(M, VT, 32) || 6928 isVREVMask(M, VT, 16) || 6929 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6930 isVTBLMask(M, VT) || 6931 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6932 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6933 } 6934 6935 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6936 /// the specified operations to build the shuffle. 6937 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6938 SDValue RHS, SelectionDAG &DAG, 6939 const SDLoc &dl) { 6940 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6941 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6942 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6943 6944 enum { 6945 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6946 OP_VREV, 6947 OP_VDUP0, 6948 OP_VDUP1, 6949 OP_VDUP2, 6950 OP_VDUP3, 6951 OP_VEXT1, 6952 OP_VEXT2, 6953 OP_VEXT3, 6954 OP_VUZPL, // VUZP, left result 6955 OP_VUZPR, // VUZP, right result 6956 OP_VZIPL, // VZIP, left result 6957 OP_VZIPR, // VZIP, right result 6958 OP_VTRNL, // VTRN, left result 6959 OP_VTRNR // VTRN, right result 6960 }; 6961 6962 if (OpNum == OP_COPY) { 6963 if (LHSID == (1*9+2)*9+3) return LHS; 6964 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6965 return RHS; 6966 } 6967 6968 SDValue OpLHS, OpRHS; 6969 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6970 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6971 EVT VT = OpLHS.getValueType(); 6972 6973 switch (OpNum) { 6974 default: llvm_unreachable("Unknown shuffle opcode!"); 6975 case OP_VREV: 6976 // VREV divides the vector in half and swaps within the half. 6977 if (VT.getVectorElementType() == MVT::i32 || 6978 VT.getVectorElementType() == MVT::f32) 6979 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6980 // vrev <4 x i16> -> VREV32 6981 if (VT.getVectorElementType() == MVT::i16) 6982 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6983 // vrev <4 x i8> -> VREV16 6984 assert(VT.getVectorElementType() == MVT::i8); 6985 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6986 case OP_VDUP0: 6987 case OP_VDUP1: 6988 case OP_VDUP2: 6989 case OP_VDUP3: 6990 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6991 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6992 case OP_VEXT1: 6993 case OP_VEXT2: 6994 case OP_VEXT3: 6995 return DAG.getNode(ARMISD::VEXT, dl, VT, 6996 OpLHS, OpRHS, 6997 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6998 case OP_VUZPL: 6999 case OP_VUZPR: 7000 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 7001 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 7002 case OP_VZIPL: 7003 case OP_VZIPR: 7004 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 7005 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 7006 case OP_VTRNL: 7007 case OP_VTRNR: 7008 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 7009 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 7010 } 7011 } 7012 7013 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 7014 ArrayRef<int> ShuffleMask, 7015 SelectionDAG &DAG) { 7016 // Check to see if we can use the VTBL instruction. 7017 SDValue V1 = Op.getOperand(0); 7018 SDValue V2 = Op.getOperand(1); 7019 SDLoc DL(Op); 7020 7021 SmallVector<SDValue, 8> VTBLMask; 7022 for (ArrayRef<int>::iterator 7023 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 7024 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 7025 7026 if (V2.getNode()->isUndef()) 7027 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 7028 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7029 7030 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 7031 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7032 } 7033 7034 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 7035 SelectionDAG &DAG) { 7036 SDLoc DL(Op); 7037 SDValue OpLHS = Op.getOperand(0); 7038 EVT VT = OpLHS.getValueType(); 7039 7040 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 7041 "Expect an v8i16/v16i8 type"); 7042 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 7043 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 7044 // extract the first 8 bytes into the top double word and the last 8 bytes 7045 // into the bottom double word. The v8i16 case is similar. 7046 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 7047 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 7048 DAG.getConstant(ExtractNum, DL, MVT::i32)); 7049 } 7050 7051 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 7052 SDValue V1 = Op.getOperand(0); 7053 SDValue V2 = Op.getOperand(1); 7054 SDLoc dl(Op); 7055 EVT VT = Op.getValueType(); 7056 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7057 7058 // Convert shuffles that are directly supported on NEON to target-specific 7059 // DAG nodes, instead of keeping them as shuffles and matching them again 7060 // during code selection. This is more efficient and avoids the possibility 7061 // of inconsistencies between legalization and selection. 7062 // FIXME: floating-point vectors should be canonicalized to integer vectors 7063 // of the same time so that they get CSEd properly. 7064 ArrayRef<int> ShuffleMask = SVN->getMask(); 7065 7066 unsigned EltSize = VT.getScalarSizeInBits(); 7067 if (EltSize <= 32) { 7068 if (SVN->isSplat()) { 7069 int Lane = SVN->getSplatIndex(); 7070 // If this is undef splat, generate it via "just" vdup, if possible. 7071 if (Lane == -1) Lane = 0; 7072 7073 // Test if V1 is a SCALAR_TO_VECTOR. 7074 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7075 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7076 } 7077 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7078 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 7079 // reaches it). 7080 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 7081 !isa<ConstantSDNode>(V1.getOperand(0))) { 7082 bool IsScalarToVector = true; 7083 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 7084 if (!V1.getOperand(i).isUndef()) { 7085 IsScalarToVector = false; 7086 break; 7087 } 7088 if (IsScalarToVector) 7089 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7090 } 7091 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7092 DAG.getConstant(Lane, dl, MVT::i32)); 7093 } 7094 7095 bool ReverseVEXT; 7096 unsigned Imm; 7097 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7098 if (ReverseVEXT) 7099 std::swap(V1, V2); 7100 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7101 DAG.getConstant(Imm, dl, MVT::i32)); 7102 } 7103 7104 if (isVREVMask(ShuffleMask, VT, 64)) 7105 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7106 if (isVREVMask(ShuffleMask, VT, 32)) 7107 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7108 if (isVREVMask(ShuffleMask, VT, 16)) 7109 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7110 7111 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7112 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7113 DAG.getConstant(Imm, dl, MVT::i32)); 7114 } 7115 7116 // Check for Neon shuffles that modify both input vectors in place. 7117 // If both results are used, i.e., if there are two shuffles with the same 7118 // source operands and with masks corresponding to both results of one of 7119 // these operations, DAG memoization will ensure that a single node is 7120 // used for both shuffles. 7121 unsigned WhichResult; 7122 bool isV_UNDEF; 7123 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7124 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7125 if (isV_UNDEF) 7126 V2 = V1; 7127 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7128 .getValue(WhichResult); 7129 } 7130 7131 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7132 // shuffles that produce a result larger than their operands with: 7133 // shuffle(concat(v1, undef), concat(v2, undef)) 7134 // -> 7135 // shuffle(concat(v1, v2), undef) 7136 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7137 // 7138 // This is useful in the general case, but there are special cases where 7139 // native shuffles produce larger results: the two-result ops. 7140 // 7141 // Look through the concat when lowering them: 7142 // shuffle(concat(v1, v2), undef) 7143 // -> 7144 // concat(VZIP(v1, v2):0, :1) 7145 // 7146 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7147 SDValue SubV1 = V1->getOperand(0); 7148 SDValue SubV2 = V1->getOperand(1); 7149 EVT SubVT = SubV1.getValueType(); 7150 7151 // We expect these to have been canonicalized to -1. 7152 assert(llvm::all_of(ShuffleMask, [&](int i) { 7153 return i < (int)VT.getVectorNumElements(); 7154 }) && "Unexpected shuffle index into UNDEF operand!"); 7155 7156 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7157 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7158 if (isV_UNDEF) 7159 SubV2 = SubV1; 7160 assert((WhichResult == 0) && 7161 "In-place shuffle of concat can only have one result!"); 7162 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7163 SubV1, SubV2); 7164 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7165 Res.getValue(1)); 7166 } 7167 } 7168 } 7169 7170 // If the shuffle is not directly supported and it has 4 elements, use 7171 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7172 unsigned NumElts = VT.getVectorNumElements(); 7173 if (NumElts == 4) { 7174 unsigned PFIndexes[4]; 7175 for (unsigned i = 0; i != 4; ++i) { 7176 if (ShuffleMask[i] < 0) 7177 PFIndexes[i] = 8; 7178 else 7179 PFIndexes[i] = ShuffleMask[i]; 7180 } 7181 7182 // Compute the index in the perfect shuffle table. 7183 unsigned PFTableIndex = 7184 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7185 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7186 unsigned Cost = (PFEntry >> 30); 7187 7188 if (Cost <= 4) 7189 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7190 } 7191 7192 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7193 if (EltSize >= 32) { 7194 // Do the expansion with floating-point types, since that is what the VFP 7195 // registers are defined to use, and since i64 is not legal. 7196 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7197 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7198 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7199 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7200 SmallVector<SDValue, 8> Ops; 7201 for (unsigned i = 0; i < NumElts; ++i) { 7202 if (ShuffleMask[i] < 0) 7203 Ops.push_back(DAG.getUNDEF(EltVT)); 7204 else 7205 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7206 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7207 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7208 dl, MVT::i32))); 7209 } 7210 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7211 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7212 } 7213 7214 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7215 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7216 7217 if (VT == MVT::v8i8) 7218 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7219 return NewOp; 7220 7221 return SDValue(); 7222 } 7223 7224 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7225 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7226 SDValue Lane = Op.getOperand(2); 7227 if (!isa<ConstantSDNode>(Lane)) 7228 return SDValue(); 7229 7230 return Op; 7231 } 7232 7233 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7234 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7235 SDValue Lane = Op.getOperand(1); 7236 if (!isa<ConstantSDNode>(Lane)) 7237 return SDValue(); 7238 7239 SDValue Vec = Op.getOperand(0); 7240 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7241 SDLoc dl(Op); 7242 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7243 } 7244 7245 return Op; 7246 } 7247 7248 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 7249 // The only time a CONCAT_VECTORS operation can have legal types is when 7250 // two 64-bit vectors are concatenated to a 128-bit vector. 7251 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7252 "unexpected CONCAT_VECTORS"); 7253 SDLoc dl(Op); 7254 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7255 SDValue Op0 = Op.getOperand(0); 7256 SDValue Op1 = Op.getOperand(1); 7257 if (!Op0.isUndef()) 7258 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7259 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7260 DAG.getIntPtrConstant(0, dl)); 7261 if (!Op1.isUndef()) 7262 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7263 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7264 DAG.getIntPtrConstant(1, dl)); 7265 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7266 } 7267 7268 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7269 /// element has been zero/sign-extended, depending on the isSigned parameter, 7270 /// from an integer type half its size. 7271 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7272 bool isSigned) { 7273 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7274 EVT VT = N->getValueType(0); 7275 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7276 SDNode *BVN = N->getOperand(0).getNode(); 7277 if (BVN->getValueType(0) != MVT::v4i32 || 7278 BVN->getOpcode() != ISD::BUILD_VECTOR) 7279 return false; 7280 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7281 unsigned HiElt = 1 - LoElt; 7282 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7283 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7284 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7285 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7286 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7287 return false; 7288 if (isSigned) { 7289 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7290 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7291 return true; 7292 } else { 7293 if (Hi0->isNullValue() && Hi1->isNullValue()) 7294 return true; 7295 } 7296 return false; 7297 } 7298 7299 if (N->getOpcode() != ISD::BUILD_VECTOR) 7300 return false; 7301 7302 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7303 SDNode *Elt = N->getOperand(i).getNode(); 7304 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 7305 unsigned EltSize = VT.getScalarSizeInBits(); 7306 unsigned HalfSize = EltSize / 2; 7307 if (isSigned) { 7308 if (!isIntN(HalfSize, C->getSExtValue())) 7309 return false; 7310 } else { 7311 if (!isUIntN(HalfSize, C->getZExtValue())) 7312 return false; 7313 } 7314 continue; 7315 } 7316 return false; 7317 } 7318 7319 return true; 7320 } 7321 7322 /// isSignExtended - Check if a node is a vector value that is sign-extended 7323 /// or a constant BUILD_VECTOR with sign-extended elements. 7324 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7325 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7326 return true; 7327 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7328 return true; 7329 return false; 7330 } 7331 7332 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7333 /// or a constant BUILD_VECTOR with zero-extended elements. 7334 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7335 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7336 return true; 7337 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7338 return true; 7339 return false; 7340 } 7341 7342 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7343 if (OrigVT.getSizeInBits() >= 64) 7344 return OrigVT; 7345 7346 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7347 7348 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7349 switch (OrigSimpleTy) { 7350 default: llvm_unreachable("Unexpected Vector Type"); 7351 case MVT::v2i8: 7352 case MVT::v2i16: 7353 return MVT::v2i32; 7354 case MVT::v4i8: 7355 return MVT::v4i16; 7356 } 7357 } 7358 7359 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7360 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7361 /// We insert the required extension here to get the vector to fill a D register. 7362 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7363 const EVT &OrigTy, 7364 const EVT &ExtTy, 7365 unsigned ExtOpcode) { 7366 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7367 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7368 // 64-bits we need to insert a new extension so that it will be 64-bits. 7369 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7370 if (OrigTy.getSizeInBits() >= 64) 7371 return N; 7372 7373 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7374 EVT NewVT = getExtensionTo64Bits(OrigTy); 7375 7376 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7377 } 7378 7379 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7380 /// does not do any sign/zero extension. If the original vector is less 7381 /// than 64 bits, an appropriate extension will be added after the load to 7382 /// reach a total size of 64 bits. We have to add the extension separately 7383 /// because ARM does not have a sign/zero extending load for vectors. 7384 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7385 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7386 7387 // The load already has the right type. 7388 if (ExtendedTy == LD->getMemoryVT()) 7389 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7390 LD->getBasePtr(), LD->getPointerInfo(), 7391 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7392 7393 // We need to create a zextload/sextload. We cannot just create a load 7394 // followed by a zext/zext node because LowerMUL is also run during normal 7395 // operation legalization where we can't create illegal types. 7396 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7397 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7398 LD->getMemoryVT(), LD->getAlignment(), 7399 LD->getMemOperand()->getFlags()); 7400 } 7401 7402 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7403 /// extending load, or BUILD_VECTOR with extended elements, return the 7404 /// unextended value. The unextended vector should be 64 bits so that it can 7405 /// be used as an operand to a VMULL instruction. If the original vector size 7406 /// before extension is less than 64 bits we add a an extension to resize 7407 /// the vector to 64 bits. 7408 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7409 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7410 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7411 N->getOperand(0)->getValueType(0), 7412 N->getValueType(0), 7413 N->getOpcode()); 7414 7415 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7416 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7417 "Expected extending load"); 7418 7419 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7420 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7421 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7422 SDValue extLoad = 7423 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7424 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7425 7426 return newLoad; 7427 } 7428 7429 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7430 // have been legalized as a BITCAST from v4i32. 7431 if (N->getOpcode() == ISD::BITCAST) { 7432 SDNode *BVN = N->getOperand(0).getNode(); 7433 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7434 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7435 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7436 return DAG.getBuildVector( 7437 MVT::v2i32, SDLoc(N), 7438 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7439 } 7440 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7441 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7442 EVT VT = N->getValueType(0); 7443 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7444 unsigned NumElts = VT.getVectorNumElements(); 7445 MVT TruncVT = MVT::getIntegerVT(EltSize); 7446 SmallVector<SDValue, 8> Ops; 7447 SDLoc dl(N); 7448 for (unsigned i = 0; i != NumElts; ++i) { 7449 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7450 const APInt &CInt = C->getAPIntValue(); 7451 // Element types smaller than 32 bits are not legal, so use i32 elements. 7452 // The values are implicitly truncated so sext vs. zext doesn't matter. 7453 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7454 } 7455 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7456 } 7457 7458 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7459 unsigned Opcode = N->getOpcode(); 7460 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7461 SDNode *N0 = N->getOperand(0).getNode(); 7462 SDNode *N1 = N->getOperand(1).getNode(); 7463 return N0->hasOneUse() && N1->hasOneUse() && 7464 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7465 } 7466 return false; 7467 } 7468 7469 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7470 unsigned Opcode = N->getOpcode(); 7471 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7472 SDNode *N0 = N->getOperand(0).getNode(); 7473 SDNode *N1 = N->getOperand(1).getNode(); 7474 return N0->hasOneUse() && N1->hasOneUse() && 7475 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7476 } 7477 return false; 7478 } 7479 7480 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7481 // Multiplications are only custom-lowered for 128-bit vectors so that 7482 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7483 EVT VT = Op.getValueType(); 7484 assert(VT.is128BitVector() && VT.isInteger() && 7485 "unexpected type for custom-lowering ISD::MUL"); 7486 SDNode *N0 = Op.getOperand(0).getNode(); 7487 SDNode *N1 = Op.getOperand(1).getNode(); 7488 unsigned NewOpc = 0; 7489 bool isMLA = false; 7490 bool isN0SExt = isSignExtended(N0, DAG); 7491 bool isN1SExt = isSignExtended(N1, DAG); 7492 if (isN0SExt && isN1SExt) 7493 NewOpc = ARMISD::VMULLs; 7494 else { 7495 bool isN0ZExt = isZeroExtended(N0, DAG); 7496 bool isN1ZExt = isZeroExtended(N1, DAG); 7497 if (isN0ZExt && isN1ZExt) 7498 NewOpc = ARMISD::VMULLu; 7499 else if (isN1SExt || isN1ZExt) { 7500 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7501 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7502 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7503 NewOpc = ARMISD::VMULLs; 7504 isMLA = true; 7505 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7506 NewOpc = ARMISD::VMULLu; 7507 isMLA = true; 7508 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7509 std::swap(N0, N1); 7510 NewOpc = ARMISD::VMULLu; 7511 isMLA = true; 7512 } 7513 } 7514 7515 if (!NewOpc) { 7516 if (VT == MVT::v2i64) 7517 // Fall through to expand this. It is not legal. 7518 return SDValue(); 7519 else 7520 // Other vector multiplications are legal. 7521 return Op; 7522 } 7523 } 7524 7525 // Legalize to a VMULL instruction. 7526 SDLoc DL(Op); 7527 SDValue Op0; 7528 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7529 if (!isMLA) { 7530 Op0 = SkipExtensionForVMULL(N0, DAG); 7531 assert(Op0.getValueType().is64BitVector() && 7532 Op1.getValueType().is64BitVector() && 7533 "unexpected types for extended operands to VMULL"); 7534 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7535 } 7536 7537 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7538 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7539 // vmull q0, d4, d6 7540 // vmlal q0, d5, d6 7541 // is faster than 7542 // vaddl q0, d4, d5 7543 // vmovl q1, d6 7544 // vmul q0, q0, q1 7545 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7546 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7547 EVT Op1VT = Op1.getValueType(); 7548 return DAG.getNode(N0->getOpcode(), DL, VT, 7549 DAG.getNode(NewOpc, DL, VT, 7550 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7551 DAG.getNode(NewOpc, DL, VT, 7552 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7553 } 7554 7555 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7556 SelectionDAG &DAG) { 7557 // TODO: Should this propagate fast-math-flags? 7558 7559 // Convert to float 7560 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7561 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7562 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7563 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7564 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7565 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7566 // Get reciprocal estimate. 7567 // float4 recip = vrecpeq_f32(yf); 7568 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7569 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7570 Y); 7571 // Because char has a smaller range than uchar, we can actually get away 7572 // without any newton steps. This requires that we use a weird bias 7573 // of 0xb000, however (again, this has been exhaustively tested). 7574 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7575 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7576 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7577 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7578 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7579 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7580 // Convert back to short. 7581 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7582 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7583 return X; 7584 } 7585 7586 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7587 SelectionDAG &DAG) { 7588 // TODO: Should this propagate fast-math-flags? 7589 7590 SDValue N2; 7591 // Convert to float. 7592 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7593 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7594 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7595 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7596 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7597 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7598 7599 // Use reciprocal estimate and one refinement step. 7600 // float4 recip = vrecpeq_f32(yf); 7601 // recip *= vrecpsq_f32(yf, recip); 7602 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7603 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7604 N1); 7605 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7606 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7607 N1, N2); 7608 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7609 // Because short has a smaller range than ushort, we can actually get away 7610 // with only a single newton step. This requires that we use a weird bias 7611 // of 89, however (again, this has been exhaustively tested). 7612 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7613 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7614 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7615 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7616 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7617 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7618 // Convert back to integer and return. 7619 // return vmovn_s32(vcvt_s32_f32(result)); 7620 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7621 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7622 return N0; 7623 } 7624 7625 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7626 EVT VT = Op.getValueType(); 7627 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7628 "unexpected type for custom-lowering ISD::SDIV"); 7629 7630 SDLoc dl(Op); 7631 SDValue N0 = Op.getOperand(0); 7632 SDValue N1 = Op.getOperand(1); 7633 SDValue N2, N3; 7634 7635 if (VT == MVT::v8i8) { 7636 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7637 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7638 7639 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7640 DAG.getIntPtrConstant(4, dl)); 7641 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7642 DAG.getIntPtrConstant(4, dl)); 7643 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7644 DAG.getIntPtrConstant(0, dl)); 7645 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7646 DAG.getIntPtrConstant(0, dl)); 7647 7648 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7649 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7650 7651 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7652 N0 = LowerCONCAT_VECTORS(N0, DAG); 7653 7654 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7655 return N0; 7656 } 7657 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7658 } 7659 7660 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7661 // TODO: Should this propagate fast-math-flags? 7662 EVT VT = Op.getValueType(); 7663 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7664 "unexpected type for custom-lowering ISD::UDIV"); 7665 7666 SDLoc dl(Op); 7667 SDValue N0 = Op.getOperand(0); 7668 SDValue N1 = Op.getOperand(1); 7669 SDValue N2, N3; 7670 7671 if (VT == MVT::v8i8) { 7672 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7673 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7674 7675 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7676 DAG.getIntPtrConstant(4, dl)); 7677 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7678 DAG.getIntPtrConstant(4, dl)); 7679 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7680 DAG.getIntPtrConstant(0, dl)); 7681 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7682 DAG.getIntPtrConstant(0, dl)); 7683 7684 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7685 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7686 7687 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7688 N0 = LowerCONCAT_VECTORS(N0, DAG); 7689 7690 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7691 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7692 MVT::i32), 7693 N0); 7694 return N0; 7695 } 7696 7697 // v4i16 sdiv ... Convert to float. 7698 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7699 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7700 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7701 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7702 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7703 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7704 7705 // Use reciprocal estimate and two refinement steps. 7706 // float4 recip = vrecpeq_f32(yf); 7707 // recip *= vrecpsq_f32(yf, recip); 7708 // recip *= vrecpsq_f32(yf, recip); 7709 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7710 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7711 BN1); 7712 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7713 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7714 BN1, N2); 7715 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7716 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7717 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7718 BN1, N2); 7719 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7720 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7721 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7722 // and that it will never cause us to return an answer too large). 7723 // float4 result = as_float4(as_int4(xf*recip) + 2); 7724 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7725 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7726 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7727 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7728 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7729 // Convert back to integer and return. 7730 // return vmovn_u32(vcvt_s32_f32(result)); 7731 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7732 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7733 return N0; 7734 } 7735 7736 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7737 EVT VT = Op.getNode()->getValueType(0); 7738 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7739 7740 unsigned Opc; 7741 bool ExtraOp = false; 7742 switch (Op.getOpcode()) { 7743 default: llvm_unreachable("Invalid code"); 7744 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7745 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7746 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7747 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7748 } 7749 7750 if (!ExtraOp) 7751 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7752 Op.getOperand(1)); 7753 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7754 Op.getOperand(1), Op.getOperand(2)); 7755 } 7756 7757 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 7758 SDNode *N = Op.getNode(); 7759 EVT VT = N->getValueType(0); 7760 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7761 7762 SDValue Carry = Op.getOperand(2); 7763 7764 SDLoc DL(Op); 7765 7766 SDValue Result; 7767 if (Op.getOpcode() == ISD::ADDCARRY) { 7768 // This converts the boolean value carry into the carry flag. 7769 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7770 7771 // Do the addition proper using the carry flag we wanted. 7772 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 7773 Op.getOperand(1), Carry); 7774 7775 // Now convert the carry flag into a boolean value. 7776 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7777 } else { 7778 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 7779 // have to invert the carry first. 7780 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7781 DAG.getConstant(1, DL, MVT::i32), Carry); 7782 // This converts the boolean value carry into the carry flag. 7783 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7784 7785 // Do the subtraction proper using the carry flag we wanted. 7786 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 7787 Op.getOperand(1), Carry); 7788 7789 // Now convert the carry flag into a boolean value. 7790 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7791 // But the carry returned by ARMISD::SUBE is not a borrow as expected 7792 // by ISD::SUBCARRY, so compute 1 - C. 7793 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7794 DAG.getConstant(1, DL, MVT::i32), Carry); 7795 } 7796 7797 // Return both values. 7798 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 7799 } 7800 7801 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7802 assert(Subtarget->isTargetDarwin()); 7803 7804 // For iOS, we want to call an alternative entry point: __sincos_stret, 7805 // return values are passed via sret. 7806 SDLoc dl(Op); 7807 SDValue Arg = Op.getOperand(0); 7808 EVT ArgVT = Arg.getValueType(); 7809 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7810 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7811 7812 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7813 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7814 7815 // Pair of floats / doubles used to pass the result. 7816 Type *RetTy = StructType::get(ArgTy, ArgTy); 7817 auto &DL = DAG.getDataLayout(); 7818 7819 ArgListTy Args; 7820 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7821 SDValue SRet; 7822 if (ShouldUseSRet) { 7823 // Create stack object for sret. 7824 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7825 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7826 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7827 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7828 7829 ArgListEntry Entry; 7830 Entry.Node = SRet; 7831 Entry.Ty = RetTy->getPointerTo(); 7832 Entry.IsSExt = false; 7833 Entry.IsZExt = false; 7834 Entry.IsSRet = true; 7835 Args.push_back(Entry); 7836 RetTy = Type::getVoidTy(*DAG.getContext()); 7837 } 7838 7839 ArgListEntry Entry; 7840 Entry.Node = Arg; 7841 Entry.Ty = ArgTy; 7842 Entry.IsSExt = false; 7843 Entry.IsZExt = false; 7844 Args.push_back(Entry); 7845 7846 RTLIB::Libcall LC = 7847 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 7848 const char *LibcallName = getLibcallName(LC); 7849 CallingConv::ID CC = getLibcallCallingConv(LC); 7850 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7851 7852 TargetLowering::CallLoweringInfo CLI(DAG); 7853 CLI.setDebugLoc(dl) 7854 .setChain(DAG.getEntryNode()) 7855 .setCallee(CC, RetTy, Callee, std::move(Args)) 7856 .setDiscardResult(ShouldUseSRet); 7857 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7858 7859 if (!ShouldUseSRet) 7860 return CallResult.first; 7861 7862 SDValue LoadSin = 7863 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7864 7865 // Address of cos field. 7866 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7867 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7868 SDValue LoadCos = 7869 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7870 7871 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7872 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7873 LoadSin.getValue(0), LoadCos.getValue(0)); 7874 } 7875 7876 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7877 bool Signed, 7878 SDValue &Chain) const { 7879 EVT VT = Op.getValueType(); 7880 assert((VT == MVT::i32 || VT == MVT::i64) && 7881 "unexpected type for custom lowering DIV"); 7882 SDLoc dl(Op); 7883 7884 const auto &DL = DAG.getDataLayout(); 7885 const auto &TLI = DAG.getTargetLoweringInfo(); 7886 7887 const char *Name = nullptr; 7888 if (Signed) 7889 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7890 else 7891 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7892 7893 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7894 7895 ARMTargetLowering::ArgListTy Args; 7896 7897 for (auto AI : {1, 0}) { 7898 ArgListEntry Arg; 7899 Arg.Node = Op.getOperand(AI); 7900 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7901 Args.push_back(Arg); 7902 } 7903 7904 CallLoweringInfo CLI(DAG); 7905 CLI.setDebugLoc(dl) 7906 .setChain(Chain) 7907 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7908 ES, std::move(Args)); 7909 7910 return LowerCallTo(CLI).first; 7911 } 7912 7913 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7914 bool Signed) const { 7915 assert(Op.getValueType() == MVT::i32 && 7916 "unexpected type for custom lowering DIV"); 7917 SDLoc dl(Op); 7918 7919 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7920 DAG.getEntryNode(), Op.getOperand(1)); 7921 7922 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7923 } 7924 7925 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7926 SDLoc DL(N); 7927 SDValue Op = N->getOperand(1); 7928 if (N->getValueType(0) == MVT::i32) 7929 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7930 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7931 DAG.getConstant(0, DL, MVT::i32)); 7932 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7933 DAG.getConstant(1, DL, MVT::i32)); 7934 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7935 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7936 } 7937 7938 void ARMTargetLowering::ExpandDIV_Windows( 7939 SDValue Op, SelectionDAG &DAG, bool Signed, 7940 SmallVectorImpl<SDValue> &Results) const { 7941 const auto &DL = DAG.getDataLayout(); 7942 const auto &TLI = DAG.getTargetLoweringInfo(); 7943 7944 assert(Op.getValueType() == MVT::i64 && 7945 "unexpected type for custom lowering DIV"); 7946 SDLoc dl(Op); 7947 7948 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7949 7950 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7951 7952 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7953 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7954 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7955 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7956 7957 Results.push_back(Lower); 7958 Results.push_back(Upper); 7959 } 7960 7961 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7962 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7963 // Acquire/Release load/store is not legal for targets without a dmb or 7964 // equivalent available. 7965 return SDValue(); 7966 7967 // Monotonic load/store is legal for all targets. 7968 return Op; 7969 } 7970 7971 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7972 SmallVectorImpl<SDValue> &Results, 7973 SelectionDAG &DAG, 7974 const ARMSubtarget *Subtarget) { 7975 SDLoc DL(N); 7976 // Under Power Management extensions, the cycle-count is: 7977 // mrc p15, #0, <Rt>, c9, c13, #0 7978 SDValue Ops[] = { N->getOperand(0), // Chain 7979 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7980 DAG.getConstant(15, DL, MVT::i32), 7981 DAG.getConstant(0, DL, MVT::i32), 7982 DAG.getConstant(9, DL, MVT::i32), 7983 DAG.getConstant(13, DL, MVT::i32), 7984 DAG.getConstant(0, DL, MVT::i32) 7985 }; 7986 7987 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7988 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7989 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7990 DAG.getConstant(0, DL, MVT::i32))); 7991 Results.push_back(Cycles32.getValue(1)); 7992 } 7993 7994 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7995 SDLoc dl(V.getNode()); 7996 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7997 SDValue VHi = DAG.getAnyExtOrTrunc( 7998 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7999 dl, MVT::i32); 8000 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8001 if (isBigEndian) 8002 std::swap (VLo, VHi); 8003 SDValue RegClass = 8004 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 8005 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 8006 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 8007 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 8008 return SDValue( 8009 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 8010 } 8011 8012 static void ReplaceCMP_SWAP_64Results(SDNode *N, 8013 SmallVectorImpl<SDValue> & Results, 8014 SelectionDAG &DAG) { 8015 assert(N->getValueType(0) == MVT::i64 && 8016 "AtomicCmpSwap on types less than 64 should be legal"); 8017 SDValue Ops[] = {N->getOperand(1), 8018 createGPRPairNode(DAG, N->getOperand(2)), 8019 createGPRPairNode(DAG, N->getOperand(3)), 8020 N->getOperand(0)}; 8021 SDNode *CmpSwap = DAG.getMachineNode( 8022 ARM::CMP_SWAP_64, SDLoc(N), 8023 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 8024 8025 MachineFunction &MF = DAG.getMachineFunction(); 8026 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 8027 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 8028 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 8029 8030 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8031 8032 Results.push_back( 8033 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 8034 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8035 Results.push_back( 8036 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 8037 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8038 Results.push_back(SDValue(CmpSwap, 2)); 8039 } 8040 8041 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 8042 SelectionDAG &DAG) { 8043 const auto &TLI = DAG.getTargetLoweringInfo(); 8044 8045 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 8046 "Custom lowering is MSVCRT specific!"); 8047 8048 SDLoc dl(Op); 8049 SDValue Val = Op.getOperand(0); 8050 MVT Ty = Val->getSimpleValueType(0); 8051 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 8052 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 8053 TLI.getPointerTy(DAG.getDataLayout())); 8054 8055 TargetLowering::ArgListTy Args; 8056 TargetLowering::ArgListEntry Entry; 8057 8058 Entry.Node = Val; 8059 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8060 Entry.IsZExt = true; 8061 Args.push_back(Entry); 8062 8063 Entry.Node = Exponent; 8064 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 8065 Entry.IsZExt = true; 8066 Args.push_back(Entry); 8067 8068 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8069 8070 // In the in-chain to the call is the entry node If we are emitting a 8071 // tailcall, the chain will be mutated if the node has a non-entry input 8072 // chain. 8073 SDValue InChain = DAG.getEntryNode(); 8074 SDValue TCChain = InChain; 8075 8076 const Function &F = DAG.getMachineFunction().getFunction(); 8077 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8078 F.getReturnType() == LCRTy; 8079 if (IsTC) 8080 InChain = TCChain; 8081 8082 TargetLowering::CallLoweringInfo CLI(DAG); 8083 CLI.setDebugLoc(dl) 8084 .setChain(InChain) 8085 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8086 .setTailCall(IsTC); 8087 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8088 8089 // Return the chain (the DAG root) if it is a tail call 8090 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8091 } 8092 8093 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8094 DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8095 switch (Op.getOpcode()) { 8096 default: llvm_unreachable("Don't know how to custom lower this!"); 8097 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8098 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8099 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8100 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8101 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8102 case ISD::SELECT: return LowerSELECT(Op, DAG); 8103 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8104 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8105 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8106 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8107 case ISD::VASTART: return LowerVASTART(Op, DAG); 8108 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8109 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8110 case ISD::SINT_TO_FP: 8111 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8112 case ISD::FP_TO_SINT: 8113 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8114 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8115 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8116 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8117 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8118 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8119 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8120 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8121 Subtarget); 8122 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8123 case ISD::SHL: 8124 case ISD::SRL: 8125 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8126 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8127 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8128 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8129 case ISD::SRL_PARTS: 8130 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8131 case ISD::CTTZ: 8132 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8133 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8134 case ISD::SETCC: return LowerVSETCC(Op, DAG); 8135 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 8136 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8137 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8138 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 8139 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8140 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 8141 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 8142 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8143 case ISD::MUL: return LowerMUL(Op, DAG); 8144 case ISD::SDIV: 8145 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8146 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8147 return LowerSDIV(Op, DAG); 8148 case ISD::UDIV: 8149 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8150 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8151 return LowerUDIV(Op, DAG); 8152 case ISD::ADDC: 8153 case ISD::ADDE: 8154 case ISD::SUBC: 8155 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 8156 case ISD::ADDCARRY: 8157 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8158 case ISD::SADDO: 8159 case ISD::SSUBO: 8160 return LowerSignedALUO(Op, DAG); 8161 case ISD::UADDO: 8162 case ISD::USUBO: 8163 return LowerUnsignedALUO(Op, DAG); 8164 case ISD::ATOMIC_LOAD: 8165 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8166 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8167 case ISD::SDIVREM: 8168 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8169 case ISD::DYNAMIC_STACKALLOC: 8170 if (Subtarget->isTargetWindows()) 8171 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8172 llvm_unreachable("Don't know how to custom lower this!"); 8173 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8174 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8175 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8176 case ARMISD::WIN__DBZCHK: return SDValue(); 8177 } 8178 } 8179 8180 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8181 SelectionDAG &DAG) { 8182 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8183 unsigned Opc = 0; 8184 if (IntNo == Intrinsic::arm_smlald) 8185 Opc = ARMISD::SMLALD; 8186 else if (IntNo == Intrinsic::arm_smlaldx) 8187 Opc = ARMISD::SMLALDX; 8188 else if (IntNo == Intrinsic::arm_smlsld) 8189 Opc = ARMISD::SMLSLD; 8190 else if (IntNo == Intrinsic::arm_smlsldx) 8191 Opc = ARMISD::SMLSLDX; 8192 else 8193 return; 8194 8195 SDLoc dl(N); 8196 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8197 N->getOperand(3), 8198 DAG.getConstant(0, dl, MVT::i32)); 8199 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8200 N->getOperand(3), 8201 DAG.getConstant(1, dl, MVT::i32)); 8202 8203 SDValue LongMul = DAG.getNode(Opc, dl, 8204 DAG.getVTList(MVT::i32, MVT::i32), 8205 N->getOperand(1), N->getOperand(2), 8206 Lo, Hi); 8207 Results.push_back(LongMul.getValue(0)); 8208 Results.push_back(LongMul.getValue(1)); 8209 } 8210 8211 /// ReplaceNodeResults - Replace the results of node with an illegal result 8212 /// type with new values built out of custom code. 8213 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8214 SmallVectorImpl<SDValue> &Results, 8215 SelectionDAG &DAG) const { 8216 SDValue Res; 8217 switch (N->getOpcode()) { 8218 default: 8219 llvm_unreachable("Don't know how to custom expand this!"); 8220 case ISD::READ_REGISTER: 8221 ExpandREAD_REGISTER(N, Results, DAG); 8222 break; 8223 case ISD::BITCAST: 8224 Res = ExpandBITCAST(N, DAG, Subtarget); 8225 break; 8226 case ISD::SRL: 8227 case ISD::SRA: 8228 Res = Expand64BitShift(N, DAG, Subtarget); 8229 break; 8230 case ISD::SREM: 8231 case ISD::UREM: 8232 Res = LowerREM(N, DAG); 8233 break; 8234 case ISD::SDIVREM: 8235 case ISD::UDIVREM: 8236 Res = LowerDivRem(SDValue(N, 0), DAG); 8237 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 8238 Results.push_back(Res.getValue(0)); 8239 Results.push_back(Res.getValue(1)); 8240 return; 8241 case ISD::READCYCLECOUNTER: 8242 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8243 return; 8244 case ISD::UDIV: 8245 case ISD::SDIV: 8246 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8247 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8248 Results); 8249 case ISD::ATOMIC_CMP_SWAP: 8250 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8251 return; 8252 case ISD::INTRINSIC_WO_CHAIN: 8253 return ReplaceLongIntrinsic(N, Results, DAG); 8254 } 8255 if (Res.getNode()) 8256 Results.push_back(Res); 8257 } 8258 8259 //===----------------------------------------------------------------------===// 8260 // ARM Scheduler Hooks 8261 //===----------------------------------------------------------------------===// 8262 8263 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8264 /// registers the function context. 8265 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8266 MachineBasicBlock *MBB, 8267 MachineBasicBlock *DispatchBB, 8268 int FI) const { 8269 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8270 "ROPI/RWPI not currently supported with SjLj"); 8271 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8272 DebugLoc dl = MI.getDebugLoc(); 8273 MachineFunction *MF = MBB->getParent(); 8274 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8275 MachineConstantPool *MCP = MF->getConstantPool(); 8276 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8277 const Function &F = MF->getFunction(); 8278 8279 bool isThumb = Subtarget->isThumb(); 8280 bool isThumb2 = Subtarget->isThumb2(); 8281 8282 unsigned PCLabelId = AFI->createPICLabelUId(); 8283 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 8284 ARMConstantPoolValue *CPV = 8285 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 8286 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 8287 8288 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 8289 : &ARM::GPRRegClass; 8290 8291 // Grab constant pool and fixed stack memory operands. 8292 MachineMemOperand *CPMMO = 8293 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 8294 MachineMemOperand::MOLoad, 4, 4); 8295 8296 MachineMemOperand *FIMMOSt = 8297 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 8298 MachineMemOperand::MOStore, 4, 4); 8299 8300 // Load the address of the dispatch MBB into the jump buffer. 8301 if (isThumb2) { 8302 // Incoming value: jbuf 8303 // ldr.n r5, LCPI1_1 8304 // orr r5, r5, #1 8305 // add r5, pc 8306 // str r5, [$jbuf, #+4] ; &jbuf[1] 8307 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8308 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 8309 .addConstantPoolIndex(CPI) 8310 .addMemOperand(CPMMO) 8311 .add(predOps(ARMCC::AL)); 8312 // Set the low bit because of thumb mode. 8313 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8314 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 8315 .addReg(NewVReg1, RegState::Kill) 8316 .addImm(0x01) 8317 .add(predOps(ARMCC::AL)) 8318 .add(condCodeOp()); 8319 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8320 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8321 .addReg(NewVReg2, RegState::Kill) 8322 .addImm(PCLabelId); 8323 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8324 .addReg(NewVReg3, RegState::Kill) 8325 .addFrameIndex(FI) 8326 .addImm(36) // &jbuf[1] :: pc 8327 .addMemOperand(FIMMOSt) 8328 .add(predOps(ARMCC::AL)); 8329 } else if (isThumb) { 8330 // Incoming value: jbuf 8331 // ldr.n r1, LCPI1_4 8332 // add r1, pc 8333 // mov r2, #1 8334 // orrs r1, r2 8335 // add r2, $jbuf, #+4 ; &jbuf[1] 8336 // str r1, [r2] 8337 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8338 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8339 .addConstantPoolIndex(CPI) 8340 .addMemOperand(CPMMO) 8341 .add(predOps(ARMCC::AL)); 8342 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8343 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8344 .addReg(NewVReg1, RegState::Kill) 8345 .addImm(PCLabelId); 8346 // Set the low bit because of thumb mode. 8347 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8348 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8349 .addReg(ARM::CPSR, RegState::Define) 8350 .addImm(1) 8351 .add(predOps(ARMCC::AL)); 8352 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8353 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8354 .addReg(ARM::CPSR, RegState::Define) 8355 .addReg(NewVReg2, RegState::Kill) 8356 .addReg(NewVReg3, RegState::Kill) 8357 .add(predOps(ARMCC::AL)); 8358 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8359 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8360 .addFrameIndex(FI) 8361 .addImm(36); // &jbuf[1] :: pc 8362 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8363 .addReg(NewVReg4, RegState::Kill) 8364 .addReg(NewVReg5, RegState::Kill) 8365 .addImm(0) 8366 .addMemOperand(FIMMOSt) 8367 .add(predOps(ARMCC::AL)); 8368 } else { 8369 // Incoming value: jbuf 8370 // ldr r1, LCPI1_1 8371 // add r1, pc, r1 8372 // str r1, [$jbuf, #+4] ; &jbuf[1] 8373 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8374 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8375 .addConstantPoolIndex(CPI) 8376 .addImm(0) 8377 .addMemOperand(CPMMO) 8378 .add(predOps(ARMCC::AL)); 8379 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8380 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8381 .addReg(NewVReg1, RegState::Kill) 8382 .addImm(PCLabelId) 8383 .add(predOps(ARMCC::AL)); 8384 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8385 .addReg(NewVReg2, RegState::Kill) 8386 .addFrameIndex(FI) 8387 .addImm(36) // &jbuf[1] :: pc 8388 .addMemOperand(FIMMOSt) 8389 .add(predOps(ARMCC::AL)); 8390 } 8391 } 8392 8393 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8394 MachineBasicBlock *MBB) const { 8395 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8396 DebugLoc dl = MI.getDebugLoc(); 8397 MachineFunction *MF = MBB->getParent(); 8398 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8399 MachineFrameInfo &MFI = MF->getFrameInfo(); 8400 int FI = MFI.getFunctionContextIndex(); 8401 8402 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8403 : &ARM::GPRnopcRegClass; 8404 8405 // Get a mapping of the call site numbers to all of the landing pads they're 8406 // associated with. 8407 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8408 unsigned MaxCSNum = 0; 8409 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8410 ++BB) { 8411 if (!BB->isEHPad()) continue; 8412 8413 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8414 // pad. 8415 for (MachineBasicBlock::iterator 8416 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8417 if (!II->isEHLabel()) continue; 8418 8419 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8420 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8421 8422 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8423 for (SmallVectorImpl<unsigned>::iterator 8424 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8425 CSI != CSE; ++CSI) { 8426 CallSiteNumToLPad[*CSI].push_back(&*BB); 8427 MaxCSNum = std::max(MaxCSNum, *CSI); 8428 } 8429 break; 8430 } 8431 } 8432 8433 // Get an ordered list of the machine basic blocks for the jump table. 8434 std::vector<MachineBasicBlock*> LPadList; 8435 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8436 LPadList.reserve(CallSiteNumToLPad.size()); 8437 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8438 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8439 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8440 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8441 LPadList.push_back(*II); 8442 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8443 } 8444 } 8445 8446 assert(!LPadList.empty() && 8447 "No landing pad destinations for the dispatch jump table!"); 8448 8449 // Create the jump table and associated information. 8450 MachineJumpTableInfo *JTI = 8451 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8452 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8453 8454 // Create the MBBs for the dispatch code. 8455 8456 // Shove the dispatch's address into the return slot in the function context. 8457 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8458 DispatchBB->setIsEHPad(); 8459 8460 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8461 unsigned trap_opcode; 8462 if (Subtarget->isThumb()) 8463 trap_opcode = ARM::tTRAP; 8464 else 8465 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8466 8467 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8468 DispatchBB->addSuccessor(TrapBB); 8469 8470 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8471 DispatchBB->addSuccessor(DispContBB); 8472 8473 // Insert and MBBs. 8474 MF->insert(MF->end(), DispatchBB); 8475 MF->insert(MF->end(), DispContBB); 8476 MF->insert(MF->end(), TrapBB); 8477 8478 // Insert code into the entry block that creates and registers the function 8479 // context. 8480 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8481 8482 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8483 MachinePointerInfo::getFixedStack(*MF, FI), 8484 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8485 8486 MachineInstrBuilder MIB; 8487 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8488 8489 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8490 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8491 8492 // Add a register mask with no preserved registers. This results in all 8493 // registers being marked as clobbered. This can't work if the dispatch block 8494 // is in a Thumb1 function and is linked with ARM code which uses the FP 8495 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8496 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8497 8498 bool IsPositionIndependent = isPositionIndependent(); 8499 unsigned NumLPads = LPadList.size(); 8500 if (Subtarget->isThumb2()) { 8501 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8502 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8503 .addFrameIndex(FI) 8504 .addImm(4) 8505 .addMemOperand(FIMMOLd) 8506 .add(predOps(ARMCC::AL)); 8507 8508 if (NumLPads < 256) { 8509 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8510 .addReg(NewVReg1) 8511 .addImm(LPadList.size()) 8512 .add(predOps(ARMCC::AL)); 8513 } else { 8514 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8515 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8516 .addImm(NumLPads & 0xFFFF) 8517 .add(predOps(ARMCC::AL)); 8518 8519 unsigned VReg2 = VReg1; 8520 if ((NumLPads & 0xFFFF0000) != 0) { 8521 VReg2 = MRI->createVirtualRegister(TRC); 8522 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8523 .addReg(VReg1) 8524 .addImm(NumLPads >> 16) 8525 .add(predOps(ARMCC::AL)); 8526 } 8527 8528 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8529 .addReg(NewVReg1) 8530 .addReg(VReg2) 8531 .add(predOps(ARMCC::AL)); 8532 } 8533 8534 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8535 .addMBB(TrapBB) 8536 .addImm(ARMCC::HI) 8537 .addReg(ARM::CPSR); 8538 8539 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8540 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8541 .addJumpTableIndex(MJTI) 8542 .add(predOps(ARMCC::AL)); 8543 8544 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8545 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8546 .addReg(NewVReg3, RegState::Kill) 8547 .addReg(NewVReg1) 8548 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8549 .add(predOps(ARMCC::AL)) 8550 .add(condCodeOp()); 8551 8552 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8553 .addReg(NewVReg4, RegState::Kill) 8554 .addReg(NewVReg1) 8555 .addJumpTableIndex(MJTI); 8556 } else if (Subtarget->isThumb()) { 8557 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8558 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8559 .addFrameIndex(FI) 8560 .addImm(1) 8561 .addMemOperand(FIMMOLd) 8562 .add(predOps(ARMCC::AL)); 8563 8564 if (NumLPads < 256) { 8565 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8566 .addReg(NewVReg1) 8567 .addImm(NumLPads) 8568 .add(predOps(ARMCC::AL)); 8569 } else { 8570 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8571 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8572 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8573 8574 // MachineConstantPool wants an explicit alignment. 8575 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8576 if (Align == 0) 8577 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8578 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8579 8580 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8581 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8582 .addReg(VReg1, RegState::Define) 8583 .addConstantPoolIndex(Idx) 8584 .add(predOps(ARMCC::AL)); 8585 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8586 .addReg(NewVReg1) 8587 .addReg(VReg1) 8588 .add(predOps(ARMCC::AL)); 8589 } 8590 8591 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8592 .addMBB(TrapBB) 8593 .addImm(ARMCC::HI) 8594 .addReg(ARM::CPSR); 8595 8596 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8597 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8598 .addReg(ARM::CPSR, RegState::Define) 8599 .addReg(NewVReg1) 8600 .addImm(2) 8601 .add(predOps(ARMCC::AL)); 8602 8603 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8604 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8605 .addJumpTableIndex(MJTI) 8606 .add(predOps(ARMCC::AL)); 8607 8608 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8609 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8610 .addReg(ARM::CPSR, RegState::Define) 8611 .addReg(NewVReg2, RegState::Kill) 8612 .addReg(NewVReg3) 8613 .add(predOps(ARMCC::AL)); 8614 8615 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8616 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8617 8618 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8619 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8620 .addReg(NewVReg4, RegState::Kill) 8621 .addImm(0) 8622 .addMemOperand(JTMMOLd) 8623 .add(predOps(ARMCC::AL)); 8624 8625 unsigned NewVReg6 = NewVReg5; 8626 if (IsPositionIndependent) { 8627 NewVReg6 = MRI->createVirtualRegister(TRC); 8628 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8629 .addReg(ARM::CPSR, RegState::Define) 8630 .addReg(NewVReg5, RegState::Kill) 8631 .addReg(NewVReg3) 8632 .add(predOps(ARMCC::AL)); 8633 } 8634 8635 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8636 .addReg(NewVReg6, RegState::Kill) 8637 .addJumpTableIndex(MJTI); 8638 } else { 8639 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8640 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8641 .addFrameIndex(FI) 8642 .addImm(4) 8643 .addMemOperand(FIMMOLd) 8644 .add(predOps(ARMCC::AL)); 8645 8646 if (NumLPads < 256) { 8647 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8648 .addReg(NewVReg1) 8649 .addImm(NumLPads) 8650 .add(predOps(ARMCC::AL)); 8651 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8652 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8653 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8654 .addImm(NumLPads & 0xFFFF) 8655 .add(predOps(ARMCC::AL)); 8656 8657 unsigned VReg2 = VReg1; 8658 if ((NumLPads & 0xFFFF0000) != 0) { 8659 VReg2 = MRI->createVirtualRegister(TRC); 8660 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8661 .addReg(VReg1) 8662 .addImm(NumLPads >> 16) 8663 .add(predOps(ARMCC::AL)); 8664 } 8665 8666 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8667 .addReg(NewVReg1) 8668 .addReg(VReg2) 8669 .add(predOps(ARMCC::AL)); 8670 } else { 8671 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8672 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8673 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8674 8675 // MachineConstantPool wants an explicit alignment. 8676 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8677 if (Align == 0) 8678 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8679 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8680 8681 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8682 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8683 .addReg(VReg1, RegState::Define) 8684 .addConstantPoolIndex(Idx) 8685 .addImm(0) 8686 .add(predOps(ARMCC::AL)); 8687 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8688 .addReg(NewVReg1) 8689 .addReg(VReg1, RegState::Kill) 8690 .add(predOps(ARMCC::AL)); 8691 } 8692 8693 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8694 .addMBB(TrapBB) 8695 .addImm(ARMCC::HI) 8696 .addReg(ARM::CPSR); 8697 8698 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8699 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8700 .addReg(NewVReg1) 8701 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8702 .add(predOps(ARMCC::AL)) 8703 .add(condCodeOp()); 8704 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8705 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8706 .addJumpTableIndex(MJTI) 8707 .add(predOps(ARMCC::AL)); 8708 8709 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8710 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8711 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8712 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8713 .addReg(NewVReg3, RegState::Kill) 8714 .addReg(NewVReg4) 8715 .addImm(0) 8716 .addMemOperand(JTMMOLd) 8717 .add(predOps(ARMCC::AL)); 8718 8719 if (IsPositionIndependent) { 8720 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8721 .addReg(NewVReg5, RegState::Kill) 8722 .addReg(NewVReg4) 8723 .addJumpTableIndex(MJTI); 8724 } else { 8725 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8726 .addReg(NewVReg5, RegState::Kill) 8727 .addJumpTableIndex(MJTI); 8728 } 8729 } 8730 8731 // Add the jump table entries as successors to the MBB. 8732 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8733 for (std::vector<MachineBasicBlock*>::iterator 8734 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8735 MachineBasicBlock *CurMBB = *I; 8736 if (SeenMBBs.insert(CurMBB).second) 8737 DispContBB->addSuccessor(CurMBB); 8738 } 8739 8740 // N.B. the order the invoke BBs are processed in doesn't matter here. 8741 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8742 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8743 for (MachineBasicBlock *BB : InvokeBBs) { 8744 8745 // Remove the landing pad successor from the invoke block and replace it 8746 // with the new dispatch block. 8747 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8748 BB->succ_end()); 8749 while (!Successors.empty()) { 8750 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8751 if (SMBB->isEHPad()) { 8752 BB->removeSuccessor(SMBB); 8753 MBBLPads.push_back(SMBB); 8754 } 8755 } 8756 8757 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8758 BB->normalizeSuccProbs(); 8759 8760 // Find the invoke call and mark all of the callee-saved registers as 8761 // 'implicit defined' so that they're spilled. This prevents code from 8762 // moving instructions to before the EH block, where they will never be 8763 // executed. 8764 for (MachineBasicBlock::reverse_iterator 8765 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8766 if (!II->isCall()) continue; 8767 8768 DenseMap<unsigned, bool> DefRegs; 8769 for (MachineInstr::mop_iterator 8770 OI = II->operands_begin(), OE = II->operands_end(); 8771 OI != OE; ++OI) { 8772 if (!OI->isReg()) continue; 8773 DefRegs[OI->getReg()] = true; 8774 } 8775 8776 MachineInstrBuilder MIB(*MF, &*II); 8777 8778 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8779 unsigned Reg = SavedRegs[i]; 8780 if (Subtarget->isThumb2() && 8781 !ARM::tGPRRegClass.contains(Reg) && 8782 !ARM::hGPRRegClass.contains(Reg)) 8783 continue; 8784 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8785 continue; 8786 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8787 continue; 8788 if (!DefRegs[Reg]) 8789 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8790 } 8791 8792 break; 8793 } 8794 } 8795 8796 // Mark all former landing pads as non-landing pads. The dispatch is the only 8797 // landing pad now. 8798 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8799 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8800 (*I)->setIsEHPad(false); 8801 8802 // The instruction is gone now. 8803 MI.eraseFromParent(); 8804 } 8805 8806 static 8807 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8808 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8809 E = MBB->succ_end(); I != E; ++I) 8810 if (*I != Succ) 8811 return *I; 8812 llvm_unreachable("Expecting a BB with two successors!"); 8813 } 8814 8815 /// Return the load opcode for a given load size. If load size >= 8, 8816 /// neon opcode will be returned. 8817 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8818 if (LdSize >= 8) 8819 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8820 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8821 if (IsThumb1) 8822 return LdSize == 4 ? ARM::tLDRi 8823 : LdSize == 2 ? ARM::tLDRHi 8824 : LdSize == 1 ? ARM::tLDRBi : 0; 8825 if (IsThumb2) 8826 return LdSize == 4 ? ARM::t2LDR_POST 8827 : LdSize == 2 ? ARM::t2LDRH_POST 8828 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8829 return LdSize == 4 ? ARM::LDR_POST_IMM 8830 : LdSize == 2 ? ARM::LDRH_POST 8831 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8832 } 8833 8834 /// Return the store opcode for a given store size. If store size >= 8, 8835 /// neon opcode will be returned. 8836 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8837 if (StSize >= 8) 8838 return StSize == 16 ? ARM::VST1q32wb_fixed 8839 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8840 if (IsThumb1) 8841 return StSize == 4 ? ARM::tSTRi 8842 : StSize == 2 ? ARM::tSTRHi 8843 : StSize == 1 ? ARM::tSTRBi : 0; 8844 if (IsThumb2) 8845 return StSize == 4 ? ARM::t2STR_POST 8846 : StSize == 2 ? ARM::t2STRH_POST 8847 : StSize == 1 ? ARM::t2STRB_POST : 0; 8848 return StSize == 4 ? ARM::STR_POST_IMM 8849 : StSize == 2 ? ARM::STRH_POST 8850 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8851 } 8852 8853 /// Emit a post-increment load operation with given size. The instructions 8854 /// will be added to BB at Pos. 8855 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8856 const TargetInstrInfo *TII, const DebugLoc &dl, 8857 unsigned LdSize, unsigned Data, unsigned AddrIn, 8858 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8859 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8860 assert(LdOpc != 0 && "Should have a load opcode"); 8861 if (LdSize >= 8) { 8862 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8863 .addReg(AddrOut, RegState::Define) 8864 .addReg(AddrIn) 8865 .addImm(0) 8866 .add(predOps(ARMCC::AL)); 8867 } else if (IsThumb1) { 8868 // load + update AddrIn 8869 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8870 .addReg(AddrIn) 8871 .addImm(0) 8872 .add(predOps(ARMCC::AL)); 8873 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8874 .add(t1CondCodeOp()) 8875 .addReg(AddrIn) 8876 .addImm(LdSize) 8877 .add(predOps(ARMCC::AL)); 8878 } else if (IsThumb2) { 8879 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8880 .addReg(AddrOut, RegState::Define) 8881 .addReg(AddrIn) 8882 .addImm(LdSize) 8883 .add(predOps(ARMCC::AL)); 8884 } else { // arm 8885 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8886 .addReg(AddrOut, RegState::Define) 8887 .addReg(AddrIn) 8888 .addReg(0) 8889 .addImm(LdSize) 8890 .add(predOps(ARMCC::AL)); 8891 } 8892 } 8893 8894 /// Emit a post-increment store operation with given size. The instructions 8895 /// will be added to BB at Pos. 8896 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8897 const TargetInstrInfo *TII, const DebugLoc &dl, 8898 unsigned StSize, unsigned Data, unsigned AddrIn, 8899 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8900 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8901 assert(StOpc != 0 && "Should have a store opcode"); 8902 if (StSize >= 8) { 8903 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8904 .addReg(AddrIn) 8905 .addImm(0) 8906 .addReg(Data) 8907 .add(predOps(ARMCC::AL)); 8908 } else if (IsThumb1) { 8909 // store + update AddrIn 8910 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8911 .addReg(Data) 8912 .addReg(AddrIn) 8913 .addImm(0) 8914 .add(predOps(ARMCC::AL)); 8915 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8916 .add(t1CondCodeOp()) 8917 .addReg(AddrIn) 8918 .addImm(StSize) 8919 .add(predOps(ARMCC::AL)); 8920 } else if (IsThumb2) { 8921 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8922 .addReg(Data) 8923 .addReg(AddrIn) 8924 .addImm(StSize) 8925 .add(predOps(ARMCC::AL)); 8926 } else { // arm 8927 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8928 .addReg(Data) 8929 .addReg(AddrIn) 8930 .addReg(0) 8931 .addImm(StSize) 8932 .add(predOps(ARMCC::AL)); 8933 } 8934 } 8935 8936 MachineBasicBlock * 8937 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8938 MachineBasicBlock *BB) const { 8939 // This pseudo instruction has 3 operands: dst, src, size 8940 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8941 // Otherwise, we will generate unrolled scalar copies. 8942 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8943 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8944 MachineFunction::iterator It = ++BB->getIterator(); 8945 8946 unsigned dest = MI.getOperand(0).getReg(); 8947 unsigned src = MI.getOperand(1).getReg(); 8948 unsigned SizeVal = MI.getOperand(2).getImm(); 8949 unsigned Align = MI.getOperand(3).getImm(); 8950 DebugLoc dl = MI.getDebugLoc(); 8951 8952 MachineFunction *MF = BB->getParent(); 8953 MachineRegisterInfo &MRI = MF->getRegInfo(); 8954 unsigned UnitSize = 0; 8955 const TargetRegisterClass *TRC = nullptr; 8956 const TargetRegisterClass *VecTRC = nullptr; 8957 8958 bool IsThumb1 = Subtarget->isThumb1Only(); 8959 bool IsThumb2 = Subtarget->isThumb2(); 8960 bool IsThumb = Subtarget->isThumb(); 8961 8962 if (Align & 1) { 8963 UnitSize = 1; 8964 } else if (Align & 2) { 8965 UnitSize = 2; 8966 } else { 8967 // Check whether we can use NEON instructions. 8968 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 8969 Subtarget->hasNEON()) { 8970 if ((Align % 16 == 0) && SizeVal >= 16) 8971 UnitSize = 16; 8972 else if ((Align % 8 == 0) && SizeVal >= 8) 8973 UnitSize = 8; 8974 } 8975 // Can't use NEON instructions. 8976 if (UnitSize == 0) 8977 UnitSize = 4; 8978 } 8979 8980 // Select the correct opcode and register class for unit size load/store 8981 bool IsNeon = UnitSize >= 8; 8982 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8983 if (IsNeon) 8984 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8985 : UnitSize == 8 ? &ARM::DPRRegClass 8986 : nullptr; 8987 8988 unsigned BytesLeft = SizeVal % UnitSize; 8989 unsigned LoopSize = SizeVal - BytesLeft; 8990 8991 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8992 // Use LDR and STR to copy. 8993 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8994 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8995 unsigned srcIn = src; 8996 unsigned destIn = dest; 8997 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8998 unsigned srcOut = MRI.createVirtualRegister(TRC); 8999 unsigned destOut = MRI.createVirtualRegister(TRC); 9000 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9001 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 9002 IsThumb1, IsThumb2); 9003 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 9004 IsThumb1, IsThumb2); 9005 srcIn = srcOut; 9006 destIn = destOut; 9007 } 9008 9009 // Handle the leftover bytes with LDRB and STRB. 9010 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 9011 // [destOut] = STRB_POST(scratch, destIn, 1) 9012 for (unsigned i = 0; i < BytesLeft; i++) { 9013 unsigned srcOut = MRI.createVirtualRegister(TRC); 9014 unsigned destOut = MRI.createVirtualRegister(TRC); 9015 unsigned scratch = MRI.createVirtualRegister(TRC); 9016 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 9017 IsThumb1, IsThumb2); 9018 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 9019 IsThumb1, IsThumb2); 9020 srcIn = srcOut; 9021 destIn = destOut; 9022 } 9023 MI.eraseFromParent(); // The instruction is gone now. 9024 return BB; 9025 } 9026 9027 // Expand the pseudo op to a loop. 9028 // thisMBB: 9029 // ... 9030 // movw varEnd, # --> with thumb2 9031 // movt varEnd, # 9032 // ldrcp varEnd, idx --> without thumb2 9033 // fallthrough --> loopMBB 9034 // loopMBB: 9035 // PHI varPhi, varEnd, varLoop 9036 // PHI srcPhi, src, srcLoop 9037 // PHI destPhi, dst, destLoop 9038 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9039 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 9040 // subs varLoop, varPhi, #UnitSize 9041 // bne loopMBB 9042 // fallthrough --> exitMBB 9043 // exitMBB: 9044 // epilogue to handle left-over bytes 9045 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9046 // [destOut] = STRB_POST(scratch, destLoop, 1) 9047 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9048 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9049 MF->insert(It, loopMBB); 9050 MF->insert(It, exitMBB); 9051 9052 // Transfer the remainder of BB and its successor edges to exitMBB. 9053 exitMBB->splice(exitMBB->begin(), BB, 9054 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9055 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9056 9057 // Load an immediate to varEnd. 9058 unsigned varEnd = MRI.createVirtualRegister(TRC); 9059 if (Subtarget->useMovt(*MF)) { 9060 unsigned Vtmp = varEnd; 9061 if ((LoopSize & 0xFFFF0000) != 0) 9062 Vtmp = MRI.createVirtualRegister(TRC); 9063 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 9064 .addImm(LoopSize & 0xFFFF) 9065 .add(predOps(ARMCC::AL)); 9066 9067 if ((LoopSize & 0xFFFF0000) != 0) 9068 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 9069 .addReg(Vtmp) 9070 .addImm(LoopSize >> 16) 9071 .add(predOps(ARMCC::AL)); 9072 } else { 9073 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9074 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9075 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 9076 9077 // MachineConstantPool wants an explicit alignment. 9078 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9079 if (Align == 0) 9080 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9081 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9082 9083 if (IsThumb) 9084 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9085 .addReg(varEnd, RegState::Define) 9086 .addConstantPoolIndex(Idx) 9087 .add(predOps(ARMCC::AL)); 9088 else 9089 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9090 .addReg(varEnd, RegState::Define) 9091 .addConstantPoolIndex(Idx) 9092 .addImm(0) 9093 .add(predOps(ARMCC::AL)); 9094 } 9095 BB->addSuccessor(loopMBB); 9096 9097 // Generate the loop body: 9098 // varPhi = PHI(varLoop, varEnd) 9099 // srcPhi = PHI(srcLoop, src) 9100 // destPhi = PHI(destLoop, dst) 9101 MachineBasicBlock *entryBB = BB; 9102 BB = loopMBB; 9103 unsigned varLoop = MRI.createVirtualRegister(TRC); 9104 unsigned varPhi = MRI.createVirtualRegister(TRC); 9105 unsigned srcLoop = MRI.createVirtualRegister(TRC); 9106 unsigned srcPhi = MRI.createVirtualRegister(TRC); 9107 unsigned destLoop = MRI.createVirtualRegister(TRC); 9108 unsigned destPhi = MRI.createVirtualRegister(TRC); 9109 9110 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9111 .addReg(varLoop).addMBB(loopMBB) 9112 .addReg(varEnd).addMBB(entryBB); 9113 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9114 .addReg(srcLoop).addMBB(loopMBB) 9115 .addReg(src).addMBB(entryBB); 9116 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9117 .addReg(destLoop).addMBB(loopMBB) 9118 .addReg(dest).addMBB(entryBB); 9119 9120 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9121 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9122 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9123 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9124 IsThumb1, IsThumb2); 9125 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9126 IsThumb1, IsThumb2); 9127 9128 // Decrement loop variable by UnitSize. 9129 if (IsThumb1) { 9130 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9131 .add(t1CondCodeOp()) 9132 .addReg(varPhi) 9133 .addImm(UnitSize) 9134 .add(predOps(ARMCC::AL)); 9135 } else { 9136 MachineInstrBuilder MIB = 9137 BuildMI(*BB, BB->end(), dl, 9138 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9139 MIB.addReg(varPhi) 9140 .addImm(UnitSize) 9141 .add(predOps(ARMCC::AL)) 9142 .add(condCodeOp()); 9143 MIB->getOperand(5).setReg(ARM::CPSR); 9144 MIB->getOperand(5).setIsDef(true); 9145 } 9146 BuildMI(*BB, BB->end(), dl, 9147 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9148 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9149 9150 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9151 BB->addSuccessor(loopMBB); 9152 BB->addSuccessor(exitMBB); 9153 9154 // Add epilogue to handle BytesLeft. 9155 BB = exitMBB; 9156 auto StartOfExit = exitMBB->begin(); 9157 9158 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9159 // [destOut] = STRB_POST(scratch, destLoop, 1) 9160 unsigned srcIn = srcLoop; 9161 unsigned destIn = destLoop; 9162 for (unsigned i = 0; i < BytesLeft; i++) { 9163 unsigned srcOut = MRI.createVirtualRegister(TRC); 9164 unsigned destOut = MRI.createVirtualRegister(TRC); 9165 unsigned scratch = MRI.createVirtualRegister(TRC); 9166 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9167 IsThumb1, IsThumb2); 9168 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9169 IsThumb1, IsThumb2); 9170 srcIn = srcOut; 9171 destIn = destOut; 9172 } 9173 9174 MI.eraseFromParent(); // The instruction is gone now. 9175 return BB; 9176 } 9177 9178 MachineBasicBlock * 9179 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9180 MachineBasicBlock *MBB) const { 9181 const TargetMachine &TM = getTargetMachine(); 9182 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9183 DebugLoc DL = MI.getDebugLoc(); 9184 9185 assert(Subtarget->isTargetWindows() && 9186 "__chkstk is only supported on Windows"); 9187 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9188 9189 // __chkstk takes the number of words to allocate on the stack in R4, and 9190 // returns the stack adjustment in number of bytes in R4. This will not 9191 // clober any other registers (other than the obvious lr). 9192 // 9193 // Although, technically, IP should be considered a register which may be 9194 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9195 // thumb-2 environment, so there is no interworking required. As a result, we 9196 // do not expect a veneer to be emitted by the linker, clobbering IP. 9197 // 9198 // Each module receives its own copy of __chkstk, so no import thunk is 9199 // required, again, ensuring that IP is not clobbered. 9200 // 9201 // Finally, although some linkers may theoretically provide a trampoline for 9202 // out of range calls (which is quite common due to a 32M range limitation of 9203 // branches for Thumb), we can generate the long-call version via 9204 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9205 // IP. 9206 9207 switch (TM.getCodeModel()) { 9208 case CodeModel::Small: 9209 case CodeModel::Medium: 9210 case CodeModel::Kernel: 9211 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9212 .add(predOps(ARMCC::AL)) 9213 .addExternalSymbol("__chkstk") 9214 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9215 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9216 .addReg(ARM::R12, 9217 RegState::Implicit | RegState::Define | RegState::Dead) 9218 .addReg(ARM::CPSR, 9219 RegState::Implicit | RegState::Define | RegState::Dead); 9220 break; 9221 case CodeModel::Large: { 9222 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9223 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9224 9225 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 9226 .addExternalSymbol("__chkstk"); 9227 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 9228 .add(predOps(ARMCC::AL)) 9229 .addReg(Reg, RegState::Kill) 9230 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9231 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9232 .addReg(ARM::R12, 9233 RegState::Implicit | RegState::Define | RegState::Dead) 9234 .addReg(ARM::CPSR, 9235 RegState::Implicit | RegState::Define | RegState::Dead); 9236 break; 9237 } 9238 } 9239 9240 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9241 .addReg(ARM::SP, RegState::Kill) 9242 .addReg(ARM::R4, RegState::Kill) 9243 .setMIFlags(MachineInstr::FrameSetup) 9244 .add(predOps(ARMCC::AL)) 9245 .add(condCodeOp()); 9246 9247 MI.eraseFromParent(); 9248 return MBB; 9249 } 9250 9251 MachineBasicBlock * 9252 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9253 MachineBasicBlock *MBB) const { 9254 DebugLoc DL = MI.getDebugLoc(); 9255 MachineFunction *MF = MBB->getParent(); 9256 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9257 9258 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9259 MF->insert(++MBB->getIterator(), ContBB); 9260 ContBB->splice(ContBB->begin(), MBB, 9261 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9262 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9263 MBB->addSuccessor(ContBB); 9264 9265 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9266 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9267 MF->push_back(TrapBB); 9268 MBB->addSuccessor(TrapBB); 9269 9270 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9271 .addReg(MI.getOperand(0).getReg()) 9272 .addImm(0) 9273 .add(predOps(ARMCC::AL)); 9274 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 9275 .addMBB(TrapBB) 9276 .addImm(ARMCC::EQ) 9277 .addReg(ARM::CPSR); 9278 9279 MI.eraseFromParent(); 9280 return ContBB; 9281 } 9282 9283 MachineBasicBlock * 9284 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9285 MachineBasicBlock *BB) const { 9286 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9287 DebugLoc dl = MI.getDebugLoc(); 9288 bool isThumb2 = Subtarget->isThumb2(); 9289 switch (MI.getOpcode()) { 9290 default: { 9291 MI.print(errs()); 9292 llvm_unreachable("Unexpected instr type to insert"); 9293 } 9294 9295 // Thumb1 post-indexed loads are really just single-register LDMs. 9296 case ARM::tLDR_postidx: { 9297 MachineOperand Def(MI.getOperand(1)); 9298 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 9299 .add(Def) // Rn_wb 9300 .add(MI.getOperand(2)) // Rn 9301 .add(MI.getOperand(3)) // PredImm 9302 .add(MI.getOperand(4)) // PredReg 9303 .add(MI.getOperand(0)); // Rt 9304 MI.eraseFromParent(); 9305 return BB; 9306 } 9307 9308 // The Thumb2 pre-indexed stores have the same MI operands, they just 9309 // define them differently in the .td files from the isel patterns, so 9310 // they need pseudos. 9311 case ARM::t2STR_preidx: 9312 MI.setDesc(TII->get(ARM::t2STR_PRE)); 9313 return BB; 9314 case ARM::t2STRB_preidx: 9315 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 9316 return BB; 9317 case ARM::t2STRH_preidx: 9318 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9319 return BB; 9320 9321 case ARM::STRi_preidx: 9322 case ARM::STRBi_preidx: { 9323 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9324 : ARM::STRB_PRE_IMM; 9325 // Decode the offset. 9326 unsigned Offset = MI.getOperand(4).getImm(); 9327 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9328 Offset = ARM_AM::getAM2Offset(Offset); 9329 if (isSub) 9330 Offset = -Offset; 9331 9332 MachineMemOperand *MMO = *MI.memoperands_begin(); 9333 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9334 .add(MI.getOperand(0)) // Rn_wb 9335 .add(MI.getOperand(1)) // Rt 9336 .add(MI.getOperand(2)) // Rn 9337 .addImm(Offset) // offset (skip GPR==zero_reg) 9338 .add(MI.getOperand(5)) // pred 9339 .add(MI.getOperand(6)) 9340 .addMemOperand(MMO); 9341 MI.eraseFromParent(); 9342 return BB; 9343 } 9344 case ARM::STRr_preidx: 9345 case ARM::STRBr_preidx: 9346 case ARM::STRH_preidx: { 9347 unsigned NewOpc; 9348 switch (MI.getOpcode()) { 9349 default: llvm_unreachable("unexpected opcode!"); 9350 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9351 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9352 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9353 } 9354 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9355 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9356 MIB.add(MI.getOperand(i)); 9357 MI.eraseFromParent(); 9358 return BB; 9359 } 9360 9361 case ARM::tMOVCCr_pseudo: { 9362 // To "insert" a SELECT_CC instruction, we actually have to insert the 9363 // diamond control-flow pattern. The incoming instruction knows the 9364 // destination vreg to set, the condition code register to branch on, the 9365 // true/false values to select between, and a branch opcode to use. 9366 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9367 MachineFunction::iterator It = ++BB->getIterator(); 9368 9369 // thisMBB: 9370 // ... 9371 // TrueVal = ... 9372 // cmpTY ccX, r1, r2 9373 // bCC copy1MBB 9374 // fallthrough --> copy0MBB 9375 MachineBasicBlock *thisMBB = BB; 9376 MachineFunction *F = BB->getParent(); 9377 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9378 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9379 F->insert(It, copy0MBB); 9380 F->insert(It, sinkMBB); 9381 9382 // Transfer the remainder of BB and its successor edges to sinkMBB. 9383 sinkMBB->splice(sinkMBB->begin(), BB, 9384 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9385 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9386 9387 BB->addSuccessor(copy0MBB); 9388 BB->addSuccessor(sinkMBB); 9389 9390 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9391 .addMBB(sinkMBB) 9392 .addImm(MI.getOperand(3).getImm()) 9393 .addReg(MI.getOperand(4).getReg()); 9394 9395 // copy0MBB: 9396 // %FalseValue = ... 9397 // # fallthrough to sinkMBB 9398 BB = copy0MBB; 9399 9400 // Update machine-CFG edges 9401 BB->addSuccessor(sinkMBB); 9402 9403 // sinkMBB: 9404 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9405 // ... 9406 BB = sinkMBB; 9407 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9408 .addReg(MI.getOperand(1).getReg()) 9409 .addMBB(copy0MBB) 9410 .addReg(MI.getOperand(2).getReg()) 9411 .addMBB(thisMBB); 9412 9413 MI.eraseFromParent(); // The pseudo instruction is gone now. 9414 return BB; 9415 } 9416 9417 case ARM::BCCi64: 9418 case ARM::BCCZi64: { 9419 // If there is an unconditional branch to the other successor, remove it. 9420 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9421 9422 // Compare both parts that make up the double comparison separately for 9423 // equality. 9424 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9425 9426 unsigned LHS1 = MI.getOperand(1).getReg(); 9427 unsigned LHS2 = MI.getOperand(2).getReg(); 9428 if (RHSisZero) { 9429 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9430 .addReg(LHS1) 9431 .addImm(0) 9432 .add(predOps(ARMCC::AL)); 9433 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9434 .addReg(LHS2).addImm(0) 9435 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9436 } else { 9437 unsigned RHS1 = MI.getOperand(3).getReg(); 9438 unsigned RHS2 = MI.getOperand(4).getReg(); 9439 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9440 .addReg(LHS1) 9441 .addReg(RHS1) 9442 .add(predOps(ARMCC::AL)); 9443 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9444 .addReg(LHS2).addReg(RHS2) 9445 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9446 } 9447 9448 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9449 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9450 if (MI.getOperand(0).getImm() == ARMCC::NE) 9451 std::swap(destMBB, exitMBB); 9452 9453 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9454 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9455 if (isThumb2) 9456 BuildMI(BB, dl, TII->get(ARM::t2B)) 9457 .addMBB(exitMBB) 9458 .add(predOps(ARMCC::AL)); 9459 else 9460 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9461 9462 MI.eraseFromParent(); // The pseudo instruction is gone now. 9463 return BB; 9464 } 9465 9466 case ARM::Int_eh_sjlj_setjmp: 9467 case ARM::Int_eh_sjlj_setjmp_nofp: 9468 case ARM::tInt_eh_sjlj_setjmp: 9469 case ARM::t2Int_eh_sjlj_setjmp: 9470 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9471 return BB; 9472 9473 case ARM::Int_eh_sjlj_setup_dispatch: 9474 EmitSjLjDispatchBlock(MI, BB); 9475 return BB; 9476 9477 case ARM::ABS: 9478 case ARM::t2ABS: { 9479 // To insert an ABS instruction, we have to insert the 9480 // diamond control-flow pattern. The incoming instruction knows the 9481 // source vreg to test against 0, the destination vreg to set, 9482 // the condition code register to branch on, the 9483 // true/false values to select between, and a branch opcode to use. 9484 // It transforms 9485 // V1 = ABS V0 9486 // into 9487 // V2 = MOVS V0 9488 // BCC (branch to SinkBB if V0 >= 0) 9489 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9490 // SinkBB: V1 = PHI(V2, V3) 9491 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9492 MachineFunction::iterator BBI = ++BB->getIterator(); 9493 MachineFunction *Fn = BB->getParent(); 9494 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9495 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9496 Fn->insert(BBI, RSBBB); 9497 Fn->insert(BBI, SinkBB); 9498 9499 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9500 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9501 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9502 bool isThumb2 = Subtarget->isThumb2(); 9503 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9504 // In Thumb mode S must not be specified if source register is the SP or 9505 // PC and if destination register is the SP, so restrict register class 9506 unsigned NewRsbDstReg = 9507 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9508 9509 // Transfer the remainder of BB and its successor edges to sinkMBB. 9510 SinkBB->splice(SinkBB->begin(), BB, 9511 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9512 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9513 9514 BB->addSuccessor(RSBBB); 9515 BB->addSuccessor(SinkBB); 9516 9517 // fall through to SinkMBB 9518 RSBBB->addSuccessor(SinkBB); 9519 9520 // insert a cmp at the end of BB 9521 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9522 .addReg(ABSSrcReg) 9523 .addImm(0) 9524 .add(predOps(ARMCC::AL)); 9525 9526 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9527 BuildMI(BB, dl, 9528 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9529 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9530 9531 // insert rsbri in RSBBB 9532 // Note: BCC and rsbri will be converted into predicated rsbmi 9533 // by if-conversion pass 9534 BuildMI(*RSBBB, RSBBB->begin(), dl, 9535 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9536 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9537 .addImm(0) 9538 .add(predOps(ARMCC::AL)) 9539 .add(condCodeOp()); 9540 9541 // insert PHI in SinkBB, 9542 // reuse ABSDstReg to not change uses of ABS instruction 9543 BuildMI(*SinkBB, SinkBB->begin(), dl, 9544 TII->get(ARM::PHI), ABSDstReg) 9545 .addReg(NewRsbDstReg).addMBB(RSBBB) 9546 .addReg(ABSSrcReg).addMBB(BB); 9547 9548 // remove ABS instruction 9549 MI.eraseFromParent(); 9550 9551 // return last added BB 9552 return SinkBB; 9553 } 9554 case ARM::COPY_STRUCT_BYVAL_I32: 9555 ++NumLoopByVals; 9556 return EmitStructByval(MI, BB); 9557 case ARM::WIN__CHKSTK: 9558 return EmitLowered__chkstk(MI, BB); 9559 case ARM::WIN__DBZCHK: 9560 return EmitLowered__dbzchk(MI, BB); 9561 } 9562 } 9563 9564 /// Attaches vregs to MEMCPY that it will use as scratch registers 9565 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9566 /// instead of as a custom inserter because we need the use list from the SDNode. 9567 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9568 MachineInstr &MI, const SDNode *Node) { 9569 bool isThumb1 = Subtarget->isThumb1Only(); 9570 9571 DebugLoc DL = MI.getDebugLoc(); 9572 MachineFunction *MF = MI.getParent()->getParent(); 9573 MachineRegisterInfo &MRI = MF->getRegInfo(); 9574 MachineInstrBuilder MIB(*MF, MI); 9575 9576 // If the new dst/src is unused mark it as dead. 9577 if (!Node->hasAnyUseOfValue(0)) { 9578 MI.getOperand(0).setIsDead(true); 9579 } 9580 if (!Node->hasAnyUseOfValue(1)) { 9581 MI.getOperand(1).setIsDead(true); 9582 } 9583 9584 // The MEMCPY both defines and kills the scratch registers. 9585 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9586 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9587 : &ARM::GPRRegClass); 9588 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9589 } 9590 } 9591 9592 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9593 SDNode *Node) const { 9594 if (MI.getOpcode() == ARM::MEMCPY) { 9595 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9596 return; 9597 } 9598 9599 const MCInstrDesc *MCID = &MI.getDesc(); 9600 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9601 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9602 // operand is still set to noreg. If needed, set the optional operand's 9603 // register to CPSR, and remove the redundant implicit def. 9604 // 9605 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 9606 9607 // Rename pseudo opcodes. 9608 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9609 unsigned ccOutIdx; 9610 if (NewOpc) { 9611 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9612 MCID = &TII->get(NewOpc); 9613 9614 assert(MCID->getNumOperands() == 9615 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9616 && "converted opcode should be the same except for cc_out" 9617 " (and, on Thumb1, pred)"); 9618 9619 MI.setDesc(*MCID); 9620 9621 // Add the optional cc_out operand 9622 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9623 9624 // On Thumb1, move all input operands to the end, then add the predicate 9625 if (Subtarget->isThumb1Only()) { 9626 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9627 MI.addOperand(MI.getOperand(1)); 9628 MI.RemoveOperand(1); 9629 } 9630 9631 // Restore the ties 9632 for (unsigned i = MI.getNumOperands(); i--;) { 9633 const MachineOperand& op = MI.getOperand(i); 9634 if (op.isReg() && op.isUse()) { 9635 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9636 if (DefIdx != -1) 9637 MI.tieOperands(DefIdx, i); 9638 } 9639 } 9640 9641 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9642 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9643 ccOutIdx = 1; 9644 } else 9645 ccOutIdx = MCID->getNumOperands() - 1; 9646 } else 9647 ccOutIdx = MCID->getNumOperands() - 1; 9648 9649 // Any ARM instruction that sets the 's' bit should specify an optional 9650 // "cc_out" operand in the last operand position. 9651 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9652 assert(!NewOpc && "Optional cc_out operand required"); 9653 return; 9654 } 9655 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9656 // since we already have an optional CPSR def. 9657 bool definesCPSR = false; 9658 bool deadCPSR = false; 9659 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9660 ++i) { 9661 const MachineOperand &MO = MI.getOperand(i); 9662 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9663 definesCPSR = true; 9664 if (MO.isDead()) 9665 deadCPSR = true; 9666 MI.RemoveOperand(i); 9667 break; 9668 } 9669 } 9670 if (!definesCPSR) { 9671 assert(!NewOpc && "Optional cc_out operand required"); 9672 return; 9673 } 9674 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9675 if (deadCPSR) { 9676 assert(!MI.getOperand(ccOutIdx).getReg() && 9677 "expect uninitialized optional cc_out operand"); 9678 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9679 if (!Subtarget->isThumb1Only()) 9680 return; 9681 } 9682 9683 // If this instruction was defined with an optional CPSR def and its dag node 9684 // had a live implicit CPSR def, then activate the optional CPSR def. 9685 MachineOperand &MO = MI.getOperand(ccOutIdx); 9686 MO.setReg(ARM::CPSR); 9687 MO.setIsDef(true); 9688 } 9689 9690 //===----------------------------------------------------------------------===// 9691 // ARM Optimization Hooks 9692 //===----------------------------------------------------------------------===// 9693 9694 // Helper function that checks if N is a null or all ones constant. 9695 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9696 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9697 } 9698 9699 // Return true if N is conditionally 0 or all ones. 9700 // Detects these expressions where cc is an i1 value: 9701 // 9702 // (select cc 0, y) [AllOnes=0] 9703 // (select cc y, 0) [AllOnes=0] 9704 // (zext cc) [AllOnes=0] 9705 // (sext cc) [AllOnes=0/1] 9706 // (select cc -1, y) [AllOnes=1] 9707 // (select cc y, -1) [AllOnes=1] 9708 // 9709 // Invert is set when N is the null/all ones constant when CC is false. 9710 // OtherOp is set to the alternative value of N. 9711 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9712 SDValue &CC, bool &Invert, 9713 SDValue &OtherOp, 9714 SelectionDAG &DAG) { 9715 switch (N->getOpcode()) { 9716 default: return false; 9717 case ISD::SELECT: { 9718 CC = N->getOperand(0); 9719 SDValue N1 = N->getOperand(1); 9720 SDValue N2 = N->getOperand(2); 9721 if (isZeroOrAllOnes(N1, AllOnes)) { 9722 Invert = false; 9723 OtherOp = N2; 9724 return true; 9725 } 9726 if (isZeroOrAllOnes(N2, AllOnes)) { 9727 Invert = true; 9728 OtherOp = N1; 9729 return true; 9730 } 9731 return false; 9732 } 9733 case ISD::ZERO_EXTEND: 9734 // (zext cc) can never be the all ones value. 9735 if (AllOnes) 9736 return false; 9737 LLVM_FALLTHROUGH; 9738 case ISD::SIGN_EXTEND: { 9739 SDLoc dl(N); 9740 EVT VT = N->getValueType(0); 9741 CC = N->getOperand(0); 9742 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9743 return false; 9744 Invert = !AllOnes; 9745 if (AllOnes) 9746 // When looking for an AllOnes constant, N is an sext, and the 'other' 9747 // value is 0. 9748 OtherOp = DAG.getConstant(0, dl, VT); 9749 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9750 // When looking for a 0 constant, N can be zext or sext. 9751 OtherOp = DAG.getConstant(1, dl, VT); 9752 else 9753 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9754 VT); 9755 return true; 9756 } 9757 } 9758 } 9759 9760 // Combine a constant select operand into its use: 9761 // 9762 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9763 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9764 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9765 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9766 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9767 // 9768 // The transform is rejected if the select doesn't have a constant operand that 9769 // is null, or all ones when AllOnes is set. 9770 // 9771 // Also recognize sext/zext from i1: 9772 // 9773 // (add (zext cc), x) -> (select cc (add x, 1), x) 9774 // (add (sext cc), x) -> (select cc (add x, -1), x) 9775 // 9776 // These transformations eventually create predicated instructions. 9777 // 9778 // @param N The node to transform. 9779 // @param Slct The N operand that is a select. 9780 // @param OtherOp The other N operand (x above). 9781 // @param DCI Context. 9782 // @param AllOnes Require the select constant to be all ones instead of null. 9783 // @returns The new node, or SDValue() on failure. 9784 static 9785 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9786 TargetLowering::DAGCombinerInfo &DCI, 9787 bool AllOnes = false) { 9788 SelectionDAG &DAG = DCI.DAG; 9789 EVT VT = N->getValueType(0); 9790 SDValue NonConstantVal; 9791 SDValue CCOp; 9792 bool SwapSelectOps; 9793 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9794 NonConstantVal, DAG)) 9795 return SDValue(); 9796 9797 // Slct is now know to be the desired identity constant when CC is true. 9798 SDValue TrueVal = OtherOp; 9799 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9800 OtherOp, NonConstantVal); 9801 // Unless SwapSelectOps says CC should be false. 9802 if (SwapSelectOps) 9803 std::swap(TrueVal, FalseVal); 9804 9805 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9806 CCOp, TrueVal, FalseVal); 9807 } 9808 9809 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9810 static 9811 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9812 TargetLowering::DAGCombinerInfo &DCI) { 9813 SDValue N0 = N->getOperand(0); 9814 SDValue N1 = N->getOperand(1); 9815 if (N0.getNode()->hasOneUse()) 9816 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9817 return Result; 9818 if (N1.getNode()->hasOneUse()) 9819 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9820 return Result; 9821 return SDValue(); 9822 } 9823 9824 static bool IsVUZPShuffleNode(SDNode *N) { 9825 // VUZP shuffle node. 9826 if (N->getOpcode() == ARMISD::VUZP) 9827 return true; 9828 9829 // "VUZP" on i32 is an alias for VTRN. 9830 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9831 return true; 9832 9833 return false; 9834 } 9835 9836 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9837 TargetLowering::DAGCombinerInfo &DCI, 9838 const ARMSubtarget *Subtarget) { 9839 // Look for ADD(VUZP.0, VUZP.1). 9840 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9841 N0 == N1) 9842 return SDValue(); 9843 9844 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9845 if (!N->getValueType(0).is64BitVector()) 9846 return SDValue(); 9847 9848 // Generate vpadd. 9849 SelectionDAG &DAG = DCI.DAG; 9850 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9851 SDLoc dl(N); 9852 SDNode *Unzip = N0.getNode(); 9853 EVT VT = N->getValueType(0); 9854 9855 SmallVector<SDValue, 8> Ops; 9856 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9857 TLI.getPointerTy(DAG.getDataLayout()))); 9858 Ops.push_back(Unzip->getOperand(0)); 9859 Ops.push_back(Unzip->getOperand(1)); 9860 9861 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9862 } 9863 9864 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9865 TargetLowering::DAGCombinerInfo &DCI, 9866 const ARMSubtarget *Subtarget) { 9867 // Check for two extended operands. 9868 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9869 N1.getOpcode() == ISD::SIGN_EXTEND) && 9870 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9871 N1.getOpcode() == ISD::ZERO_EXTEND)) 9872 return SDValue(); 9873 9874 SDValue N00 = N0.getOperand(0); 9875 SDValue N10 = N1.getOperand(0); 9876 9877 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9878 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9879 N00 == N10) 9880 return SDValue(); 9881 9882 // We only recognize Q register paddl here; this can't be reached until 9883 // after type legalization. 9884 if (!N00.getValueType().is64BitVector() || 9885 !N0.getValueType().is128BitVector()) 9886 return SDValue(); 9887 9888 // Generate vpaddl. 9889 SelectionDAG &DAG = DCI.DAG; 9890 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9891 SDLoc dl(N); 9892 EVT VT = N->getValueType(0); 9893 9894 SmallVector<SDValue, 8> Ops; 9895 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9896 unsigned Opcode; 9897 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9898 Opcode = Intrinsic::arm_neon_vpaddls; 9899 else 9900 Opcode = Intrinsic::arm_neon_vpaddlu; 9901 Ops.push_back(DAG.getConstant(Opcode, dl, 9902 TLI.getPointerTy(DAG.getDataLayout()))); 9903 EVT ElemTy = N00.getValueType().getVectorElementType(); 9904 unsigned NumElts = VT.getVectorNumElements(); 9905 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9906 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9907 N00.getOperand(0), N00.getOperand(1)); 9908 Ops.push_back(Concat); 9909 9910 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9911 } 9912 9913 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9914 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9915 // much easier to match. 9916 static SDValue 9917 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9918 TargetLowering::DAGCombinerInfo &DCI, 9919 const ARMSubtarget *Subtarget) { 9920 // Only perform optimization if after legalize, and if NEON is available. We 9921 // also expected both operands to be BUILD_VECTORs. 9922 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9923 || N0.getOpcode() != ISD::BUILD_VECTOR 9924 || N1.getOpcode() != ISD::BUILD_VECTOR) 9925 return SDValue(); 9926 9927 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9928 EVT VT = N->getValueType(0); 9929 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9930 return SDValue(); 9931 9932 // Check that the vector operands are of the right form. 9933 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9934 // operands, where N is the size of the formed vector. 9935 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9936 // index such that we have a pair wise add pattern. 9937 9938 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9939 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9940 return SDValue(); 9941 SDValue Vec = N0->getOperand(0)->getOperand(0); 9942 SDNode *V = Vec.getNode(); 9943 unsigned nextIndex = 0; 9944 9945 // For each operands to the ADD which are BUILD_VECTORs, 9946 // check to see if each of their operands are an EXTRACT_VECTOR with 9947 // the same vector and appropriate index. 9948 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9949 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9950 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9951 9952 SDValue ExtVec0 = N0->getOperand(i); 9953 SDValue ExtVec1 = N1->getOperand(i); 9954 9955 // First operand is the vector, verify its the same. 9956 if (V != ExtVec0->getOperand(0).getNode() || 9957 V != ExtVec1->getOperand(0).getNode()) 9958 return SDValue(); 9959 9960 // Second is the constant, verify its correct. 9961 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9962 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9963 9964 // For the constant, we want to see all the even or all the odd. 9965 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9966 || C1->getZExtValue() != nextIndex+1) 9967 return SDValue(); 9968 9969 // Increment index. 9970 nextIndex+=2; 9971 } else 9972 return SDValue(); 9973 } 9974 9975 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 9976 // we're using the entire input vector, otherwise there's a size/legality 9977 // mismatch somewhere. 9978 if (nextIndex != Vec.getValueType().getVectorNumElements() || 9979 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9980 return SDValue(); 9981 9982 // Create VPADDL node. 9983 SelectionDAG &DAG = DCI.DAG; 9984 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9985 9986 SDLoc dl(N); 9987 9988 // Build operand list. 9989 SmallVector<SDValue, 8> Ops; 9990 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9991 TLI.getPointerTy(DAG.getDataLayout()))); 9992 9993 // Input is the vector. 9994 Ops.push_back(Vec); 9995 9996 // Get widened type and narrowed type. 9997 MVT widenType; 9998 unsigned numElem = VT.getVectorNumElements(); 9999 10000 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 10001 switch (inputLaneType.getSimpleVT().SimpleTy) { 10002 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 10003 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 10004 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 10005 default: 10006 llvm_unreachable("Invalid vector element type for padd optimization."); 10007 } 10008 10009 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 10010 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 10011 return DAG.getNode(ExtOp, dl, VT, tmp); 10012 } 10013 10014 static SDValue findMUL_LOHI(SDValue V) { 10015 if (V->getOpcode() == ISD::UMUL_LOHI || 10016 V->getOpcode() == ISD::SMUL_LOHI) 10017 return V; 10018 return SDValue(); 10019 } 10020 10021 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 10022 TargetLowering::DAGCombinerInfo &DCI, 10023 const ARMSubtarget *Subtarget) { 10024 if (Subtarget->isThumb()) { 10025 if (!Subtarget->hasDSP()) 10026 return SDValue(); 10027 } else if (!Subtarget->hasV5TEOps()) 10028 return SDValue(); 10029 10030 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 10031 // accumulates the product into a 64-bit value. The 16-bit values will 10032 // be sign extended somehow or SRA'd into 32-bit values 10033 // (addc (adde (mul 16bit, 16bit), lo), hi) 10034 SDValue Mul = AddcNode->getOperand(0); 10035 SDValue Lo = AddcNode->getOperand(1); 10036 if (Mul.getOpcode() != ISD::MUL) { 10037 Lo = AddcNode->getOperand(0); 10038 Mul = AddcNode->getOperand(1); 10039 if (Mul.getOpcode() != ISD::MUL) 10040 return SDValue(); 10041 } 10042 10043 SDValue SRA = AddeNode->getOperand(0); 10044 SDValue Hi = AddeNode->getOperand(1); 10045 if (SRA.getOpcode() != ISD::SRA) { 10046 SRA = AddeNode->getOperand(1); 10047 Hi = AddeNode->getOperand(0); 10048 if (SRA.getOpcode() != ISD::SRA) 10049 return SDValue(); 10050 } 10051 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 10052 if (Const->getZExtValue() != 31) 10053 return SDValue(); 10054 } else 10055 return SDValue(); 10056 10057 if (SRA.getOperand(0) != Mul) 10058 return SDValue(); 10059 10060 SelectionDAG &DAG = DCI.DAG; 10061 SDLoc dl(AddcNode); 10062 unsigned Opcode = 0; 10063 SDValue Op0; 10064 SDValue Op1; 10065 10066 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 10067 Opcode = ARMISD::SMLALBB; 10068 Op0 = Mul.getOperand(0); 10069 Op1 = Mul.getOperand(1); 10070 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 10071 Opcode = ARMISD::SMLALBT; 10072 Op0 = Mul.getOperand(0); 10073 Op1 = Mul.getOperand(1).getOperand(0); 10074 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10075 Opcode = ARMISD::SMLALTB; 10076 Op0 = Mul.getOperand(0).getOperand(0); 10077 Op1 = Mul.getOperand(1); 10078 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10079 Opcode = ARMISD::SMLALTT; 10080 Op0 = Mul->getOperand(0).getOperand(0); 10081 Op1 = Mul->getOperand(1).getOperand(0); 10082 } 10083 10084 if (!Op0 || !Op1) 10085 return SDValue(); 10086 10087 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10088 Op0, Op1, Lo, Hi); 10089 // Replace the ADDs' nodes uses by the MLA node's values. 10090 SDValue HiMLALResult(SMLAL.getNode(), 1); 10091 SDValue LoMLALResult(SMLAL.getNode(), 0); 10092 10093 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10094 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10095 10096 // Return original node to notify the driver to stop replacing. 10097 SDValue resNode(AddcNode, 0); 10098 return resNode; 10099 } 10100 10101 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10102 TargetLowering::DAGCombinerInfo &DCI, 10103 const ARMSubtarget *Subtarget) { 10104 // Look for multiply add opportunities. 10105 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10106 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10107 // a glue link from the first add to the second add. 10108 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10109 // a S/UMLAL instruction. 10110 // UMUL_LOHI 10111 // / :lo \ :hi 10112 // V \ [no multiline comment] 10113 // loAdd -> ADDC | 10114 // \ :carry / 10115 // V V 10116 // ADDE <- hiAdd 10117 // 10118 // In the special case where only the higher part of a signed result is used 10119 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10120 // a constant with the exact value of 0x80000000, we recognize we are dealing 10121 // with a "rounded multiply and add" (or subtract) and transform it into 10122 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10123 10124 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10125 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10126 "Expect an ADDE or SUBE"); 10127 10128 assert(AddeSubeNode->getNumOperands() == 3 && 10129 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10130 "ADDE node has the wrong inputs"); 10131 10132 // Check that we are chained to the right ADDC or SUBC node. 10133 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10134 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10135 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10136 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10137 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10138 return SDValue(); 10139 10140 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10141 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10142 10143 // Check if the two operands are from the same mul_lohi node. 10144 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10145 return SDValue(); 10146 10147 assert(AddcSubcNode->getNumValues() == 2 && 10148 AddcSubcNode->getValueType(0) == MVT::i32 && 10149 "Expect ADDC with two result values. First: i32"); 10150 10151 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10152 // maybe a SMLAL which multiplies two 16-bit values. 10153 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10154 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10155 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10156 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10157 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10158 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10159 10160 // Check for the triangle shape. 10161 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10162 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10163 10164 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10165 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10166 return SDValue(); 10167 10168 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10169 bool IsLeftOperandMUL = false; 10170 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10171 if (MULOp == SDValue()) 10172 MULOp = findMUL_LOHI(AddeSubeOp1); 10173 else 10174 IsLeftOperandMUL = true; 10175 if (MULOp == SDValue()) 10176 return SDValue(); 10177 10178 // Figure out the right opcode. 10179 unsigned Opc = MULOp->getOpcode(); 10180 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 10181 10182 // Figure out the high and low input values to the MLAL node. 10183 SDValue *HiAddSub = nullptr; 10184 SDValue *LoMul = nullptr; 10185 SDValue *LowAddSub = nullptr; 10186 10187 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 10188 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 10189 return SDValue(); 10190 10191 if (IsLeftOperandMUL) 10192 HiAddSub = &AddeSubeOp1; 10193 else 10194 HiAddSub = &AddeSubeOp0; 10195 10196 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 10197 // whose low result is fed to the ADDC/SUBC we are checking. 10198 10199 if (AddcSubcOp0 == MULOp.getValue(0)) { 10200 LoMul = &AddcSubcOp0; 10201 LowAddSub = &AddcSubcOp1; 10202 } 10203 if (AddcSubcOp1 == MULOp.getValue(0)) { 10204 LoMul = &AddcSubcOp1; 10205 LowAddSub = &AddcSubcOp0; 10206 } 10207 10208 if (!LoMul) 10209 return SDValue(); 10210 10211 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 10212 // the replacement below will create a cycle. 10213 if (AddcSubcNode == HiAddSub->getNode() || 10214 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 10215 return SDValue(); 10216 10217 // Create the merged node. 10218 SelectionDAG &DAG = DCI.DAG; 10219 10220 // Start building operand list. 10221 SmallVector<SDValue, 8> Ops; 10222 Ops.push_back(LoMul->getOperand(0)); 10223 Ops.push_back(LoMul->getOperand(1)); 10224 10225 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 10226 // the case, we must be doing signed multiplication and only use the higher 10227 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 10228 // addition or subtraction with the value of 0x800000. 10229 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 10230 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 10231 LowAddSub->getNode()->getOpcode() == ISD::Constant && 10232 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 10233 0x80000000) { 10234 Ops.push_back(*HiAddSub); 10235 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 10236 FinalOpc = ARMISD::SMMLSR; 10237 } else { 10238 FinalOpc = ARMISD::SMMLAR; 10239 } 10240 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 10241 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 10242 10243 return SDValue(AddeSubeNode, 0); 10244 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 10245 // SMMLS is generated during instruction selection and the rest of this 10246 // function can not handle the case where AddcSubcNode is a SUBC. 10247 return SDValue(); 10248 10249 // Finish building the operand list for {U/S}MLAL 10250 Ops.push_back(*LowAddSub); 10251 Ops.push_back(*HiAddSub); 10252 10253 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 10254 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10255 10256 // Replace the ADDs' nodes uses by the MLA node's values. 10257 SDValue HiMLALResult(MLALNode.getNode(), 1); 10258 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 10259 10260 SDValue LoMLALResult(MLALNode.getNode(), 0); 10261 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 10262 10263 // Return original node to notify the driver to stop replacing. 10264 return SDValue(AddeSubeNode, 0); 10265 } 10266 10267 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 10268 TargetLowering::DAGCombinerInfo &DCI, 10269 const ARMSubtarget *Subtarget) { 10270 // UMAAL is similar to UMLAL except that it adds two unsigned values. 10271 // While trying to combine for the other MLAL nodes, first search for the 10272 // chance to use UMAAL. Check if Addc uses a node which has already 10273 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 10274 // as the addend, and it's handled in PerformUMLALCombine. 10275 10276 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10277 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10278 10279 // Check that we have a glued ADDC node. 10280 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 10281 if (AddcNode->getOpcode() != ARMISD::ADDC) 10282 return SDValue(); 10283 10284 // Find the converted UMAAL or quit if it doesn't exist. 10285 SDNode *UmlalNode = nullptr; 10286 SDValue AddHi; 10287 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 10288 UmlalNode = AddcNode->getOperand(0).getNode(); 10289 AddHi = AddcNode->getOperand(1); 10290 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 10291 UmlalNode = AddcNode->getOperand(1).getNode(); 10292 AddHi = AddcNode->getOperand(0); 10293 } else { 10294 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10295 } 10296 10297 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 10298 // the ADDC as well as Zero. 10299 if (!isNullConstant(UmlalNode->getOperand(3))) 10300 return SDValue(); 10301 10302 if ((isNullConstant(AddeNode->getOperand(0)) && 10303 AddeNode->getOperand(1).getNode() == UmlalNode) || 10304 (AddeNode->getOperand(0).getNode() == UmlalNode && 10305 isNullConstant(AddeNode->getOperand(1)))) { 10306 SelectionDAG &DAG = DCI.DAG; 10307 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 10308 UmlalNode->getOperand(2), AddHi }; 10309 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 10310 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10311 10312 // Replace the ADDs' nodes uses by the UMAAL node's values. 10313 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 10314 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 10315 10316 // Return original node to notify the driver to stop replacing. 10317 return SDValue(AddeNode, 0); 10318 } 10319 return SDValue(); 10320 } 10321 10322 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 10323 const ARMSubtarget *Subtarget) { 10324 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10325 return SDValue(); 10326 10327 // Check that we have a pair of ADDC and ADDE as operands. 10328 // Both addends of the ADDE must be zero. 10329 SDNode* AddcNode = N->getOperand(2).getNode(); 10330 SDNode* AddeNode = N->getOperand(3).getNode(); 10331 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 10332 (AddeNode->getOpcode() == ARMISD::ADDE) && 10333 isNullConstant(AddeNode->getOperand(0)) && 10334 isNullConstant(AddeNode->getOperand(1)) && 10335 (AddeNode->getOperand(2).getNode() == AddcNode)) 10336 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 10337 DAG.getVTList(MVT::i32, MVT::i32), 10338 {N->getOperand(0), N->getOperand(1), 10339 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 10340 else 10341 return SDValue(); 10342 } 10343 10344 static SDValue PerformAddcSubcCombine(SDNode *N, 10345 TargetLowering::DAGCombinerInfo &DCI, 10346 const ARMSubtarget *Subtarget) { 10347 SelectionDAG &DAG(DCI.DAG); 10348 10349 if (N->getOpcode() == ARMISD::SUBC) { 10350 // (SUBC (ADDE 0, 0, C), 1) -> C 10351 SDValue LHS = N->getOperand(0); 10352 SDValue RHS = N->getOperand(1); 10353 if (LHS->getOpcode() == ARMISD::ADDE && 10354 isNullConstant(LHS->getOperand(0)) && 10355 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 10356 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10357 } 10358 } 10359 10360 if (Subtarget->isThumb1Only()) { 10361 SDValue RHS = N->getOperand(1); 10362 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10363 int32_t imm = C->getSExtValue(); 10364 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10365 SDLoc DL(N); 10366 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10367 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10368 : ARMISD::ADDC; 10369 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10370 } 10371 } 10372 } 10373 10374 return SDValue(); 10375 } 10376 10377 static SDValue PerformAddeSubeCombine(SDNode *N, 10378 TargetLowering::DAGCombinerInfo &DCI, 10379 const ARMSubtarget *Subtarget) { 10380 if (Subtarget->isThumb1Only()) { 10381 SelectionDAG &DAG = DCI.DAG; 10382 SDValue RHS = N->getOperand(1); 10383 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10384 int64_t imm = C->getSExtValue(); 10385 if (imm < 0) { 10386 SDLoc DL(N); 10387 10388 // The with-carry-in form matches bitwise not instead of the negation. 10389 // Effectively, the inverse interpretation of the carry flag already 10390 // accounts for part of the negation. 10391 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10392 10393 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10394 : ARMISD::ADDE; 10395 return DAG.getNode(Opcode, DL, N->getVTList(), 10396 N->getOperand(0), RHS, N->getOperand(2)); 10397 } 10398 } 10399 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 10400 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 10401 } 10402 return SDValue(); 10403 } 10404 10405 /// PerformADDECombine - Target-specific dag combine transform from 10406 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10407 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10408 static SDValue PerformADDECombine(SDNode *N, 10409 TargetLowering::DAGCombinerInfo &DCI, 10410 const ARMSubtarget *Subtarget) { 10411 // Only ARM and Thumb2 support UMLAL/SMLAL. 10412 if (Subtarget->isThumb1Only()) 10413 return PerformAddeSubeCombine(N, DCI, Subtarget); 10414 10415 // Only perform the checks after legalize when the pattern is available. 10416 if (DCI.isBeforeLegalize()) return SDValue(); 10417 10418 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10419 } 10420 10421 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10422 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10423 /// called with the default operands, and if that fails, with commuted 10424 /// operands. 10425 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10426 TargetLowering::DAGCombinerInfo &DCI, 10427 const ARMSubtarget *Subtarget){ 10428 // Attempt to create vpadd for this add. 10429 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10430 return Result; 10431 10432 // Attempt to create vpaddl for this add. 10433 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10434 return Result; 10435 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10436 Subtarget)) 10437 return Result; 10438 10439 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10440 if (N0.getNode()->hasOneUse()) 10441 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10442 return Result; 10443 return SDValue(); 10444 } 10445 10446 static SDValue PerformSHLSimplify(SDNode *N, 10447 TargetLowering::DAGCombinerInfo &DCI, 10448 const ARMSubtarget *ST) { 10449 // Allow the generic combiner to identify potential bswaps. 10450 if (DCI.isBeforeLegalize()) 10451 return SDValue(); 10452 10453 // DAG combiner will fold: 10454 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10455 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 10456 // Other code patterns that can be also be modified have the following form: 10457 // b + ((a << 1) | 510) 10458 // b + ((a << 1) & 510) 10459 // b + ((a << 1) ^ 510) 10460 // b + ((a << 1) + 510) 10461 10462 // Many instructions can perform the shift for free, but it requires both 10463 // the operands to be registers. If c1 << c2 is too large, a mov immediate 10464 // instruction will needed. So, unfold back to the original pattern if: 10465 // - if c1 and c2 are small enough that they don't require mov imms. 10466 // - the user(s) of the node can perform an shl 10467 10468 // No shifted operands for 16-bit instructions. 10469 if (ST->isThumb() && ST->isThumb1Only()) 10470 return SDValue(); 10471 10472 // Check that all the users could perform the shl themselves. 10473 for (auto U : N->uses()) { 10474 switch(U->getOpcode()) { 10475 default: 10476 return SDValue(); 10477 case ISD::SUB: 10478 case ISD::ADD: 10479 case ISD::AND: 10480 case ISD::OR: 10481 case ISD::XOR: 10482 case ISD::SETCC: 10483 case ARMISD::CMP: 10484 // Check that the user isn't already using a constant because there 10485 // aren't any instructions that support an immediate operand and a 10486 // shifted operand. 10487 if (isa<ConstantSDNode>(U->getOperand(0)) || 10488 isa<ConstantSDNode>(U->getOperand(1))) 10489 return SDValue(); 10490 10491 // Check that it's not already using a shift. 10492 if (U->getOperand(0).getOpcode() == ISD::SHL || 10493 U->getOperand(1).getOpcode() == ISD::SHL) 10494 return SDValue(); 10495 break; 10496 } 10497 } 10498 10499 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 10500 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 10501 return SDValue(); 10502 10503 if (N->getOperand(0).getOpcode() != ISD::SHL) 10504 return SDValue(); 10505 10506 SDValue SHL = N->getOperand(0); 10507 10508 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10509 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 10510 if (!C1ShlC2 || !C2) 10511 return SDValue(); 10512 10513 APInt C2Int = C2->getAPIntValue(); 10514 APInt C1Int = C1ShlC2->getAPIntValue(); 10515 10516 // Check that performing a lshr will not lose any information. 10517 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 10518 C2Int.getBitWidth() - C2->getZExtValue()); 10519 if ((C1Int & Mask) != C1Int) 10520 return SDValue(); 10521 10522 // Shift the first constant. 10523 C1Int.lshrInPlace(C2Int); 10524 10525 // The immediates are encoded as an 8-bit value that can be rotated. 10526 auto LargeImm = [](const APInt &Imm) { 10527 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 10528 return Imm.getBitWidth() - Zeros > 8; 10529 }; 10530 10531 if (LargeImm(C1Int) || LargeImm(C2Int)) 10532 return SDValue(); 10533 10534 SelectionDAG &DAG = DCI.DAG; 10535 SDLoc dl(N); 10536 SDValue X = SHL.getOperand(0); 10537 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 10538 DAG.getConstant(C1Int, dl, MVT::i32)); 10539 // Shift left to compensate for the lshr of C1Int. 10540 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 10541 10542 DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); SHL.dump(); 10543 N->dump()); 10544 DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 10545 10546 DAG.ReplaceAllUsesWith(SDValue(N, 0), Res); 10547 return SDValue(N, 0); 10548 } 10549 10550 10551 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10552 /// 10553 static SDValue PerformADDCombine(SDNode *N, 10554 TargetLowering::DAGCombinerInfo &DCI, 10555 const ARMSubtarget *Subtarget) { 10556 SDValue N0 = N->getOperand(0); 10557 SDValue N1 = N->getOperand(1); 10558 10559 // Only works one way, because it needs an immediate operand. 10560 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10561 return Result; 10562 10563 // First try with the default operand order. 10564 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10565 return Result; 10566 10567 // If that didn't work, try again with the operands commuted. 10568 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10569 } 10570 10571 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 10572 /// 10573 static SDValue PerformSUBCombine(SDNode *N, 10574 TargetLowering::DAGCombinerInfo &DCI) { 10575 SDValue N0 = N->getOperand(0); 10576 SDValue N1 = N->getOperand(1); 10577 10578 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10579 if (N1.getNode()->hasOneUse()) 10580 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 10581 return Result; 10582 10583 return SDValue(); 10584 } 10585 10586 /// PerformVMULCombine 10587 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 10588 /// special multiplier accumulator forwarding. 10589 /// vmul d3, d0, d2 10590 /// vmla d3, d1, d2 10591 /// is faster than 10592 /// vadd d3, d0, d1 10593 /// vmul d3, d3, d2 10594 // However, for (A + B) * (A + B), 10595 // vadd d2, d0, d1 10596 // vmul d3, d0, d2 10597 // vmla d3, d1, d2 10598 // is slower than 10599 // vadd d2, d0, d1 10600 // vmul d3, d2, d2 10601 static SDValue PerformVMULCombine(SDNode *N, 10602 TargetLowering::DAGCombinerInfo &DCI, 10603 const ARMSubtarget *Subtarget) { 10604 if (!Subtarget->hasVMLxForwarding()) 10605 return SDValue(); 10606 10607 SelectionDAG &DAG = DCI.DAG; 10608 SDValue N0 = N->getOperand(0); 10609 SDValue N1 = N->getOperand(1); 10610 unsigned Opcode = N0.getOpcode(); 10611 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10612 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10613 Opcode = N1.getOpcode(); 10614 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10615 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10616 return SDValue(); 10617 std::swap(N0, N1); 10618 } 10619 10620 if (N0 == N1) 10621 return SDValue(); 10622 10623 EVT VT = N->getValueType(0); 10624 SDLoc DL(N); 10625 SDValue N00 = N0->getOperand(0); 10626 SDValue N01 = N0->getOperand(1); 10627 return DAG.getNode(Opcode, DL, VT, 10628 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10629 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10630 } 10631 10632 static SDValue PerformMULCombine(SDNode *N, 10633 TargetLowering::DAGCombinerInfo &DCI, 10634 const ARMSubtarget *Subtarget) { 10635 SelectionDAG &DAG = DCI.DAG; 10636 10637 if (Subtarget->isThumb1Only()) 10638 return SDValue(); 10639 10640 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10641 return SDValue(); 10642 10643 EVT VT = N->getValueType(0); 10644 if (VT.is64BitVector() || VT.is128BitVector()) 10645 return PerformVMULCombine(N, DCI, Subtarget); 10646 if (VT != MVT::i32) 10647 return SDValue(); 10648 10649 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10650 if (!C) 10651 return SDValue(); 10652 10653 int64_t MulAmt = C->getSExtValue(); 10654 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10655 10656 ShiftAmt = ShiftAmt & (32 - 1); 10657 SDValue V = N->getOperand(0); 10658 SDLoc DL(N); 10659 10660 SDValue Res; 10661 MulAmt >>= ShiftAmt; 10662 10663 if (MulAmt >= 0) { 10664 if (isPowerOf2_32(MulAmt - 1)) { 10665 // (mul x, 2^N + 1) => (add (shl x, N), x) 10666 Res = DAG.getNode(ISD::ADD, DL, VT, 10667 V, 10668 DAG.getNode(ISD::SHL, DL, VT, 10669 V, 10670 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10671 MVT::i32))); 10672 } else if (isPowerOf2_32(MulAmt + 1)) { 10673 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10674 Res = DAG.getNode(ISD::SUB, DL, VT, 10675 DAG.getNode(ISD::SHL, DL, VT, 10676 V, 10677 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10678 MVT::i32)), 10679 V); 10680 } else 10681 return SDValue(); 10682 } else { 10683 uint64_t MulAmtAbs = -MulAmt; 10684 if (isPowerOf2_32(MulAmtAbs + 1)) { 10685 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10686 Res = DAG.getNode(ISD::SUB, DL, VT, 10687 V, 10688 DAG.getNode(ISD::SHL, DL, VT, 10689 V, 10690 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10691 MVT::i32))); 10692 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10693 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10694 Res = DAG.getNode(ISD::ADD, DL, VT, 10695 V, 10696 DAG.getNode(ISD::SHL, DL, VT, 10697 V, 10698 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10699 MVT::i32))); 10700 Res = DAG.getNode(ISD::SUB, DL, VT, 10701 DAG.getConstant(0, DL, MVT::i32), Res); 10702 } else 10703 return SDValue(); 10704 } 10705 10706 if (ShiftAmt != 0) 10707 Res = DAG.getNode(ISD::SHL, DL, VT, 10708 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10709 10710 // Do not add new nodes to DAG combiner worklist. 10711 DCI.CombineTo(N, Res, false); 10712 return SDValue(); 10713 } 10714 10715 static SDValue PerformANDCombine(SDNode *N, 10716 TargetLowering::DAGCombinerInfo &DCI, 10717 const ARMSubtarget *Subtarget) { 10718 // Attempt to use immediate-form VBIC 10719 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10720 SDLoc dl(N); 10721 EVT VT = N->getValueType(0); 10722 SelectionDAG &DAG = DCI.DAG; 10723 10724 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10725 return SDValue(); 10726 10727 APInt SplatBits, SplatUndef; 10728 unsigned SplatBitSize; 10729 bool HasAnyUndefs; 10730 if (BVN && 10731 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10732 if (SplatBitSize <= 64) { 10733 EVT VbicVT; 10734 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10735 SplatUndef.getZExtValue(), SplatBitSize, 10736 DAG, dl, VbicVT, VT.is128BitVector(), 10737 OtherModImm); 10738 if (Val.getNode()) { 10739 SDValue Input = 10740 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10741 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10742 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10743 } 10744 } 10745 } 10746 10747 if (!Subtarget->isThumb1Only()) { 10748 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10749 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10750 return Result; 10751 10752 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10753 return Result; 10754 } 10755 10756 return SDValue(); 10757 } 10758 10759 // Try combining OR nodes to SMULWB, SMULWT. 10760 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10761 TargetLowering::DAGCombinerInfo &DCI, 10762 const ARMSubtarget *Subtarget) { 10763 if (!Subtarget->hasV6Ops() || 10764 (Subtarget->isThumb() && 10765 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10766 return SDValue(); 10767 10768 SDValue SRL = OR->getOperand(0); 10769 SDValue SHL = OR->getOperand(1); 10770 10771 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10772 SRL = OR->getOperand(1); 10773 SHL = OR->getOperand(0); 10774 } 10775 if (!isSRL16(SRL) || !isSHL16(SHL)) 10776 return SDValue(); 10777 10778 // The first operands to the shifts need to be the two results from the 10779 // same smul_lohi node. 10780 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10781 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10782 return SDValue(); 10783 10784 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10785 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10786 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10787 return SDValue(); 10788 10789 // Now we have: 10790 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10791 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10792 // For SMUWB the 16-bit value will signed extended somehow. 10793 // For SMULWT only the SRA is required. 10794 // Check both sides of SMUL_LOHI 10795 SDValue OpS16 = SMULLOHI->getOperand(0); 10796 SDValue OpS32 = SMULLOHI->getOperand(1); 10797 10798 SelectionDAG &DAG = DCI.DAG; 10799 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10800 OpS16 = OpS32; 10801 OpS32 = SMULLOHI->getOperand(0); 10802 } 10803 10804 SDLoc dl(OR); 10805 unsigned Opcode = 0; 10806 if (isS16(OpS16, DAG)) 10807 Opcode = ARMISD::SMULWB; 10808 else if (isSRA16(OpS16)) { 10809 Opcode = ARMISD::SMULWT; 10810 OpS16 = OpS16->getOperand(0); 10811 } 10812 else 10813 return SDValue(); 10814 10815 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10816 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10817 return SDValue(OR, 0); 10818 } 10819 10820 static SDValue PerformORCombineToBFI(SDNode *N, 10821 TargetLowering::DAGCombinerInfo &DCI, 10822 const ARMSubtarget *Subtarget) { 10823 // BFI is only available on V6T2+ 10824 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10825 return SDValue(); 10826 10827 EVT VT = N->getValueType(0); 10828 SDValue N0 = N->getOperand(0); 10829 SDValue N1 = N->getOperand(1); 10830 SelectionDAG &DAG = DCI.DAG; 10831 SDLoc DL(N); 10832 // 1) or (and A, mask), val => ARMbfi A, val, mask 10833 // iff (val & mask) == val 10834 // 10835 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10836 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10837 // && mask == ~mask2 10838 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10839 // && ~mask == mask2 10840 // (i.e., copy a bitfield value into another bitfield of the same width) 10841 10842 if (VT != MVT::i32) 10843 return SDValue(); 10844 10845 SDValue N00 = N0.getOperand(0); 10846 10847 // The value and the mask need to be constants so we can verify this is 10848 // actually a bitfield set. If the mask is 0xffff, we can do better 10849 // via a movt instruction, so don't use BFI in that case. 10850 SDValue MaskOp = N0.getOperand(1); 10851 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10852 if (!MaskC) 10853 return SDValue(); 10854 unsigned Mask = MaskC->getZExtValue(); 10855 if (Mask == 0xffff) 10856 return SDValue(); 10857 SDValue Res; 10858 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10859 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10860 if (N1C) { 10861 unsigned Val = N1C->getZExtValue(); 10862 if ((Val & ~Mask) != Val) 10863 return SDValue(); 10864 10865 if (ARM::isBitFieldInvertedMask(Mask)) { 10866 Val >>= countTrailingZeros(~Mask); 10867 10868 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10869 DAG.getConstant(Val, DL, MVT::i32), 10870 DAG.getConstant(Mask, DL, MVT::i32)); 10871 10872 DCI.CombineTo(N, Res, false); 10873 // Return value from the original node to inform the combiner than N is 10874 // now dead. 10875 return SDValue(N, 0); 10876 } 10877 } else if (N1.getOpcode() == ISD::AND) { 10878 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10879 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10880 if (!N11C) 10881 return SDValue(); 10882 unsigned Mask2 = N11C->getZExtValue(); 10883 10884 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10885 // as is to match. 10886 if (ARM::isBitFieldInvertedMask(Mask) && 10887 (Mask == ~Mask2)) { 10888 // The pack halfword instruction works better for masks that fit it, 10889 // so use that when it's available. 10890 if (Subtarget->hasDSP() && 10891 (Mask == 0xffff || Mask == 0xffff0000)) 10892 return SDValue(); 10893 // 2a 10894 unsigned amt = countTrailingZeros(Mask2); 10895 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10896 DAG.getConstant(amt, DL, MVT::i32)); 10897 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10898 DAG.getConstant(Mask, DL, MVT::i32)); 10899 DCI.CombineTo(N, Res, false); 10900 // Return value from the original node to inform the combiner than N is 10901 // now dead. 10902 return SDValue(N, 0); 10903 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10904 (~Mask == Mask2)) { 10905 // The pack halfword instruction works better for masks that fit it, 10906 // so use that when it's available. 10907 if (Subtarget->hasDSP() && 10908 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10909 return SDValue(); 10910 // 2b 10911 unsigned lsb = countTrailingZeros(Mask); 10912 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10913 DAG.getConstant(lsb, DL, MVT::i32)); 10914 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10915 DAG.getConstant(Mask2, DL, MVT::i32)); 10916 DCI.CombineTo(N, Res, false); 10917 // Return value from the original node to inform the combiner than N is 10918 // now dead. 10919 return SDValue(N, 0); 10920 } 10921 } 10922 10923 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10924 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10925 ARM::isBitFieldInvertedMask(~Mask)) { 10926 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10927 // where lsb(mask) == #shamt and masked bits of B are known zero. 10928 SDValue ShAmt = N00.getOperand(1); 10929 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10930 unsigned LSB = countTrailingZeros(Mask); 10931 if (ShAmtC != LSB) 10932 return SDValue(); 10933 10934 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10935 DAG.getConstant(~Mask, DL, MVT::i32)); 10936 10937 DCI.CombineTo(N, Res, false); 10938 // Return value from the original node to inform the combiner than N is 10939 // now dead. 10940 return SDValue(N, 0); 10941 } 10942 10943 return SDValue(); 10944 } 10945 10946 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 10947 static SDValue PerformORCombine(SDNode *N, 10948 TargetLowering::DAGCombinerInfo &DCI, 10949 const ARMSubtarget *Subtarget) { 10950 // Attempt to use immediate-form VORR 10951 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10952 SDLoc dl(N); 10953 EVT VT = N->getValueType(0); 10954 SelectionDAG &DAG = DCI.DAG; 10955 10956 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10957 return SDValue(); 10958 10959 APInt SplatBits, SplatUndef; 10960 unsigned SplatBitSize; 10961 bool HasAnyUndefs; 10962 if (BVN && Subtarget->hasNEON() && 10963 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10964 if (SplatBitSize <= 64) { 10965 EVT VorrVT; 10966 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 10967 SplatUndef.getZExtValue(), SplatBitSize, 10968 DAG, dl, VorrVT, VT.is128BitVector(), 10969 OtherModImm); 10970 if (Val.getNode()) { 10971 SDValue Input = 10972 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 10973 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 10974 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 10975 } 10976 } 10977 } 10978 10979 if (!Subtarget->isThumb1Only()) { 10980 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10981 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10982 return Result; 10983 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 10984 return Result; 10985 } 10986 10987 SDValue N0 = N->getOperand(0); 10988 SDValue N1 = N->getOperand(1); 10989 10990 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 10991 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 10992 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10993 10994 // The code below optimizes (or (and X, Y), Z). 10995 // The AND operand needs to have a single user to make these optimizations 10996 // profitable. 10997 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 10998 return SDValue(); 10999 11000 APInt SplatUndef; 11001 unsigned SplatBitSize; 11002 bool HasAnyUndefs; 11003 11004 APInt SplatBits0, SplatBits1; 11005 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 11006 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 11007 // Ensure that the second operand of both ands are constants 11008 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 11009 HasAnyUndefs) && !HasAnyUndefs) { 11010 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 11011 HasAnyUndefs) && !HasAnyUndefs) { 11012 // Ensure that the bit width of the constants are the same and that 11013 // the splat arguments are logical inverses as per the pattern we 11014 // are trying to simplify. 11015 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 11016 SplatBits0 == ~SplatBits1) { 11017 // Canonicalize the vector type to make instruction selection 11018 // simpler. 11019 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 11020 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 11021 N0->getOperand(1), 11022 N0->getOperand(0), 11023 N1->getOperand(0)); 11024 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 11025 } 11026 } 11027 } 11028 } 11029 11030 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 11031 // reasonable. 11032 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 11033 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 11034 return Res; 11035 } 11036 11037 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11038 return Result; 11039 11040 return SDValue(); 11041 } 11042 11043 static SDValue PerformXORCombine(SDNode *N, 11044 TargetLowering::DAGCombinerInfo &DCI, 11045 const ARMSubtarget *Subtarget) { 11046 EVT VT = N->getValueType(0); 11047 SelectionDAG &DAG = DCI.DAG; 11048 11049 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11050 return SDValue(); 11051 11052 if (!Subtarget->isThumb1Only()) { 11053 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11054 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11055 return Result; 11056 11057 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11058 return Result; 11059 } 11060 11061 return SDValue(); 11062 } 11063 11064 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 11065 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 11066 // their position in "to" (Rd). 11067 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 11068 assert(N->getOpcode() == ARMISD::BFI); 11069 11070 SDValue From = N->getOperand(1); 11071 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 11072 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 11073 11074 // If the Base came from a SHR #C, we can deduce that it is really testing bit 11075 // #C in the base of the SHR. 11076 if (From->getOpcode() == ISD::SRL && 11077 isa<ConstantSDNode>(From->getOperand(1))) { 11078 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 11079 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 11080 FromMask <<= Shift.getLimitedValue(31); 11081 From = From->getOperand(0); 11082 } 11083 11084 return From; 11085 } 11086 11087 // If A and B contain one contiguous set of bits, does A | B == A . B? 11088 // 11089 // Neither A nor B must be zero. 11090 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 11091 unsigned LastActiveBitInA = A.countTrailingZeros(); 11092 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 11093 return LastActiveBitInA - 1 == FirstActiveBitInB; 11094 } 11095 11096 static SDValue FindBFIToCombineWith(SDNode *N) { 11097 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 11098 // if one exists. 11099 APInt ToMask, FromMask; 11100 SDValue From = ParseBFI(N, ToMask, FromMask); 11101 SDValue To = N->getOperand(0); 11102 11103 // Now check for a compatible BFI to merge with. We can pass through BFIs that 11104 // aren't compatible, but not if they set the same bit in their destination as 11105 // we do (or that of any BFI we're going to combine with). 11106 SDValue V = To; 11107 APInt CombinedToMask = ToMask; 11108 while (V.getOpcode() == ARMISD::BFI) { 11109 APInt NewToMask, NewFromMask; 11110 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 11111 if (NewFrom != From) { 11112 // This BFI has a different base. Keep going. 11113 CombinedToMask |= NewToMask; 11114 V = V.getOperand(0); 11115 continue; 11116 } 11117 11118 // Do the written bits conflict with any we've seen so far? 11119 if ((NewToMask & CombinedToMask).getBoolValue()) 11120 // Conflicting bits - bail out because going further is unsafe. 11121 return SDValue(); 11122 11123 // Are the new bits contiguous when combined with the old bits? 11124 if (BitsProperlyConcatenate(ToMask, NewToMask) && 11125 BitsProperlyConcatenate(FromMask, NewFromMask)) 11126 return V; 11127 if (BitsProperlyConcatenate(NewToMask, ToMask) && 11128 BitsProperlyConcatenate(NewFromMask, FromMask)) 11129 return V; 11130 11131 // We've seen a write to some bits, so track it. 11132 CombinedToMask |= NewToMask; 11133 // Keep going... 11134 V = V.getOperand(0); 11135 } 11136 11137 return SDValue(); 11138 } 11139 11140 static SDValue PerformBFICombine(SDNode *N, 11141 TargetLowering::DAGCombinerInfo &DCI) { 11142 SDValue N1 = N->getOperand(1); 11143 if (N1.getOpcode() == ISD::AND) { 11144 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 11145 // the bits being cleared by the AND are not demanded by the BFI. 11146 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11147 if (!N11C) 11148 return SDValue(); 11149 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 11150 unsigned LSB = countTrailingZeros(~InvMask); 11151 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 11152 assert(Width < 11153 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 11154 "undefined behavior"); 11155 unsigned Mask = (1u << Width) - 1; 11156 unsigned Mask2 = N11C->getZExtValue(); 11157 if ((Mask & (~Mask2)) == 0) 11158 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 11159 N->getOperand(0), N1.getOperand(0), 11160 N->getOperand(2)); 11161 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 11162 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 11163 // Keep track of any consecutive bits set that all come from the same base 11164 // value. We can combine these together into a single BFI. 11165 SDValue CombineBFI = FindBFIToCombineWith(N); 11166 if (CombineBFI == SDValue()) 11167 return SDValue(); 11168 11169 // We've found a BFI. 11170 APInt ToMask1, FromMask1; 11171 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 11172 11173 APInt ToMask2, FromMask2; 11174 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 11175 assert(From1 == From2); 11176 (void)From2; 11177 11178 // First, unlink CombineBFI. 11179 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 11180 // Then create a new BFI, combining the two together. 11181 APInt NewFromMask = FromMask1 | FromMask2; 11182 APInt NewToMask = ToMask1 | ToMask2; 11183 11184 EVT VT = N->getValueType(0); 11185 SDLoc dl(N); 11186 11187 if (NewFromMask[0] == 0) 11188 From1 = DCI.DAG.getNode( 11189 ISD::SRL, dl, VT, From1, 11190 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 11191 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 11192 DCI.DAG.getConstant(~NewToMask, dl, VT)); 11193 } 11194 return SDValue(); 11195 } 11196 11197 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 11198 /// ARMISD::VMOVRRD. 11199 static SDValue PerformVMOVRRDCombine(SDNode *N, 11200 TargetLowering::DAGCombinerInfo &DCI, 11201 const ARMSubtarget *Subtarget) { 11202 // vmovrrd(vmovdrr x, y) -> x,y 11203 SDValue InDouble = N->getOperand(0); 11204 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 11205 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 11206 11207 // vmovrrd(load f64) -> (load i32), (load i32) 11208 SDNode *InNode = InDouble.getNode(); 11209 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 11210 InNode->getValueType(0) == MVT::f64 && 11211 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 11212 !cast<LoadSDNode>(InNode)->isVolatile()) { 11213 // TODO: Should this be done for non-FrameIndex operands? 11214 LoadSDNode *LD = cast<LoadSDNode>(InNode); 11215 11216 SelectionDAG &DAG = DCI.DAG; 11217 SDLoc DL(LD); 11218 SDValue BasePtr = LD->getBasePtr(); 11219 SDValue NewLD1 = 11220 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 11221 LD->getAlignment(), LD->getMemOperand()->getFlags()); 11222 11223 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11224 DAG.getConstant(4, DL, MVT::i32)); 11225 SDValue NewLD2 = DAG.getLoad( 11226 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 11227 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 11228 11229 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 11230 if (DCI.DAG.getDataLayout().isBigEndian()) 11231 std::swap (NewLD1, NewLD2); 11232 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 11233 return Result; 11234 } 11235 11236 return SDValue(); 11237 } 11238 11239 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 11240 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 11241 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 11242 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 11243 SDValue Op0 = N->getOperand(0); 11244 SDValue Op1 = N->getOperand(1); 11245 if (Op0.getOpcode() == ISD::BITCAST) 11246 Op0 = Op0.getOperand(0); 11247 if (Op1.getOpcode() == ISD::BITCAST) 11248 Op1 = Op1.getOperand(0); 11249 if (Op0.getOpcode() == ARMISD::VMOVRRD && 11250 Op0.getNode() == Op1.getNode() && 11251 Op0.getResNo() == 0 && Op1.getResNo() == 1) 11252 return DAG.getNode(ISD::BITCAST, SDLoc(N), 11253 N->getValueType(0), Op0.getOperand(0)); 11254 return SDValue(); 11255 } 11256 11257 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 11258 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 11259 /// i64 vector to have f64 elements, since the value can then be loaded 11260 /// directly into a VFP register. 11261 static bool hasNormalLoadOperand(SDNode *N) { 11262 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 11263 for (unsigned i = 0; i < NumElts; ++i) { 11264 SDNode *Elt = N->getOperand(i).getNode(); 11265 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 11266 return true; 11267 } 11268 return false; 11269 } 11270 11271 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 11272 /// ISD::BUILD_VECTOR. 11273 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 11274 TargetLowering::DAGCombinerInfo &DCI, 11275 const ARMSubtarget *Subtarget) { 11276 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 11277 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 11278 // into a pair of GPRs, which is fine when the value is used as a scalar, 11279 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 11280 SelectionDAG &DAG = DCI.DAG; 11281 if (N->getNumOperands() == 2) 11282 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 11283 return RV; 11284 11285 // Load i64 elements as f64 values so that type legalization does not split 11286 // them up into i32 values. 11287 EVT VT = N->getValueType(0); 11288 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 11289 return SDValue(); 11290 SDLoc dl(N); 11291 SmallVector<SDValue, 8> Ops; 11292 unsigned NumElts = VT.getVectorNumElements(); 11293 for (unsigned i = 0; i < NumElts; ++i) { 11294 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 11295 Ops.push_back(V); 11296 // Make the DAGCombiner fold the bitcast. 11297 DCI.AddToWorklist(V.getNode()); 11298 } 11299 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 11300 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 11301 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11302 } 11303 11304 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 11305 static SDValue 11306 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11307 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 11308 // At that time, we may have inserted bitcasts from integer to float. 11309 // If these bitcasts have survived DAGCombine, change the lowering of this 11310 // BUILD_VECTOR in something more vector friendly, i.e., that does not 11311 // force to use floating point types. 11312 11313 // Make sure we can change the type of the vector. 11314 // This is possible iff: 11315 // 1. The vector is only used in a bitcast to a integer type. I.e., 11316 // 1.1. Vector is used only once. 11317 // 1.2. Use is a bit convert to an integer type. 11318 // 2. The size of its operands are 32-bits (64-bits are not legal). 11319 EVT VT = N->getValueType(0); 11320 EVT EltVT = VT.getVectorElementType(); 11321 11322 // Check 1.1. and 2. 11323 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 11324 return SDValue(); 11325 11326 // By construction, the input type must be float. 11327 assert(EltVT == MVT::f32 && "Unexpected type!"); 11328 11329 // Check 1.2. 11330 SDNode *Use = *N->use_begin(); 11331 if (Use->getOpcode() != ISD::BITCAST || 11332 Use->getValueType(0).isFloatingPoint()) 11333 return SDValue(); 11334 11335 // Check profitability. 11336 // Model is, if more than half of the relevant operands are bitcast from 11337 // i32, turn the build_vector into a sequence of insert_vector_elt. 11338 // Relevant operands are everything that is not statically 11339 // (i.e., at compile time) bitcasted. 11340 unsigned NumOfBitCastedElts = 0; 11341 unsigned NumElts = VT.getVectorNumElements(); 11342 unsigned NumOfRelevantElts = NumElts; 11343 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 11344 SDValue Elt = N->getOperand(Idx); 11345 if (Elt->getOpcode() == ISD::BITCAST) { 11346 // Assume only bit cast to i32 will go away. 11347 if (Elt->getOperand(0).getValueType() == MVT::i32) 11348 ++NumOfBitCastedElts; 11349 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 11350 // Constants are statically casted, thus do not count them as 11351 // relevant operands. 11352 --NumOfRelevantElts; 11353 } 11354 11355 // Check if more than half of the elements require a non-free bitcast. 11356 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 11357 return SDValue(); 11358 11359 SelectionDAG &DAG = DCI.DAG; 11360 // Create the new vector type. 11361 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 11362 // Check if the type is legal. 11363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11364 if (!TLI.isTypeLegal(VecVT)) 11365 return SDValue(); 11366 11367 // Combine: 11368 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 11369 // => BITCAST INSERT_VECTOR_ELT 11370 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 11371 // (BITCAST EN), N. 11372 SDValue Vec = DAG.getUNDEF(VecVT); 11373 SDLoc dl(N); 11374 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 11375 SDValue V = N->getOperand(Idx); 11376 if (V.isUndef()) 11377 continue; 11378 if (V.getOpcode() == ISD::BITCAST && 11379 V->getOperand(0).getValueType() == MVT::i32) 11380 // Fold obvious case. 11381 V = V.getOperand(0); 11382 else { 11383 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 11384 // Make the DAGCombiner fold the bitcasts. 11385 DCI.AddToWorklist(V.getNode()); 11386 } 11387 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 11388 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 11389 } 11390 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 11391 // Make the DAGCombiner fold the bitcasts. 11392 DCI.AddToWorklist(Vec.getNode()); 11393 return Vec; 11394 } 11395 11396 /// PerformInsertEltCombine - Target-specific dag combine xforms for 11397 /// ISD::INSERT_VECTOR_ELT. 11398 static SDValue PerformInsertEltCombine(SDNode *N, 11399 TargetLowering::DAGCombinerInfo &DCI) { 11400 // Bitcast an i64 load inserted into a vector to f64. 11401 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11402 EVT VT = N->getValueType(0); 11403 SDNode *Elt = N->getOperand(1).getNode(); 11404 if (VT.getVectorElementType() != MVT::i64 || 11405 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 11406 return SDValue(); 11407 11408 SelectionDAG &DAG = DCI.DAG; 11409 SDLoc dl(N); 11410 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11411 VT.getVectorNumElements()); 11412 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 11413 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 11414 // Make the DAGCombiner fold the bitcasts. 11415 DCI.AddToWorklist(Vec.getNode()); 11416 DCI.AddToWorklist(V.getNode()); 11417 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 11418 Vec, V, N->getOperand(2)); 11419 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 11420 } 11421 11422 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 11423 /// ISD::VECTOR_SHUFFLE. 11424 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 11425 // The LLVM shufflevector instruction does not require the shuffle mask 11426 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 11427 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 11428 // operands do not match the mask length, they are extended by concatenating 11429 // them with undef vectors. That is probably the right thing for other 11430 // targets, but for NEON it is better to concatenate two double-register 11431 // size vector operands into a single quad-register size vector. Do that 11432 // transformation here: 11433 // shuffle(concat(v1, undef), concat(v2, undef)) -> 11434 // shuffle(concat(v1, v2), undef) 11435 SDValue Op0 = N->getOperand(0); 11436 SDValue Op1 = N->getOperand(1); 11437 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 11438 Op1.getOpcode() != ISD::CONCAT_VECTORS || 11439 Op0.getNumOperands() != 2 || 11440 Op1.getNumOperands() != 2) 11441 return SDValue(); 11442 SDValue Concat0Op1 = Op0.getOperand(1); 11443 SDValue Concat1Op1 = Op1.getOperand(1); 11444 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 11445 return SDValue(); 11446 // Skip the transformation if any of the types are illegal. 11447 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11448 EVT VT = N->getValueType(0); 11449 if (!TLI.isTypeLegal(VT) || 11450 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 11451 !TLI.isTypeLegal(Concat1Op1.getValueType())) 11452 return SDValue(); 11453 11454 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11455 Op0.getOperand(0), Op1.getOperand(0)); 11456 // Translate the shuffle mask. 11457 SmallVector<int, 16> NewMask; 11458 unsigned NumElts = VT.getVectorNumElements(); 11459 unsigned HalfElts = NumElts/2; 11460 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11461 for (unsigned n = 0; n < NumElts; ++n) { 11462 int MaskElt = SVN->getMaskElt(n); 11463 int NewElt = -1; 11464 if (MaskElt < (int)HalfElts) 11465 NewElt = MaskElt; 11466 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 11467 NewElt = HalfElts + MaskElt - NumElts; 11468 NewMask.push_back(NewElt); 11469 } 11470 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 11471 DAG.getUNDEF(VT), NewMask); 11472 } 11473 11474 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 11475 /// NEON load/store intrinsics, and generic vector load/stores, to merge 11476 /// base address updates. 11477 /// For generic load/stores, the memory type is assumed to be a vector. 11478 /// The caller is assumed to have checked legality. 11479 static SDValue CombineBaseUpdate(SDNode *N, 11480 TargetLowering::DAGCombinerInfo &DCI) { 11481 SelectionDAG &DAG = DCI.DAG; 11482 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 11483 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 11484 const bool isStore = N->getOpcode() == ISD::STORE; 11485 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 11486 SDValue Addr = N->getOperand(AddrOpIdx); 11487 MemSDNode *MemN = cast<MemSDNode>(N); 11488 SDLoc dl(N); 11489 11490 // Search for a use of the address operand that is an increment. 11491 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11492 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11493 SDNode *User = *UI; 11494 if (User->getOpcode() != ISD::ADD || 11495 UI.getUse().getResNo() != Addr.getResNo()) 11496 continue; 11497 11498 // Check that the add is independent of the load/store. Otherwise, folding 11499 // it would create a cycle. 11500 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 11501 continue; 11502 11503 // Find the new opcode for the updating load/store. 11504 bool isLoadOp = true; 11505 bool isLaneOp = false; 11506 unsigned NewOpc = 0; 11507 unsigned NumVecs = 0; 11508 if (isIntrinsic) { 11509 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11510 switch (IntNo) { 11511 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11512 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 11513 NumVecs = 1; break; 11514 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 11515 NumVecs = 2; break; 11516 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 11517 NumVecs = 3; break; 11518 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 11519 NumVecs = 4; break; 11520 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 11521 NumVecs = 2; isLaneOp = true; break; 11522 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 11523 NumVecs = 3; isLaneOp = true; break; 11524 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 11525 NumVecs = 4; isLaneOp = true; break; 11526 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 11527 NumVecs = 1; isLoadOp = false; break; 11528 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 11529 NumVecs = 2; isLoadOp = false; break; 11530 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 11531 NumVecs = 3; isLoadOp = false; break; 11532 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 11533 NumVecs = 4; isLoadOp = false; break; 11534 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 11535 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 11536 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 11537 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 11538 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 11539 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 11540 } 11541 } else { 11542 isLaneOp = true; 11543 switch (N->getOpcode()) { 11544 default: llvm_unreachable("unexpected opcode for Neon base update"); 11545 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 11546 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 11547 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 11548 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 11549 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 11550 NumVecs = 1; isLaneOp = false; break; 11551 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 11552 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 11553 } 11554 } 11555 11556 // Find the size of memory referenced by the load/store. 11557 EVT VecTy; 11558 if (isLoadOp) { 11559 VecTy = N->getValueType(0); 11560 } else if (isIntrinsic) { 11561 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 11562 } else { 11563 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 11564 VecTy = N->getOperand(1).getValueType(); 11565 } 11566 11567 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11568 if (isLaneOp) 11569 NumBytes /= VecTy.getVectorNumElements(); 11570 11571 // If the increment is a constant, it must match the memory ref size. 11572 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11573 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 11574 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 11575 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 11576 // separate instructions that make it harder to use a non-constant update. 11577 continue; 11578 } 11579 11580 // OK, we found an ADD we can fold into the base update. 11581 // Now, create a _UPD node, taking care of not breaking alignment. 11582 11583 EVT AlignedVecTy = VecTy; 11584 unsigned Alignment = MemN->getAlignment(); 11585 11586 // If this is a less-than-standard-aligned load/store, change the type to 11587 // match the standard alignment. 11588 // The alignment is overlooked when selecting _UPD variants; and it's 11589 // easier to introduce bitcasts here than fix that. 11590 // There are 3 ways to get to this base-update combine: 11591 // - intrinsics: they are assumed to be properly aligned (to the standard 11592 // alignment of the memory type), so we don't need to do anything. 11593 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 11594 // intrinsics, so, likewise, there's nothing to do. 11595 // - generic load/store instructions: the alignment is specified as an 11596 // explicit operand, rather than implicitly as the standard alignment 11597 // of the memory type (like the intrisics). We need to change the 11598 // memory type to match the explicit alignment. That way, we don't 11599 // generate non-standard-aligned ARMISD::VLDx nodes. 11600 if (isa<LSBaseSDNode>(N)) { 11601 if (Alignment == 0) 11602 Alignment = 1; 11603 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 11604 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 11605 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 11606 assert(!isLaneOp && "Unexpected generic load/store lane."); 11607 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 11608 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 11609 } 11610 // Don't set an explicit alignment on regular load/stores that we want 11611 // to transform to VLD/VST 1_UPD nodes. 11612 // This matches the behavior of regular load/stores, which only get an 11613 // explicit alignment if the MMO alignment is larger than the standard 11614 // alignment of the memory type. 11615 // Intrinsics, however, always get an explicit alignment, set to the 11616 // alignment of the MMO. 11617 Alignment = 1; 11618 } 11619 11620 // Create the new updating load/store node. 11621 // First, create an SDVTList for the new updating node's results. 11622 EVT Tys[6]; 11623 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 11624 unsigned n; 11625 for (n = 0; n < NumResultVecs; ++n) 11626 Tys[n] = AlignedVecTy; 11627 Tys[n++] = MVT::i32; 11628 Tys[n] = MVT::Other; 11629 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 11630 11631 // Then, gather the new node's operands. 11632 SmallVector<SDValue, 8> Ops; 11633 Ops.push_back(N->getOperand(0)); // incoming chain 11634 Ops.push_back(N->getOperand(AddrOpIdx)); 11635 Ops.push_back(Inc); 11636 11637 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 11638 // Try to match the intrinsic's signature 11639 Ops.push_back(StN->getValue()); 11640 } else { 11641 // Loads (and of course intrinsics) match the intrinsics' signature, 11642 // so just add all but the alignment operand. 11643 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 11644 Ops.push_back(N->getOperand(i)); 11645 } 11646 11647 // For all node types, the alignment operand is always the last one. 11648 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 11649 11650 // If this is a non-standard-aligned STORE, the penultimate operand is the 11651 // stored value. Bitcast it to the aligned type. 11652 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 11653 SDValue &StVal = Ops[Ops.size()-2]; 11654 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 11655 } 11656 11657 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 11658 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 11659 MemN->getMemOperand()); 11660 11661 // Update the uses. 11662 SmallVector<SDValue, 5> NewResults; 11663 for (unsigned i = 0; i < NumResultVecs; ++i) 11664 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11665 11666 // If this is an non-standard-aligned LOAD, the first result is the loaded 11667 // value. Bitcast it to the expected result type. 11668 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 11669 SDValue &LdVal = NewResults[0]; 11670 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 11671 } 11672 11673 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 11674 DCI.CombineTo(N, NewResults); 11675 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11676 11677 break; 11678 } 11679 return SDValue(); 11680 } 11681 11682 static SDValue PerformVLDCombine(SDNode *N, 11683 TargetLowering::DAGCombinerInfo &DCI) { 11684 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11685 return SDValue(); 11686 11687 return CombineBaseUpdate(N, DCI); 11688 } 11689 11690 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 11691 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 11692 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11693 /// return true. 11694 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11695 SelectionDAG &DAG = DCI.DAG; 11696 EVT VT = N->getValueType(0); 11697 // vldN-dup instructions only support 64-bit vectors for N > 1. 11698 if (!VT.is64BitVector()) 11699 return false; 11700 11701 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11702 SDNode *VLD = N->getOperand(0).getNode(); 11703 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11704 return false; 11705 unsigned NumVecs = 0; 11706 unsigned NewOpc = 0; 11707 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11708 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11709 NumVecs = 2; 11710 NewOpc = ARMISD::VLD2DUP; 11711 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11712 NumVecs = 3; 11713 NewOpc = ARMISD::VLD3DUP; 11714 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11715 NumVecs = 4; 11716 NewOpc = ARMISD::VLD4DUP; 11717 } else { 11718 return false; 11719 } 11720 11721 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11722 // numbers match the load. 11723 unsigned VLDLaneNo = 11724 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11725 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11726 UI != UE; ++UI) { 11727 // Ignore uses of the chain result. 11728 if (UI.getUse().getResNo() == NumVecs) 11729 continue; 11730 SDNode *User = *UI; 11731 if (User->getOpcode() != ARMISD::VDUPLANE || 11732 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11733 return false; 11734 } 11735 11736 // Create the vldN-dup node. 11737 EVT Tys[5]; 11738 unsigned n; 11739 for (n = 0; n < NumVecs; ++n) 11740 Tys[n] = VT; 11741 Tys[n] = MVT::Other; 11742 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11743 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11744 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11745 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11746 Ops, VLDMemInt->getMemoryVT(), 11747 VLDMemInt->getMemOperand()); 11748 11749 // Update the uses. 11750 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11751 UI != UE; ++UI) { 11752 unsigned ResNo = UI.getUse().getResNo(); 11753 // Ignore uses of the chain result. 11754 if (ResNo == NumVecs) 11755 continue; 11756 SDNode *User = *UI; 11757 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11758 } 11759 11760 // Now the vldN-lane intrinsic is dead except for its chain result. 11761 // Update uses of the chain. 11762 std::vector<SDValue> VLDDupResults; 11763 for (unsigned n = 0; n < NumVecs; ++n) 11764 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11765 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11766 DCI.CombineTo(VLD, VLDDupResults); 11767 11768 return true; 11769 } 11770 11771 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11772 /// ARMISD::VDUPLANE. 11773 static SDValue PerformVDUPLANECombine(SDNode *N, 11774 TargetLowering::DAGCombinerInfo &DCI) { 11775 SDValue Op = N->getOperand(0); 11776 11777 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11778 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11779 if (CombineVLDDUP(N, DCI)) 11780 return SDValue(N, 0); 11781 11782 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11783 // redundant. Ignore bit_converts for now; element sizes are checked below. 11784 while (Op.getOpcode() == ISD::BITCAST) 11785 Op = Op.getOperand(0); 11786 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11787 return SDValue(); 11788 11789 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11790 unsigned EltSize = Op.getScalarValueSizeInBits(); 11791 // The canonical VMOV for a zero vector uses a 32-bit element size. 11792 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11793 unsigned EltBits; 11794 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11795 EltSize = 8; 11796 EVT VT = N->getValueType(0); 11797 if (EltSize > VT.getScalarSizeInBits()) 11798 return SDValue(); 11799 11800 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11801 } 11802 11803 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11804 static SDValue PerformVDUPCombine(SDNode *N, 11805 TargetLowering::DAGCombinerInfo &DCI) { 11806 SelectionDAG &DAG = DCI.DAG; 11807 SDValue Op = N->getOperand(0); 11808 11809 // Match VDUP(LOAD) -> VLD1DUP. 11810 // We match this pattern here rather than waiting for isel because the 11811 // transform is only legal for unindexed loads. 11812 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11813 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11814 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11815 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11816 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11817 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11818 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11819 Ops, LD->getMemoryVT(), 11820 LD->getMemOperand()); 11821 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11822 return VLDDup; 11823 } 11824 11825 return SDValue(); 11826 } 11827 11828 static SDValue PerformLOADCombine(SDNode *N, 11829 TargetLowering::DAGCombinerInfo &DCI) { 11830 EVT VT = N->getValueType(0); 11831 11832 // If this is a legal vector load, try to combine it into a VLD1_UPD. 11833 if (ISD::isNormalLoad(N) && VT.isVector() && 11834 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11835 return CombineBaseUpdate(N, DCI); 11836 11837 return SDValue(); 11838 } 11839 11840 /// PerformSTORECombine - Target-specific dag combine xforms for 11841 /// ISD::STORE. 11842 static SDValue PerformSTORECombine(SDNode *N, 11843 TargetLowering::DAGCombinerInfo &DCI) { 11844 StoreSDNode *St = cast<StoreSDNode>(N); 11845 if (St->isVolatile()) 11846 return SDValue(); 11847 11848 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 11849 // pack all of the elements in one place. Next, store to memory in fewer 11850 // chunks. 11851 SDValue StVal = St->getValue(); 11852 EVT VT = StVal.getValueType(); 11853 if (St->isTruncatingStore() && VT.isVector()) { 11854 SelectionDAG &DAG = DCI.DAG; 11855 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11856 EVT StVT = St->getMemoryVT(); 11857 unsigned NumElems = VT.getVectorNumElements(); 11858 assert(StVT != VT && "Cannot truncate to the same type"); 11859 unsigned FromEltSz = VT.getScalarSizeInBits(); 11860 unsigned ToEltSz = StVT.getScalarSizeInBits(); 11861 11862 // From, To sizes and ElemCount must be pow of two 11863 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 11864 11865 // We are going to use the original vector elt for storing. 11866 // Accumulated smaller vector elements must be a multiple of the store size. 11867 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 11868 11869 unsigned SizeRatio = FromEltSz / ToEltSz; 11870 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 11871 11872 // Create a type on which we perform the shuffle. 11873 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 11874 NumElems*SizeRatio); 11875 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 11876 11877 SDLoc DL(St); 11878 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 11879 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 11880 for (unsigned i = 0; i < NumElems; ++i) 11881 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 11882 ? (i + 1) * SizeRatio - 1 11883 : i * SizeRatio; 11884 11885 // Can't shuffle using an illegal type. 11886 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 11887 11888 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 11889 DAG.getUNDEF(WideVec.getValueType()), 11890 ShuffleVec); 11891 // At this point all of the data is stored at the bottom of the 11892 // register. We now need to save it to mem. 11893 11894 // Find the largest store unit 11895 MVT StoreType = MVT::i8; 11896 for (MVT Tp : MVT::integer_valuetypes()) { 11897 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 11898 StoreType = Tp; 11899 } 11900 // Didn't find a legal store type. 11901 if (!TLI.isTypeLegal(StoreType)) 11902 return SDValue(); 11903 11904 // Bitcast the original vector into a vector of store-size units 11905 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 11906 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 11907 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 11908 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 11909 SmallVector<SDValue, 8> Chains; 11910 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 11911 TLI.getPointerTy(DAG.getDataLayout())); 11912 SDValue BasePtr = St->getBasePtr(); 11913 11914 // Perform one or more big stores into memory. 11915 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 11916 for (unsigned I = 0; I < E; I++) { 11917 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 11918 StoreType, ShuffWide, 11919 DAG.getIntPtrConstant(I, DL)); 11920 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 11921 St->getPointerInfo(), St->getAlignment(), 11922 St->getMemOperand()->getFlags()); 11923 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 11924 Increment); 11925 Chains.push_back(Ch); 11926 } 11927 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11928 } 11929 11930 if (!ISD::isNormalStore(St)) 11931 return SDValue(); 11932 11933 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 11934 // ARM stores of arguments in the same cache line. 11935 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 11936 StVal.getNode()->hasOneUse()) { 11937 SelectionDAG &DAG = DCI.DAG; 11938 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 11939 SDLoc DL(St); 11940 SDValue BasePtr = St->getBasePtr(); 11941 SDValue NewST1 = DAG.getStore( 11942 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 11943 BasePtr, St->getPointerInfo(), St->getAlignment(), 11944 St->getMemOperand()->getFlags()); 11945 11946 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11947 DAG.getConstant(4, DL, MVT::i32)); 11948 return DAG.getStore(NewST1.getValue(0), DL, 11949 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 11950 OffsetPtr, St->getPointerInfo(), 11951 std::min(4U, St->getAlignment() / 2), 11952 St->getMemOperand()->getFlags()); 11953 } 11954 11955 if (StVal.getValueType() == MVT::i64 && 11956 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11957 11958 // Bitcast an i64 store extracted from a vector to f64. 11959 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11960 SelectionDAG &DAG = DCI.DAG; 11961 SDLoc dl(StVal); 11962 SDValue IntVec = StVal.getOperand(0); 11963 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11964 IntVec.getValueType().getVectorNumElements()); 11965 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 11966 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 11967 Vec, StVal.getOperand(1)); 11968 dl = SDLoc(N); 11969 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 11970 // Make the DAGCombiner fold the bitcasts. 11971 DCI.AddToWorklist(Vec.getNode()); 11972 DCI.AddToWorklist(ExtElt.getNode()); 11973 DCI.AddToWorklist(V.getNode()); 11974 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 11975 St->getPointerInfo(), St->getAlignment(), 11976 St->getMemOperand()->getFlags(), St->getAAInfo()); 11977 } 11978 11979 // If this is a legal vector store, try to combine it into a VST1_UPD. 11980 if (ISD::isNormalStore(N) && VT.isVector() && 11981 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11982 return CombineBaseUpdate(N, DCI); 11983 11984 return SDValue(); 11985 } 11986 11987 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11988 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11989 /// when the VMUL has a constant operand that is a power of 2. 11990 /// 11991 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11992 /// vmul.f32 d16, d17, d16 11993 /// vcvt.s32.f32 d16, d16 11994 /// becomes: 11995 /// vcvt.s32.f32 d16, d16, #3 11996 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11997 const ARMSubtarget *Subtarget) { 11998 if (!Subtarget->hasNEON()) 11999 return SDValue(); 12000 12001 SDValue Op = N->getOperand(0); 12002 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 12003 Op.getOpcode() != ISD::FMUL) 12004 return SDValue(); 12005 12006 SDValue ConstVec = Op->getOperand(1); 12007 if (!isa<BuildVectorSDNode>(ConstVec)) 12008 return SDValue(); 12009 12010 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 12011 uint32_t FloatBits = FloatTy.getSizeInBits(); 12012 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 12013 uint32_t IntBits = IntTy.getSizeInBits(); 12014 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12015 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 12016 // These instructions only exist converting from f32 to i32. We can handle 12017 // smaller integers by generating an extra truncate, but larger ones would 12018 // be lossy. We also can't handle more then 4 lanes, since these intructions 12019 // only support v2i32/v4i32 types. 12020 return SDValue(); 12021 } 12022 12023 BitVector UndefElements; 12024 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12025 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12026 if (C == -1 || C == 0 || C > 32) 12027 return SDValue(); 12028 12029 SDLoc dl(N); 12030 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 12031 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 12032 Intrinsic::arm_neon_vcvtfp2fxu; 12033 SDValue FixConv = DAG.getNode( 12034 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12035 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 12036 DAG.getConstant(C, dl, MVT::i32)); 12037 12038 if (IntBits < FloatBits) 12039 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 12040 12041 return FixConv; 12042 } 12043 12044 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 12045 /// can replace combinations of VCVT (integer to floating-point) and VDIV 12046 /// when the VDIV has a constant operand that is a power of 2. 12047 /// 12048 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12049 /// vcvt.f32.s32 d16, d16 12050 /// vdiv.f32 d16, d17, d16 12051 /// becomes: 12052 /// vcvt.f32.s32 d16, d16, #3 12053 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 12054 const ARMSubtarget *Subtarget) { 12055 if (!Subtarget->hasNEON()) 12056 return SDValue(); 12057 12058 SDValue Op = N->getOperand(0); 12059 unsigned OpOpcode = Op.getNode()->getOpcode(); 12060 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 12061 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 12062 return SDValue(); 12063 12064 SDValue ConstVec = N->getOperand(1); 12065 if (!isa<BuildVectorSDNode>(ConstVec)) 12066 return SDValue(); 12067 12068 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 12069 uint32_t FloatBits = FloatTy.getSizeInBits(); 12070 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 12071 uint32_t IntBits = IntTy.getSizeInBits(); 12072 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12073 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 12074 // These instructions only exist converting from i32 to f32. We can handle 12075 // smaller integers by generating an extra extend, but larger ones would 12076 // be lossy. We also can't handle more then 4 lanes, since these intructions 12077 // only support v2i32/v4i32 types. 12078 return SDValue(); 12079 } 12080 12081 BitVector UndefElements; 12082 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12083 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12084 if (C == -1 || C == 0 || C > 32) 12085 return SDValue(); 12086 12087 SDLoc dl(N); 12088 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 12089 SDValue ConvInput = Op.getOperand(0); 12090 if (IntBits < FloatBits) 12091 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 12092 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12093 ConvInput); 12094 12095 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 12096 Intrinsic::arm_neon_vcvtfxu2fp; 12097 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 12098 Op.getValueType(), 12099 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 12100 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 12101 } 12102 12103 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 12104 /// operand of a vector shift operation, where all the elements of the 12105 /// build_vector must have the same constant integer value. 12106 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 12107 // Ignore bit_converts. 12108 while (Op.getOpcode() == ISD::BITCAST) 12109 Op = Op.getOperand(0); 12110 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 12111 APInt SplatBits, SplatUndef; 12112 unsigned SplatBitSize; 12113 bool HasAnyUndefs; 12114 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 12115 HasAnyUndefs, ElementBits) || 12116 SplatBitSize > ElementBits) 12117 return false; 12118 Cnt = SplatBits.getSExtValue(); 12119 return true; 12120 } 12121 12122 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 12123 /// operand of a vector shift left operation. That value must be in the range: 12124 /// 0 <= Value < ElementBits for a left shift; or 12125 /// 0 <= Value <= ElementBits for a long left shift. 12126 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 12127 assert(VT.isVector() && "vector shift count is not a vector type"); 12128 int64_t ElementBits = VT.getScalarSizeInBits(); 12129 if (! getVShiftImm(Op, ElementBits, Cnt)) 12130 return false; 12131 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 12132 } 12133 12134 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 12135 /// operand of a vector shift right operation. For a shift opcode, the value 12136 /// is positive, but for an intrinsic the value count must be negative. The 12137 /// absolute value must be in the range: 12138 /// 1 <= |Value| <= ElementBits for a right shift; or 12139 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 12140 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 12141 int64_t &Cnt) { 12142 assert(VT.isVector() && "vector shift count is not a vector type"); 12143 int64_t ElementBits = VT.getScalarSizeInBits(); 12144 if (! getVShiftImm(Op, ElementBits, Cnt)) 12145 return false; 12146 if (!isIntrinsic) 12147 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 12148 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 12149 Cnt = -Cnt; 12150 return true; 12151 } 12152 return false; 12153 } 12154 12155 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 12156 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 12157 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12158 switch (IntNo) { 12159 default: 12160 // Don't do anything for most intrinsics. 12161 break; 12162 12163 // Vector shifts: check for immediate versions and lower them. 12164 // Note: This is done during DAG combining instead of DAG legalizing because 12165 // the build_vectors for 64-bit vector element shift counts are generally 12166 // not legal, and it is hard to see their values after they get legalized to 12167 // loads from a constant pool. 12168 case Intrinsic::arm_neon_vshifts: 12169 case Intrinsic::arm_neon_vshiftu: 12170 case Intrinsic::arm_neon_vrshifts: 12171 case Intrinsic::arm_neon_vrshiftu: 12172 case Intrinsic::arm_neon_vrshiftn: 12173 case Intrinsic::arm_neon_vqshifts: 12174 case Intrinsic::arm_neon_vqshiftu: 12175 case Intrinsic::arm_neon_vqshiftsu: 12176 case Intrinsic::arm_neon_vqshiftns: 12177 case Intrinsic::arm_neon_vqshiftnu: 12178 case Intrinsic::arm_neon_vqshiftnsu: 12179 case Intrinsic::arm_neon_vqrshiftns: 12180 case Intrinsic::arm_neon_vqrshiftnu: 12181 case Intrinsic::arm_neon_vqrshiftnsu: { 12182 EVT VT = N->getOperand(1).getValueType(); 12183 int64_t Cnt; 12184 unsigned VShiftOpc = 0; 12185 12186 switch (IntNo) { 12187 case Intrinsic::arm_neon_vshifts: 12188 case Intrinsic::arm_neon_vshiftu: 12189 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 12190 VShiftOpc = ARMISD::VSHL; 12191 break; 12192 } 12193 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 12194 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 12195 ARMISD::VSHRs : ARMISD::VSHRu); 12196 break; 12197 } 12198 return SDValue(); 12199 12200 case Intrinsic::arm_neon_vrshifts: 12201 case Intrinsic::arm_neon_vrshiftu: 12202 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 12203 break; 12204 return SDValue(); 12205 12206 case Intrinsic::arm_neon_vqshifts: 12207 case Intrinsic::arm_neon_vqshiftu: 12208 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12209 break; 12210 return SDValue(); 12211 12212 case Intrinsic::arm_neon_vqshiftsu: 12213 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12214 break; 12215 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 12216 12217 case Intrinsic::arm_neon_vrshiftn: 12218 case Intrinsic::arm_neon_vqshiftns: 12219 case Intrinsic::arm_neon_vqshiftnu: 12220 case Intrinsic::arm_neon_vqshiftnsu: 12221 case Intrinsic::arm_neon_vqrshiftns: 12222 case Intrinsic::arm_neon_vqrshiftnu: 12223 case Intrinsic::arm_neon_vqrshiftnsu: 12224 // Narrowing shifts require an immediate right shift. 12225 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 12226 break; 12227 llvm_unreachable("invalid shift count for narrowing vector shift " 12228 "intrinsic"); 12229 12230 default: 12231 llvm_unreachable("unhandled vector shift"); 12232 } 12233 12234 switch (IntNo) { 12235 case Intrinsic::arm_neon_vshifts: 12236 case Intrinsic::arm_neon_vshiftu: 12237 // Opcode already set above. 12238 break; 12239 case Intrinsic::arm_neon_vrshifts: 12240 VShiftOpc = ARMISD::VRSHRs; break; 12241 case Intrinsic::arm_neon_vrshiftu: 12242 VShiftOpc = ARMISD::VRSHRu; break; 12243 case Intrinsic::arm_neon_vrshiftn: 12244 VShiftOpc = ARMISD::VRSHRN; break; 12245 case Intrinsic::arm_neon_vqshifts: 12246 VShiftOpc = ARMISD::VQSHLs; break; 12247 case Intrinsic::arm_neon_vqshiftu: 12248 VShiftOpc = ARMISD::VQSHLu; break; 12249 case Intrinsic::arm_neon_vqshiftsu: 12250 VShiftOpc = ARMISD::VQSHLsu; break; 12251 case Intrinsic::arm_neon_vqshiftns: 12252 VShiftOpc = ARMISD::VQSHRNs; break; 12253 case Intrinsic::arm_neon_vqshiftnu: 12254 VShiftOpc = ARMISD::VQSHRNu; break; 12255 case Intrinsic::arm_neon_vqshiftnsu: 12256 VShiftOpc = ARMISD::VQSHRNsu; break; 12257 case Intrinsic::arm_neon_vqrshiftns: 12258 VShiftOpc = ARMISD::VQRSHRNs; break; 12259 case Intrinsic::arm_neon_vqrshiftnu: 12260 VShiftOpc = ARMISD::VQRSHRNu; break; 12261 case Intrinsic::arm_neon_vqrshiftnsu: 12262 VShiftOpc = ARMISD::VQRSHRNsu; break; 12263 } 12264 12265 SDLoc dl(N); 12266 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12267 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 12268 } 12269 12270 case Intrinsic::arm_neon_vshiftins: { 12271 EVT VT = N->getOperand(1).getValueType(); 12272 int64_t Cnt; 12273 unsigned VShiftOpc = 0; 12274 12275 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 12276 VShiftOpc = ARMISD::VSLI; 12277 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 12278 VShiftOpc = ARMISD::VSRI; 12279 else { 12280 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 12281 } 12282 12283 SDLoc dl(N); 12284 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12285 N->getOperand(1), N->getOperand(2), 12286 DAG.getConstant(Cnt, dl, MVT::i32)); 12287 } 12288 12289 case Intrinsic::arm_neon_vqrshifts: 12290 case Intrinsic::arm_neon_vqrshiftu: 12291 // No immediate versions of these to check for. 12292 break; 12293 } 12294 12295 return SDValue(); 12296 } 12297 12298 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 12299 /// lowers them. As with the vector shift intrinsics, this is done during DAG 12300 /// combining instead of DAG legalizing because the build_vectors for 64-bit 12301 /// vector element shift counts are generally not legal, and it is hard to see 12302 /// their values after they get legalized to loads from a constant pool. 12303 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 12304 const ARMSubtarget *ST) { 12305 EVT VT = N->getValueType(0); 12306 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 12307 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 12308 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 12309 SDValue N1 = N->getOperand(1); 12310 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12311 SDValue N0 = N->getOperand(0); 12312 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 12313 DAG.MaskedValueIsZero(N0.getOperand(0), 12314 APInt::getHighBitsSet(32, 16))) 12315 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 12316 } 12317 } 12318 12319 // Nothing to be done for scalar shifts. 12320 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12321 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 12322 return SDValue(); 12323 12324 assert(ST->hasNEON() && "unexpected vector shift"); 12325 int64_t Cnt; 12326 12327 switch (N->getOpcode()) { 12328 default: llvm_unreachable("unexpected shift opcode"); 12329 12330 case ISD::SHL: 12331 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 12332 SDLoc dl(N); 12333 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 12334 DAG.getConstant(Cnt, dl, MVT::i32)); 12335 } 12336 break; 12337 12338 case ISD::SRA: 12339 case ISD::SRL: 12340 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 12341 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 12342 ARMISD::VSHRs : ARMISD::VSHRu); 12343 SDLoc dl(N); 12344 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 12345 DAG.getConstant(Cnt, dl, MVT::i32)); 12346 } 12347 } 12348 return SDValue(); 12349 } 12350 12351 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 12352 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 12353 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 12354 const ARMSubtarget *ST) { 12355 SDValue N0 = N->getOperand(0); 12356 12357 // Check for sign- and zero-extensions of vector extract operations of 8- 12358 // and 16-bit vector elements. NEON supports these directly. They are 12359 // handled during DAG combining because type legalization will promote them 12360 // to 32-bit types and it is messy to recognize the operations after that. 12361 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12362 SDValue Vec = N0.getOperand(0); 12363 SDValue Lane = N0.getOperand(1); 12364 EVT VT = N->getValueType(0); 12365 EVT EltVT = N0.getValueType(); 12366 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12367 12368 if (VT == MVT::i32 && 12369 (EltVT == MVT::i8 || EltVT == MVT::i16) && 12370 TLI.isTypeLegal(Vec.getValueType()) && 12371 isa<ConstantSDNode>(Lane)) { 12372 12373 unsigned Opc = 0; 12374 switch (N->getOpcode()) { 12375 default: llvm_unreachable("unexpected opcode"); 12376 case ISD::SIGN_EXTEND: 12377 Opc = ARMISD::VGETLANEs; 12378 break; 12379 case ISD::ZERO_EXTEND: 12380 case ISD::ANY_EXTEND: 12381 Opc = ARMISD::VGETLANEu; 12382 break; 12383 } 12384 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 12385 } 12386 } 12387 12388 return SDValue(); 12389 } 12390 12391 static const APInt *isPowerOf2Constant(SDValue V) { 12392 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 12393 if (!C) 12394 return nullptr; 12395 const APInt *CV = &C->getAPIntValue(); 12396 return CV->isPowerOf2() ? CV : nullptr; 12397 } 12398 12399 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 12400 // If we have a CMOV, OR and AND combination such as: 12401 // if (x & CN) 12402 // y |= CM; 12403 // 12404 // And: 12405 // * CN is a single bit; 12406 // * All bits covered by CM are known zero in y 12407 // 12408 // Then we can convert this into a sequence of BFI instructions. This will 12409 // always be a win if CM is a single bit, will always be no worse than the 12410 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 12411 // three bits (due to the extra IT instruction). 12412 12413 SDValue Op0 = CMOV->getOperand(0); 12414 SDValue Op1 = CMOV->getOperand(1); 12415 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 12416 auto CC = CCNode->getAPIntValue().getLimitedValue(); 12417 SDValue CmpZ = CMOV->getOperand(4); 12418 12419 // The compare must be against zero. 12420 if (!isNullConstant(CmpZ->getOperand(1))) 12421 return SDValue(); 12422 12423 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 12424 SDValue And = CmpZ->getOperand(0); 12425 if (And->getOpcode() != ISD::AND) 12426 return SDValue(); 12427 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 12428 if (!AndC) 12429 return SDValue(); 12430 SDValue X = And->getOperand(0); 12431 12432 if (CC == ARMCC::EQ) { 12433 // We're performing an "equal to zero" compare. Swap the operands so we 12434 // canonicalize on a "not equal to zero" compare. 12435 std::swap(Op0, Op1); 12436 } else { 12437 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 12438 } 12439 12440 if (Op1->getOpcode() != ISD::OR) 12441 return SDValue(); 12442 12443 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 12444 if (!OrC) 12445 return SDValue(); 12446 SDValue Y = Op1->getOperand(0); 12447 12448 if (Op0 != Y) 12449 return SDValue(); 12450 12451 // Now, is it profitable to continue? 12452 APInt OrCI = OrC->getAPIntValue(); 12453 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 12454 if (OrCI.countPopulation() > Heuristic) 12455 return SDValue(); 12456 12457 // Lastly, can we determine that the bits defined by OrCI 12458 // are zero in Y? 12459 KnownBits Known; 12460 DAG.computeKnownBits(Y, Known); 12461 if ((OrCI & Known.Zero) != OrCI) 12462 return SDValue(); 12463 12464 // OK, we can do the combine. 12465 SDValue V = Y; 12466 SDLoc dl(X); 12467 EVT VT = X.getValueType(); 12468 unsigned BitInX = AndC->logBase2(); 12469 12470 if (BitInX != 0) { 12471 // We must shift X first. 12472 X = DAG.getNode(ISD::SRL, dl, VT, X, 12473 DAG.getConstant(BitInX, dl, VT)); 12474 } 12475 12476 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 12477 BitInY < NumActiveBits; ++BitInY) { 12478 if (OrCI[BitInY] == 0) 12479 continue; 12480 APInt Mask(VT.getSizeInBits(), 0); 12481 Mask.setBit(BitInY); 12482 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 12483 // Confusingly, the operand is an *inverted* mask. 12484 DAG.getConstant(~Mask, dl, VT)); 12485 } 12486 12487 return V; 12488 } 12489 12490 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 12491 SDValue 12492 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 12493 SDValue Cmp = N->getOperand(4); 12494 if (Cmp.getOpcode() != ARMISD::CMPZ) 12495 // Only looking at NE cases. 12496 return SDValue(); 12497 12498 EVT VT = N->getValueType(0); 12499 SDLoc dl(N); 12500 SDValue LHS = Cmp.getOperand(0); 12501 SDValue RHS = Cmp.getOperand(1); 12502 SDValue Chain = N->getOperand(0); 12503 SDValue BB = N->getOperand(1); 12504 SDValue ARMcc = N->getOperand(2); 12505 ARMCC::CondCodes CC = 12506 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12507 12508 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 12509 // -> (brcond Chain BB CC CPSR Cmp) 12510 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 12511 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 12512 LHS->getOperand(0)->hasOneUse()) { 12513 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 12514 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 12515 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12516 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12517 if ((LHS00C && LHS00C->getZExtValue() == 0) && 12518 (LHS01C && LHS01C->getZExtValue() == 1) && 12519 (LHS1C && LHS1C->getZExtValue() == 1) && 12520 (RHSC && RHSC->getZExtValue() == 0)) { 12521 return DAG.getNode( 12522 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 12523 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 12524 } 12525 } 12526 12527 return SDValue(); 12528 } 12529 12530 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 12531 SDValue 12532 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 12533 SDValue Cmp = N->getOperand(4); 12534 if (Cmp.getOpcode() != ARMISD::CMPZ) 12535 // Only looking at EQ and NE cases. 12536 return SDValue(); 12537 12538 EVT VT = N->getValueType(0); 12539 SDLoc dl(N); 12540 SDValue LHS = Cmp.getOperand(0); 12541 SDValue RHS = Cmp.getOperand(1); 12542 SDValue FalseVal = N->getOperand(0); 12543 SDValue TrueVal = N->getOperand(1); 12544 SDValue ARMcc = N->getOperand(2); 12545 ARMCC::CondCodes CC = 12546 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12547 12548 // BFI is only available on V6T2+. 12549 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 12550 SDValue R = PerformCMOVToBFICombine(N, DAG); 12551 if (R) 12552 return R; 12553 } 12554 12555 // Simplify 12556 // mov r1, r0 12557 // cmp r1, x 12558 // mov r0, y 12559 // moveq r0, x 12560 // to 12561 // cmp r0, x 12562 // movne r0, y 12563 // 12564 // mov r1, r0 12565 // cmp r1, x 12566 // mov r0, x 12567 // movne r0, y 12568 // to 12569 // cmp r0, x 12570 // movne r0, y 12571 /// FIXME: Turn this into a target neutral optimization? 12572 SDValue Res; 12573 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 12574 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 12575 N->getOperand(3), Cmp); 12576 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 12577 SDValue ARMcc; 12578 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 12579 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 12580 N->getOperand(3), NewCmp); 12581 } 12582 12583 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 12584 // -> (cmov F T CC CPSR Cmp) 12585 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 12586 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 12587 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12588 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12589 if ((LHS0C && LHS0C->getZExtValue() == 0) && 12590 (LHS1C && LHS1C->getZExtValue() == 1) && 12591 (RHSC && RHSC->getZExtValue() == 0)) { 12592 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 12593 LHS->getOperand(2), LHS->getOperand(3), 12594 LHS->getOperand(4)); 12595 } 12596 } 12597 12598 if (!VT.isInteger()) 12599 return SDValue(); 12600 12601 // Materialize a boolean comparison for integers so we can avoid branching. 12602 if (isNullConstant(FalseVal)) { 12603 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 12604 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 12605 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 12606 // right 5 bits will make that 32 be 1, otherwise it will be 0. 12607 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 12608 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12609 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 12610 DAG.getConstant(5, dl, MVT::i32)); 12611 } else { 12612 // CMOV 0, 1, ==, (CMPZ x, y) -> 12613 // (ADDCARRY (SUB x, y), t:0, t:1) 12614 // where t = (SUBCARRY 0, (SUB x, y), 0) 12615 // 12616 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 12617 // x != y. In other words, a carry C == 1 when x == y, C == 0 12618 // otherwise. 12619 // The final ADDCARRY computes 12620 // x - y + (0 - (x - y)) + C == C 12621 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12622 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12623 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 12624 // ISD::SUBCARRY returns a borrow but we want the carry here 12625 // actually. 12626 SDValue Carry = 12627 DAG.getNode(ISD::SUB, dl, MVT::i32, 12628 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 12629 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 12630 } 12631 } else if (CC == ARMCC::NE && LHS != RHS && 12632 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 12633 // This seems pointless but will allow us to combine it further below. 12634 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUB x, y), z, !=, (CMPZ x, y) 12635 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12636 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 12637 N->getOperand(3), Cmp); 12638 } 12639 } else if (isNullConstant(TrueVal)) { 12640 if (CC == ARMCC::EQ && LHS != RHS && 12641 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 12642 // This seems pointless but will allow us to combine it further below 12643 // Note that we change == for != as this is the dual for the case above. 12644 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUB x, y), z, !=, (CMPZ x, y) 12645 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12646 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 12647 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 12648 N->getOperand(3), Cmp); 12649 } 12650 } 12651 12652 // On Thumb1, the DAG above may be further combined if z is a power of 2 12653 // (z == 2 ^ K). 12654 // CMOV (SUB x, y), z, !=, (CMPZ x, y) -> 12655 // merge t3, t4 12656 // where t1 = (SUBCARRY (SUB x, y), z, 0) 12657 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 12658 // t3 = if K != 0 then (SHL t2:0, K) else t2:0 12659 // t4 = (SUB 1, t2:1) [ we want a carry, not a borrow ] 12660 const APInt *TrueConst; 12661 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 12662 (FalseVal.getOpcode() == ISD::SUB) && (FalseVal.getOperand(0) == LHS) && 12663 (FalseVal.getOperand(1) == RHS) && 12664 (TrueConst = isPowerOf2Constant(TrueVal))) { 12665 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12666 unsigned ShiftAmount = TrueConst->logBase2(); 12667 if (ShiftAmount) 12668 TrueVal = DAG.getConstant(1, dl, VT); 12669 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 12670 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 12671 // Make it a carry, not a borrow. 12672 SDValue Carry = DAG.getNode( 12673 ISD::SUB, dl, VT, DAG.getConstant(1, dl, MVT::i32), Res.getValue(1)); 12674 Res = DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Res, Carry); 12675 12676 if (ShiftAmount) 12677 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 12678 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 12679 } 12680 12681 if (Res.getNode()) { 12682 KnownBits Known; 12683 DAG.computeKnownBits(SDValue(N,0), Known); 12684 // Capture demanded bits information that would be otherwise lost. 12685 if (Known.Zero == 0xfffffffe) 12686 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12687 DAG.getValueType(MVT::i1)); 12688 else if (Known.Zero == 0xffffff00) 12689 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12690 DAG.getValueType(MVT::i8)); 12691 else if (Known.Zero == 0xffff0000) 12692 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12693 DAG.getValueType(MVT::i16)); 12694 } 12695 12696 return Res; 12697 } 12698 12699 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 12700 DAGCombinerInfo &DCI) const { 12701 switch (N->getOpcode()) { 12702 default: break; 12703 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 12704 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 12705 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 12706 case ISD::SUB: return PerformSUBCombine(N, DCI); 12707 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 12708 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 12709 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 12710 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 12711 case ARMISD::ADDC: 12712 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 12713 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 12714 case ARMISD::BFI: return PerformBFICombine(N, DCI); 12715 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 12716 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 12717 case ISD::STORE: return PerformSTORECombine(N, DCI); 12718 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 12719 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 12720 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 12721 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 12722 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 12723 case ISD::FP_TO_SINT: 12724 case ISD::FP_TO_UINT: 12725 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 12726 case ISD::FDIV: 12727 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 12728 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 12729 case ISD::SHL: 12730 case ISD::SRA: 12731 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 12732 case ISD::SIGN_EXTEND: 12733 case ISD::ZERO_EXTEND: 12734 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 12735 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 12736 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 12737 case ISD::LOAD: return PerformLOADCombine(N, DCI); 12738 case ARMISD::VLD1DUP: 12739 case ARMISD::VLD2DUP: 12740 case ARMISD::VLD3DUP: 12741 case ARMISD::VLD4DUP: 12742 return PerformVLDCombine(N, DCI); 12743 case ARMISD::BUILD_VECTOR: 12744 return PerformARMBUILD_VECTORCombine(N, DCI); 12745 case ARMISD::SMULWB: { 12746 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12747 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12748 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12749 return SDValue(); 12750 break; 12751 } 12752 case ARMISD::SMULWT: { 12753 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12754 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12755 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12756 return SDValue(); 12757 break; 12758 } 12759 case ARMISD::SMLALBB: { 12760 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12761 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12762 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12763 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12764 return SDValue(); 12765 break; 12766 } 12767 case ARMISD::SMLALBT: { 12768 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 12769 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12770 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 12771 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12772 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 12773 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12774 return SDValue(); 12775 break; 12776 } 12777 case ARMISD::SMLALTB: { 12778 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12779 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12780 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12781 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12782 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12783 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12784 return SDValue(); 12785 break; 12786 } 12787 case ARMISD::SMLALTT: { 12788 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12789 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12790 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12791 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12792 return SDValue(); 12793 break; 12794 } 12795 case ISD::INTRINSIC_VOID: 12796 case ISD::INTRINSIC_W_CHAIN: 12797 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12798 case Intrinsic::arm_neon_vld1: 12799 case Intrinsic::arm_neon_vld2: 12800 case Intrinsic::arm_neon_vld3: 12801 case Intrinsic::arm_neon_vld4: 12802 case Intrinsic::arm_neon_vld2lane: 12803 case Intrinsic::arm_neon_vld3lane: 12804 case Intrinsic::arm_neon_vld4lane: 12805 case Intrinsic::arm_neon_vst1: 12806 case Intrinsic::arm_neon_vst2: 12807 case Intrinsic::arm_neon_vst3: 12808 case Intrinsic::arm_neon_vst4: 12809 case Intrinsic::arm_neon_vst2lane: 12810 case Intrinsic::arm_neon_vst3lane: 12811 case Intrinsic::arm_neon_vst4lane: 12812 return PerformVLDCombine(N, DCI); 12813 default: break; 12814 } 12815 break; 12816 } 12817 return SDValue(); 12818 } 12819 12820 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 12821 EVT VT) const { 12822 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 12823 } 12824 12825 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12826 unsigned, 12827 unsigned, 12828 bool *Fast) const { 12829 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 12830 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 12831 12832 switch (VT.getSimpleVT().SimpleTy) { 12833 default: 12834 return false; 12835 case MVT::i8: 12836 case MVT::i16: 12837 case MVT::i32: { 12838 // Unaligned access can use (for example) LRDB, LRDH, LDR 12839 if (AllowsUnaligned) { 12840 if (Fast) 12841 *Fast = Subtarget->hasV7Ops(); 12842 return true; 12843 } 12844 return false; 12845 } 12846 case MVT::f64: 12847 case MVT::v2f64: { 12848 // For any little-endian targets with neon, we can support unaligned ld/st 12849 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 12850 // A big-endian target may also explicitly support unaligned accesses 12851 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 12852 if (Fast) 12853 *Fast = true; 12854 return true; 12855 } 12856 return false; 12857 } 12858 } 12859 } 12860 12861 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 12862 unsigned AlignCheck) { 12863 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 12864 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 12865 } 12866 12867 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 12868 unsigned DstAlign, unsigned SrcAlign, 12869 bool IsMemset, bool ZeroMemset, 12870 bool MemcpyStrSrc, 12871 MachineFunction &MF) const { 12872 const Function &F = MF.getFunction(); 12873 12874 // See if we can use NEON instructions for this... 12875 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 12876 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 12877 bool Fast; 12878 if (Size >= 16 && 12879 (memOpAlign(SrcAlign, DstAlign, 16) || 12880 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 12881 return MVT::v2f64; 12882 } else if (Size >= 8 && 12883 (memOpAlign(SrcAlign, DstAlign, 8) || 12884 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 12885 Fast))) { 12886 return MVT::f64; 12887 } 12888 } 12889 12890 // Let the target-independent logic figure it out. 12891 return MVT::Other; 12892 } 12893 12894 // 64-bit integers are split into their high and low parts and held in two 12895 // different registers, so the trunc is free since the low register can just 12896 // be used. 12897 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 12898 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 12899 return false; 12900 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 12901 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 12902 return (SrcBits == 64 && DestBits == 32); 12903 } 12904 12905 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 12906 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 12907 !DstVT.isInteger()) 12908 return false; 12909 unsigned SrcBits = SrcVT.getSizeInBits(); 12910 unsigned DestBits = DstVT.getSizeInBits(); 12911 return (SrcBits == 64 && DestBits == 32); 12912 } 12913 12914 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12915 if (Val.getOpcode() != ISD::LOAD) 12916 return false; 12917 12918 EVT VT1 = Val.getValueType(); 12919 if (!VT1.isSimple() || !VT1.isInteger() || 12920 !VT2.isSimple() || !VT2.isInteger()) 12921 return false; 12922 12923 switch (VT1.getSimpleVT().SimpleTy) { 12924 default: break; 12925 case MVT::i1: 12926 case MVT::i8: 12927 case MVT::i16: 12928 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 12929 return true; 12930 } 12931 12932 return false; 12933 } 12934 12935 bool ARMTargetLowering::isFNegFree(EVT VT) const { 12936 if (!VT.isSimple()) 12937 return false; 12938 12939 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 12940 // negate values directly (fneg is free). So, we don't want to let the DAG 12941 // combiner rewrite fneg into xors and some other instructions. For f16 and 12942 // FullFP16 argument passing, some bitcast nodes may be introduced, 12943 // triggering this DAG combine rewrite, so we are avoiding that with this. 12944 switch (VT.getSimpleVT().SimpleTy) { 12945 default: break; 12946 case MVT::f16: 12947 return Subtarget->hasFullFP16(); 12948 } 12949 12950 return false; 12951 } 12952 12953 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 12954 EVT VT = ExtVal.getValueType(); 12955 12956 if (!isTypeLegal(VT)) 12957 return false; 12958 12959 // Don't create a loadext if we can fold the extension into a wide/long 12960 // instruction. 12961 // If there's more than one user instruction, the loadext is desirable no 12962 // matter what. There can be two uses by the same instruction. 12963 if (ExtVal->use_empty() || 12964 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 12965 return true; 12966 12967 SDNode *U = *ExtVal->use_begin(); 12968 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 12969 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 12970 return false; 12971 12972 return true; 12973 } 12974 12975 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 12976 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12977 return false; 12978 12979 if (!isTypeLegal(EVT::getEVT(Ty1))) 12980 return false; 12981 12982 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 12983 12984 // Assuming the caller doesn't have a zeroext or signext return parameter, 12985 // truncation all the way down to i1 is valid. 12986 return true; 12987 } 12988 12989 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 12990 const AddrMode &AM, Type *Ty, 12991 unsigned AS) const { 12992 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 12993 if (Subtarget->hasFPAO()) 12994 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 12995 return 0; 12996 } 12997 return -1; 12998 } 12999 13000 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 13001 if (V < 0) 13002 return false; 13003 13004 unsigned Scale = 1; 13005 switch (VT.getSimpleVT().SimpleTy) { 13006 default: return false; 13007 case MVT::i1: 13008 case MVT::i8: 13009 // Scale == 1; 13010 break; 13011 case MVT::i16: 13012 // Scale == 2; 13013 Scale = 2; 13014 break; 13015 case MVT::i32: 13016 // Scale == 4; 13017 Scale = 4; 13018 break; 13019 } 13020 13021 if ((V & (Scale - 1)) != 0) 13022 return false; 13023 V /= Scale; 13024 return V == (V & ((1LL << 5) - 1)); 13025 } 13026 13027 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 13028 const ARMSubtarget *Subtarget) { 13029 bool isNeg = false; 13030 if (V < 0) { 13031 isNeg = true; 13032 V = - V; 13033 } 13034 13035 switch (VT.getSimpleVT().SimpleTy) { 13036 default: return false; 13037 case MVT::i1: 13038 case MVT::i8: 13039 case MVT::i16: 13040 case MVT::i32: 13041 // + imm12 or - imm8 13042 if (isNeg) 13043 return V == (V & ((1LL << 8) - 1)); 13044 return V == (V & ((1LL << 12) - 1)); 13045 case MVT::f32: 13046 case MVT::f64: 13047 // Same as ARM mode. FIXME: NEON? 13048 if (!Subtarget->hasVFP2()) 13049 return false; 13050 if ((V & 3) != 0) 13051 return false; 13052 V >>= 2; 13053 return V == (V & ((1LL << 8) - 1)); 13054 } 13055 } 13056 13057 /// isLegalAddressImmediate - Return true if the integer value can be used 13058 /// as the offset of the target addressing mode for load / store of the 13059 /// given type. 13060 static bool isLegalAddressImmediate(int64_t V, EVT VT, 13061 const ARMSubtarget *Subtarget) { 13062 if (V == 0) 13063 return true; 13064 13065 if (!VT.isSimple()) 13066 return false; 13067 13068 if (Subtarget->isThumb1Only()) 13069 return isLegalT1AddressImmediate(V, VT); 13070 else if (Subtarget->isThumb2()) 13071 return isLegalT2AddressImmediate(V, VT, Subtarget); 13072 13073 // ARM mode. 13074 if (V < 0) 13075 V = - V; 13076 switch (VT.getSimpleVT().SimpleTy) { 13077 default: return false; 13078 case MVT::i1: 13079 case MVT::i8: 13080 case MVT::i32: 13081 // +- imm12 13082 return V == (V & ((1LL << 12) - 1)); 13083 case MVT::i16: 13084 // +- imm8 13085 return V == (V & ((1LL << 8) - 1)); 13086 case MVT::f32: 13087 case MVT::f64: 13088 if (!Subtarget->hasVFP2()) // FIXME: NEON? 13089 return false; 13090 if ((V & 3) != 0) 13091 return false; 13092 V >>= 2; 13093 return V == (V & ((1LL << 8) - 1)); 13094 } 13095 } 13096 13097 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 13098 EVT VT) const { 13099 int Scale = AM.Scale; 13100 if (Scale < 0) 13101 return false; 13102 13103 switch (VT.getSimpleVT().SimpleTy) { 13104 default: return false; 13105 case MVT::i1: 13106 case MVT::i8: 13107 case MVT::i16: 13108 case MVT::i32: 13109 if (Scale == 1) 13110 return true; 13111 // r + r << imm 13112 Scale = Scale & ~1; 13113 return Scale == 2 || Scale == 4 || Scale == 8; 13114 case MVT::i64: 13115 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 13116 // version in Thumb mode. 13117 // r + r 13118 if (Scale == 1) 13119 return true; 13120 // r * 2 (this can be lowered to r + r). 13121 if (!AM.HasBaseReg && Scale == 2) 13122 return true; 13123 return false; 13124 case MVT::isVoid: 13125 // Note, we allow "void" uses (basically, uses that aren't loads or 13126 // stores), because arm allows folding a scale into many arithmetic 13127 // operations. This should be made more precise and revisited later. 13128 13129 // Allow r << imm, but the imm has to be a multiple of two. 13130 if (Scale & 1) return false; 13131 return isPowerOf2_32(Scale); 13132 } 13133 } 13134 13135 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 13136 EVT VT) const { 13137 const int Scale = AM.Scale; 13138 13139 // Negative scales are not supported in Thumb1. 13140 if (Scale < 0) 13141 return false; 13142 13143 // Thumb1 addressing modes do not support register scaling excepting the 13144 // following cases: 13145 // 1. Scale == 1 means no scaling. 13146 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 13147 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 13148 } 13149 13150 /// isLegalAddressingMode - Return true if the addressing mode represented 13151 /// by AM is legal for this target, for a load/store of the specified type. 13152 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13153 const AddrMode &AM, Type *Ty, 13154 unsigned AS, Instruction *I) const { 13155 EVT VT = getValueType(DL, Ty, true); 13156 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 13157 return false; 13158 13159 // Can never fold addr of global into load/store. 13160 if (AM.BaseGV) 13161 return false; 13162 13163 switch (AM.Scale) { 13164 case 0: // no scale reg, must be "r+i" or "r", or "i". 13165 break; 13166 default: 13167 // ARM doesn't support any R+R*scale+imm addr modes. 13168 if (AM.BaseOffs) 13169 return false; 13170 13171 if (!VT.isSimple()) 13172 return false; 13173 13174 if (Subtarget->isThumb1Only()) 13175 return isLegalT1ScaledAddressingMode(AM, VT); 13176 13177 if (Subtarget->isThumb2()) 13178 return isLegalT2ScaledAddressingMode(AM, VT); 13179 13180 int Scale = AM.Scale; 13181 switch (VT.getSimpleVT().SimpleTy) { 13182 default: return false; 13183 case MVT::i1: 13184 case MVT::i8: 13185 case MVT::i32: 13186 if (Scale < 0) Scale = -Scale; 13187 if (Scale == 1) 13188 return true; 13189 // r + r << imm 13190 return isPowerOf2_32(Scale & ~1); 13191 case MVT::i16: 13192 case MVT::i64: 13193 // r +/- r 13194 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 13195 return true; 13196 // r * 2 (this can be lowered to r + r). 13197 if (!AM.HasBaseReg && Scale == 2) 13198 return true; 13199 return false; 13200 13201 case MVT::isVoid: 13202 // Note, we allow "void" uses (basically, uses that aren't loads or 13203 // stores), because arm allows folding a scale into many arithmetic 13204 // operations. This should be made more precise and revisited later. 13205 13206 // Allow r << imm, but the imm has to be a multiple of two. 13207 if (Scale & 1) return false; 13208 return isPowerOf2_32(Scale); 13209 } 13210 } 13211 return true; 13212 } 13213 13214 /// isLegalICmpImmediate - Return true if the specified immediate is legal 13215 /// icmp immediate, that is the target has icmp instructions which can compare 13216 /// a register against the immediate without having to materialize the 13217 /// immediate into a register. 13218 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13219 // Thumb2 and ARM modes can use cmn for negative immediates. 13220 if (!Subtarget->isThumb()) 13221 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 13222 if (Subtarget->isThumb2()) 13223 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 13224 // Thumb1 doesn't have cmn, and only 8-bit immediates. 13225 return Imm >= 0 && Imm <= 255; 13226 } 13227 13228 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 13229 /// *or sub* immediate, that is the target has add or sub instructions which can 13230 /// add a register with the immediate without having to materialize the 13231 /// immediate into a register. 13232 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13233 // Same encoding for add/sub, just flip the sign. 13234 int64_t AbsImm = std::abs(Imm); 13235 if (!Subtarget->isThumb()) 13236 return ARM_AM::getSOImmVal(AbsImm) != -1; 13237 if (Subtarget->isThumb2()) 13238 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 13239 // Thumb1 only has 8-bit unsigned immediate. 13240 return AbsImm >= 0 && AbsImm <= 255; 13241 } 13242 13243 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 13244 bool isSEXTLoad, SDValue &Base, 13245 SDValue &Offset, bool &isInc, 13246 SelectionDAG &DAG) { 13247 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13248 return false; 13249 13250 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 13251 // AddressingMode 3 13252 Base = Ptr->getOperand(0); 13253 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13254 int RHSC = (int)RHS->getZExtValue(); 13255 if (RHSC < 0 && RHSC > -256) { 13256 assert(Ptr->getOpcode() == ISD::ADD); 13257 isInc = false; 13258 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13259 return true; 13260 } 13261 } 13262 isInc = (Ptr->getOpcode() == ISD::ADD); 13263 Offset = Ptr->getOperand(1); 13264 return true; 13265 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 13266 // AddressingMode 2 13267 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13268 int RHSC = (int)RHS->getZExtValue(); 13269 if (RHSC < 0 && RHSC > -0x1000) { 13270 assert(Ptr->getOpcode() == ISD::ADD); 13271 isInc = false; 13272 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13273 Base = Ptr->getOperand(0); 13274 return true; 13275 } 13276 } 13277 13278 if (Ptr->getOpcode() == ISD::ADD) { 13279 isInc = true; 13280 ARM_AM::ShiftOpc ShOpcVal= 13281 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 13282 if (ShOpcVal != ARM_AM::no_shift) { 13283 Base = Ptr->getOperand(1); 13284 Offset = Ptr->getOperand(0); 13285 } else { 13286 Base = Ptr->getOperand(0); 13287 Offset = Ptr->getOperand(1); 13288 } 13289 return true; 13290 } 13291 13292 isInc = (Ptr->getOpcode() == ISD::ADD); 13293 Base = Ptr->getOperand(0); 13294 Offset = Ptr->getOperand(1); 13295 return true; 13296 } 13297 13298 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 13299 return false; 13300 } 13301 13302 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 13303 bool isSEXTLoad, SDValue &Base, 13304 SDValue &Offset, bool &isInc, 13305 SelectionDAG &DAG) { 13306 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13307 return false; 13308 13309 Base = Ptr->getOperand(0); 13310 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13311 int RHSC = (int)RHS->getZExtValue(); 13312 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 13313 assert(Ptr->getOpcode() == ISD::ADD); 13314 isInc = false; 13315 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13316 return true; 13317 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 13318 isInc = Ptr->getOpcode() == ISD::ADD; 13319 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13320 return true; 13321 } 13322 } 13323 13324 return false; 13325 } 13326 13327 /// getPreIndexedAddressParts - returns true by value, base pointer and 13328 /// offset pointer and addressing mode by reference if the node's address 13329 /// can be legally represented as pre-indexed load / store address. 13330 bool 13331 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 13332 SDValue &Offset, 13333 ISD::MemIndexedMode &AM, 13334 SelectionDAG &DAG) const { 13335 if (Subtarget->isThumb1Only()) 13336 return false; 13337 13338 EVT VT; 13339 SDValue Ptr; 13340 bool isSEXTLoad = false; 13341 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13342 Ptr = LD->getBasePtr(); 13343 VT = LD->getMemoryVT(); 13344 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13345 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13346 Ptr = ST->getBasePtr(); 13347 VT = ST->getMemoryVT(); 13348 } else 13349 return false; 13350 13351 bool isInc; 13352 bool isLegal = false; 13353 if (Subtarget->isThumb2()) 13354 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13355 Offset, isInc, DAG); 13356 else 13357 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13358 Offset, isInc, DAG); 13359 if (!isLegal) 13360 return false; 13361 13362 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 13363 return true; 13364 } 13365 13366 /// getPostIndexedAddressParts - returns true by value, base pointer and 13367 /// offset pointer and addressing mode by reference if this node can be 13368 /// combined with a load / store to form a post-indexed load / store. 13369 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 13370 SDValue &Base, 13371 SDValue &Offset, 13372 ISD::MemIndexedMode &AM, 13373 SelectionDAG &DAG) const { 13374 EVT VT; 13375 SDValue Ptr; 13376 bool isSEXTLoad = false, isNonExt; 13377 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13378 VT = LD->getMemoryVT(); 13379 Ptr = LD->getBasePtr(); 13380 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13381 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 13382 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13383 VT = ST->getMemoryVT(); 13384 Ptr = ST->getBasePtr(); 13385 isNonExt = !ST->isTruncatingStore(); 13386 } else 13387 return false; 13388 13389 if (Subtarget->isThumb1Only()) { 13390 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 13391 // must be non-extending/truncating, i32, with an offset of 4. 13392 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 13393 if (Op->getOpcode() != ISD::ADD || !isNonExt) 13394 return false; 13395 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 13396 if (!RHS || RHS->getZExtValue() != 4) 13397 return false; 13398 13399 Offset = Op->getOperand(1); 13400 Base = Op->getOperand(0); 13401 AM = ISD::POST_INC; 13402 return true; 13403 } 13404 13405 bool isInc; 13406 bool isLegal = false; 13407 if (Subtarget->isThumb2()) 13408 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13409 isInc, DAG); 13410 else 13411 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13412 isInc, DAG); 13413 if (!isLegal) 13414 return false; 13415 13416 if (Ptr != Base) { 13417 // Swap base ptr and offset to catch more post-index load / store when 13418 // it's legal. In Thumb2 mode, offset must be an immediate. 13419 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 13420 !Subtarget->isThumb2()) 13421 std::swap(Base, Offset); 13422 13423 // Post-indexed load / store update the base pointer. 13424 if (Ptr != Base) 13425 return false; 13426 } 13427 13428 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 13429 return true; 13430 } 13431 13432 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13433 KnownBits &Known, 13434 const APInt &DemandedElts, 13435 const SelectionDAG &DAG, 13436 unsigned Depth) const { 13437 unsigned BitWidth = Known.getBitWidth(); 13438 Known.resetAll(); 13439 switch (Op.getOpcode()) { 13440 default: break; 13441 case ARMISD::ADDC: 13442 case ARMISD::ADDE: 13443 case ARMISD::SUBC: 13444 case ARMISD::SUBE: 13445 // Special cases when we convert a carry to a boolean. 13446 if (Op.getResNo() == 0) { 13447 SDValue LHS = Op.getOperand(0); 13448 SDValue RHS = Op.getOperand(1); 13449 // (ADDE 0, 0, C) will give us a single bit. 13450 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 13451 isNullConstant(RHS)) { 13452 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 13453 return; 13454 } 13455 } 13456 break; 13457 case ARMISD::CMOV: { 13458 // Bits are known zero/one if known on the LHS and RHS. 13459 DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1); 13460 if (Known.isUnknown()) 13461 return; 13462 13463 KnownBits KnownRHS; 13464 DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1); 13465 Known.Zero &= KnownRHS.Zero; 13466 Known.One &= KnownRHS.One; 13467 return; 13468 } 13469 case ISD::INTRINSIC_W_CHAIN: { 13470 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 13471 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 13472 switch (IntID) { 13473 default: return; 13474 case Intrinsic::arm_ldaex: 13475 case Intrinsic::arm_ldrex: { 13476 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 13477 unsigned MemBits = VT.getScalarSizeInBits(); 13478 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 13479 return; 13480 } 13481 } 13482 } 13483 case ARMISD::BFI: { 13484 // Conservatively, we can recurse down the first operand 13485 // and just mask out all affected bits. 13486 DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1); 13487 13488 // The operand to BFI is already a mask suitable for removing the bits it 13489 // sets. 13490 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 13491 const APInt &Mask = CI->getAPIntValue(); 13492 Known.Zero &= Mask; 13493 Known.One &= Mask; 13494 return; 13495 } 13496 } 13497 } 13498 13499 //===----------------------------------------------------------------------===// 13500 // ARM Inline Assembly Support 13501 //===----------------------------------------------------------------------===// 13502 13503 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 13504 // Looking for "rev" which is V6+. 13505 if (!Subtarget->hasV6Ops()) 13506 return false; 13507 13508 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 13509 std::string AsmStr = IA->getAsmString(); 13510 SmallVector<StringRef, 4> AsmPieces; 13511 SplitString(AsmStr, AsmPieces, ";\n"); 13512 13513 switch (AsmPieces.size()) { 13514 default: return false; 13515 case 1: 13516 AsmStr = AsmPieces[0]; 13517 AsmPieces.clear(); 13518 SplitString(AsmStr, AsmPieces, " \t,"); 13519 13520 // rev $0, $1 13521 if (AsmPieces.size() == 3 && 13522 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 13523 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 13524 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 13525 if (Ty && Ty->getBitWidth() == 32) 13526 return IntrinsicLowering::LowerToByteSwap(CI); 13527 } 13528 break; 13529 } 13530 13531 return false; 13532 } 13533 13534 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 13535 // At this point, we have to lower this constraint to something else, so we 13536 // lower it to an "r" or "w". However, by doing this we will force the result 13537 // to be in register, while the X constraint is much more permissive. 13538 // 13539 // Although we are correct (we are free to emit anything, without 13540 // constraints), we might break use cases that would expect us to be more 13541 // efficient and emit something else. 13542 if (!Subtarget->hasVFP2()) 13543 return "r"; 13544 if (ConstraintVT.isFloatingPoint()) 13545 return "w"; 13546 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 13547 (ConstraintVT.getSizeInBits() == 64 || 13548 ConstraintVT.getSizeInBits() == 128)) 13549 return "w"; 13550 13551 return "r"; 13552 } 13553 13554 /// getConstraintType - Given a constraint letter, return the type of 13555 /// constraint it is for this target. 13556 ARMTargetLowering::ConstraintType 13557 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 13558 if (Constraint.size() == 1) { 13559 switch (Constraint[0]) { 13560 default: break; 13561 case 'l': return C_RegisterClass; 13562 case 'w': return C_RegisterClass; 13563 case 'h': return C_RegisterClass; 13564 case 'x': return C_RegisterClass; 13565 case 't': return C_RegisterClass; 13566 case 'j': return C_Other; // Constant for movw. 13567 // An address with a single base register. Due to the way we 13568 // currently handle addresses it is the same as an 'r' memory constraint. 13569 case 'Q': return C_Memory; 13570 } 13571 } else if (Constraint.size() == 2) { 13572 switch (Constraint[0]) { 13573 default: break; 13574 // All 'U+' constraints are addresses. 13575 case 'U': return C_Memory; 13576 } 13577 } 13578 return TargetLowering::getConstraintType(Constraint); 13579 } 13580 13581 /// Examine constraint type and operand type and determine a weight value. 13582 /// This object must already have been set up with the operand type 13583 /// and the current alternative constraint selected. 13584 TargetLowering::ConstraintWeight 13585 ARMTargetLowering::getSingleConstraintMatchWeight( 13586 AsmOperandInfo &info, const char *constraint) const { 13587 ConstraintWeight weight = CW_Invalid; 13588 Value *CallOperandVal = info.CallOperandVal; 13589 // If we don't have a value, we can't do a match, 13590 // but allow it at the lowest weight. 13591 if (!CallOperandVal) 13592 return CW_Default; 13593 Type *type = CallOperandVal->getType(); 13594 // Look at the constraint type. 13595 switch (*constraint) { 13596 default: 13597 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13598 break; 13599 case 'l': 13600 if (type->isIntegerTy()) { 13601 if (Subtarget->isThumb()) 13602 weight = CW_SpecificReg; 13603 else 13604 weight = CW_Register; 13605 } 13606 break; 13607 case 'w': 13608 if (type->isFloatingPointTy()) 13609 weight = CW_Register; 13610 break; 13611 } 13612 return weight; 13613 } 13614 13615 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 13616 13617 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 13618 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 13619 if (Constraint.size() == 1) { 13620 // GCC ARM Constraint Letters 13621 switch (Constraint[0]) { 13622 case 'l': // Low regs or general regs. 13623 if (Subtarget->isThumb()) 13624 return RCPair(0U, &ARM::tGPRRegClass); 13625 return RCPair(0U, &ARM::GPRRegClass); 13626 case 'h': // High regs or no regs. 13627 if (Subtarget->isThumb()) 13628 return RCPair(0U, &ARM::hGPRRegClass); 13629 break; 13630 case 'r': 13631 if (Subtarget->isThumb1Only()) 13632 return RCPair(0U, &ARM::tGPRRegClass); 13633 return RCPair(0U, &ARM::GPRRegClass); 13634 case 'w': 13635 if (VT == MVT::Other) 13636 break; 13637 if (VT == MVT::f32) 13638 return RCPair(0U, &ARM::SPRRegClass); 13639 if (VT.getSizeInBits() == 64) 13640 return RCPair(0U, &ARM::DPRRegClass); 13641 if (VT.getSizeInBits() == 128) 13642 return RCPair(0U, &ARM::QPRRegClass); 13643 break; 13644 case 'x': 13645 if (VT == MVT::Other) 13646 break; 13647 if (VT == MVT::f32) 13648 return RCPair(0U, &ARM::SPR_8RegClass); 13649 if (VT.getSizeInBits() == 64) 13650 return RCPair(0U, &ARM::DPR_8RegClass); 13651 if (VT.getSizeInBits() == 128) 13652 return RCPair(0U, &ARM::QPR_8RegClass); 13653 break; 13654 case 't': 13655 if (VT == MVT::Other) 13656 break; 13657 if (VT == MVT::f32 || VT == MVT::i32) 13658 return RCPair(0U, &ARM::SPRRegClass); 13659 if (VT.getSizeInBits() == 64) 13660 return RCPair(0U, &ARM::DPR_VFP2RegClass); 13661 if (VT.getSizeInBits() == 128) 13662 return RCPair(0U, &ARM::QPR_VFP2RegClass); 13663 break; 13664 } 13665 } 13666 if (StringRef("{cc}").equals_lower(Constraint)) 13667 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 13668 13669 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13670 } 13671 13672 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13673 /// vector. If it is invalid, don't add anything to Ops. 13674 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13675 std::string &Constraint, 13676 std::vector<SDValue>&Ops, 13677 SelectionDAG &DAG) const { 13678 SDValue Result; 13679 13680 // Currently only support length 1 constraints. 13681 if (Constraint.length() != 1) return; 13682 13683 char ConstraintLetter = Constraint[0]; 13684 switch (ConstraintLetter) { 13685 default: break; 13686 case 'j': 13687 case 'I': case 'J': case 'K': case 'L': 13688 case 'M': case 'N': case 'O': 13689 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 13690 if (!C) 13691 return; 13692 13693 int64_t CVal64 = C->getSExtValue(); 13694 int CVal = (int) CVal64; 13695 // None of these constraints allow values larger than 32 bits. Check 13696 // that the value fits in an int. 13697 if (CVal != CVal64) 13698 return; 13699 13700 switch (ConstraintLetter) { 13701 case 'j': 13702 // Constant suitable for movw, must be between 0 and 13703 // 65535. 13704 if (Subtarget->hasV6T2Ops()) 13705 if (CVal >= 0 && CVal <= 65535) 13706 break; 13707 return; 13708 case 'I': 13709 if (Subtarget->isThumb1Only()) { 13710 // This must be a constant between 0 and 255, for ADD 13711 // immediates. 13712 if (CVal >= 0 && CVal <= 255) 13713 break; 13714 } else if (Subtarget->isThumb2()) { 13715 // A constant that can be used as an immediate value in a 13716 // data-processing instruction. 13717 if (ARM_AM::getT2SOImmVal(CVal) != -1) 13718 break; 13719 } else { 13720 // A constant that can be used as an immediate value in a 13721 // data-processing instruction. 13722 if (ARM_AM::getSOImmVal(CVal) != -1) 13723 break; 13724 } 13725 return; 13726 13727 case 'J': 13728 if (Subtarget->isThumb1Only()) { 13729 // This must be a constant between -255 and -1, for negated ADD 13730 // immediates. This can be used in GCC with an "n" modifier that 13731 // prints the negated value, for use with SUB instructions. It is 13732 // not useful otherwise but is implemented for compatibility. 13733 if (CVal >= -255 && CVal <= -1) 13734 break; 13735 } else { 13736 // This must be a constant between -4095 and 4095. It is not clear 13737 // what this constraint is intended for. Implemented for 13738 // compatibility with GCC. 13739 if (CVal >= -4095 && CVal <= 4095) 13740 break; 13741 } 13742 return; 13743 13744 case 'K': 13745 if (Subtarget->isThumb1Only()) { 13746 // A 32-bit value where only one byte has a nonzero value. Exclude 13747 // zero to match GCC. This constraint is used by GCC internally for 13748 // constants that can be loaded with a move/shift combination. 13749 // It is not useful otherwise but is implemented for compatibility. 13750 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 13751 break; 13752 } else if (Subtarget->isThumb2()) { 13753 // A constant whose bitwise inverse can be used as an immediate 13754 // value in a data-processing instruction. This can be used in GCC 13755 // with a "B" modifier that prints the inverted value, for use with 13756 // BIC and MVN instructions. It is not useful otherwise but is 13757 // implemented for compatibility. 13758 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 13759 break; 13760 } else { 13761 // A constant whose bitwise inverse can be used as an immediate 13762 // value in a data-processing instruction. This can be used in GCC 13763 // with a "B" modifier that prints the inverted value, for use with 13764 // BIC and MVN instructions. It is not useful otherwise but is 13765 // implemented for compatibility. 13766 if (ARM_AM::getSOImmVal(~CVal) != -1) 13767 break; 13768 } 13769 return; 13770 13771 case 'L': 13772 if (Subtarget->isThumb1Only()) { 13773 // This must be a constant between -7 and 7, 13774 // for 3-operand ADD/SUB immediate instructions. 13775 if (CVal >= -7 && CVal < 7) 13776 break; 13777 } else if (Subtarget->isThumb2()) { 13778 // A constant whose negation can be used as an immediate value in a 13779 // data-processing instruction. This can be used in GCC with an "n" 13780 // modifier that prints the negated value, for use with SUB 13781 // instructions. It is not useful otherwise but is implemented for 13782 // compatibility. 13783 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 13784 break; 13785 } else { 13786 // A constant whose negation can be used as an immediate value in a 13787 // data-processing instruction. This can be used in GCC with an "n" 13788 // modifier that prints the negated value, for use with SUB 13789 // instructions. It is not useful otherwise but is implemented for 13790 // compatibility. 13791 if (ARM_AM::getSOImmVal(-CVal) != -1) 13792 break; 13793 } 13794 return; 13795 13796 case 'M': 13797 if (Subtarget->isThumb1Only()) { 13798 // This must be a multiple of 4 between 0 and 1020, for 13799 // ADD sp + immediate. 13800 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 13801 break; 13802 } else { 13803 // A power of two or a constant between 0 and 32. This is used in 13804 // GCC for the shift amount on shifted register operands, but it is 13805 // useful in general for any shift amounts. 13806 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 13807 break; 13808 } 13809 return; 13810 13811 case 'N': 13812 if (Subtarget->isThumb()) { // FIXME thumb2 13813 // This must be a constant between 0 and 31, for shift amounts. 13814 if (CVal >= 0 && CVal <= 31) 13815 break; 13816 } 13817 return; 13818 13819 case 'O': 13820 if (Subtarget->isThumb()) { // FIXME thumb2 13821 // This must be a multiple of 4 between -508 and 508, for 13822 // ADD/SUB sp = sp + immediate. 13823 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 13824 break; 13825 } 13826 return; 13827 } 13828 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 13829 break; 13830 } 13831 13832 if (Result.getNode()) { 13833 Ops.push_back(Result); 13834 return; 13835 } 13836 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13837 } 13838 13839 static RTLIB::Libcall getDivRemLibcall( 13840 const SDNode *N, MVT::SimpleValueType SVT) { 13841 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13842 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13843 "Unhandled Opcode in getDivRemLibcall"); 13844 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13845 N->getOpcode() == ISD::SREM; 13846 RTLIB::Libcall LC; 13847 switch (SVT) { 13848 default: llvm_unreachable("Unexpected request for libcall!"); 13849 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 13850 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 13851 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 13852 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 13853 } 13854 return LC; 13855 } 13856 13857 static TargetLowering::ArgListTy getDivRemArgList( 13858 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 13859 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13860 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13861 "Unhandled Opcode in getDivRemArgList"); 13862 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13863 N->getOpcode() == ISD::SREM; 13864 TargetLowering::ArgListTy Args; 13865 TargetLowering::ArgListEntry Entry; 13866 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13867 EVT ArgVT = N->getOperand(i).getValueType(); 13868 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 13869 Entry.Node = N->getOperand(i); 13870 Entry.Ty = ArgTy; 13871 Entry.IsSExt = isSigned; 13872 Entry.IsZExt = !isSigned; 13873 Args.push_back(Entry); 13874 } 13875 if (Subtarget->isTargetWindows() && Args.size() >= 2) 13876 std::swap(Args[0], Args[1]); 13877 return Args; 13878 } 13879 13880 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 13881 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 13882 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 13883 Subtarget->isTargetWindows()) && 13884 "Register-based DivRem lowering only"); 13885 unsigned Opcode = Op->getOpcode(); 13886 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 13887 "Invalid opcode for Div/Rem lowering"); 13888 bool isSigned = (Opcode == ISD::SDIVREM); 13889 EVT VT = Op->getValueType(0); 13890 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 13891 SDLoc dl(Op); 13892 13893 // If the target has hardware divide, use divide + multiply + subtract: 13894 // div = a / b 13895 // rem = a - b * div 13896 // return {div, rem} 13897 // This should be lowered into UDIV/SDIV + MLS later on. 13898 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 13899 : Subtarget->hasDivideInARMMode(); 13900 if (hasDivide && Op->getValueType(0).isSimple() && 13901 Op->getSimpleValueType(0) == MVT::i32) { 13902 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 13903 const SDValue Dividend = Op->getOperand(0); 13904 const SDValue Divisor = Op->getOperand(1); 13905 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 13906 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 13907 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 13908 13909 SDValue Values[2] = {Div, Rem}; 13910 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 13911 } 13912 13913 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 13914 VT.getSimpleVT().SimpleTy); 13915 SDValue InChain = DAG.getEntryNode(); 13916 13917 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 13918 DAG.getContext(), 13919 Subtarget); 13920 13921 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13922 getPointerTy(DAG.getDataLayout())); 13923 13924 Type *RetTy = StructType::get(Ty, Ty); 13925 13926 if (Subtarget->isTargetWindows()) 13927 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 13928 13929 TargetLowering::CallLoweringInfo CLI(DAG); 13930 CLI.setDebugLoc(dl).setChain(InChain) 13931 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 13932 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 13933 13934 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 13935 return CallInfo.first; 13936 } 13937 13938 // Lowers REM using divmod helpers 13939 // see RTABI section 4.2/4.3 13940 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 13941 // Build return types (div and rem) 13942 std::vector<Type*> RetTyParams; 13943 Type *RetTyElement; 13944 13945 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 13946 default: llvm_unreachable("Unexpected request for libcall!"); 13947 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 13948 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 13949 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 13950 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 13951 } 13952 13953 RetTyParams.push_back(RetTyElement); 13954 RetTyParams.push_back(RetTyElement); 13955 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 13956 Type *RetTy = StructType::get(*DAG.getContext(), ret); 13957 13958 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 13959 SimpleTy); 13960 SDValue InChain = DAG.getEntryNode(); 13961 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 13962 Subtarget); 13963 bool isSigned = N->getOpcode() == ISD::SREM; 13964 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13965 getPointerTy(DAG.getDataLayout())); 13966 13967 if (Subtarget->isTargetWindows()) 13968 InChain = WinDBZCheckDenominator(DAG, N, InChain); 13969 13970 // Lower call 13971 CallLoweringInfo CLI(DAG); 13972 CLI.setChain(InChain) 13973 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 13974 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 13975 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 13976 13977 // Return second (rem) result operand (first contains div) 13978 SDNode *ResNode = CallResult.first.getNode(); 13979 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 13980 return ResNode->getOperand(1); 13981 } 13982 13983 SDValue 13984 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 13985 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 13986 SDLoc DL(Op); 13987 13988 // Get the inputs. 13989 SDValue Chain = Op.getOperand(0); 13990 SDValue Size = Op.getOperand(1); 13991 13992 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 13993 "no-stack-arg-probe")) { 13994 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 13995 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 13996 Chain = SP.getValue(1); 13997 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 13998 if (Align) 13999 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 14000 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 14001 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 14002 SDValue Ops[2] = { SP, Chain }; 14003 return DAG.getMergeValues(Ops, DL); 14004 } 14005 14006 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 14007 DAG.getConstant(2, DL, MVT::i32)); 14008 14009 SDValue Flag; 14010 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 14011 Flag = Chain.getValue(1); 14012 14013 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 14014 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 14015 14016 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 14017 Chain = NewSP.getValue(1); 14018 14019 SDValue Ops[2] = { NewSP, Chain }; 14020 return DAG.getMergeValues(Ops, DL); 14021 } 14022 14023 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 14024 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 14025 "Unexpected type for custom-lowering FP_EXTEND"); 14026 14027 RTLIB::Libcall LC; 14028 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 14029 14030 SDValue SrcVal = Op.getOperand(0); 14031 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 14032 SDLoc(Op)).first; 14033 } 14034 14035 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 14036 assert(Op.getOperand(0).getValueType() == MVT::f64 && 14037 Subtarget->isFPOnlySP() && 14038 "Unexpected type for custom-lowering FP_ROUND"); 14039 14040 RTLIB::Libcall LC; 14041 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 14042 14043 SDValue SrcVal = Op.getOperand(0); 14044 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 14045 SDLoc(Op)).first; 14046 } 14047 14048 bool 14049 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14050 // The ARM target isn't yet aware of offsets. 14051 return false; 14052 } 14053 14054 bool ARM::isBitFieldInvertedMask(unsigned v) { 14055 if (v == 0xffffffff) 14056 return false; 14057 14058 // there can be 1's on either or both "outsides", all the "inside" 14059 // bits must be 0's 14060 return isShiftedMask_32(~v); 14061 } 14062 14063 /// isFPImmLegal - Returns true if the target can instruction select the 14064 /// specified FP immediate natively. If false, the legalizer will 14065 /// materialize the FP immediate as a load from a constant pool. 14066 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 14067 if (!Subtarget->hasVFP3()) 14068 return false; 14069 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 14070 return ARM_AM::getFP16Imm(Imm) != -1; 14071 if (VT == MVT::f32) 14072 return ARM_AM::getFP32Imm(Imm) != -1; 14073 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 14074 return ARM_AM::getFP64Imm(Imm) != -1; 14075 return false; 14076 } 14077 14078 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 14079 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 14080 /// specified in the intrinsic calls. 14081 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14082 const CallInst &I, 14083 MachineFunction &MF, 14084 unsigned Intrinsic) const { 14085 switch (Intrinsic) { 14086 case Intrinsic::arm_neon_vld1: 14087 case Intrinsic::arm_neon_vld2: 14088 case Intrinsic::arm_neon_vld3: 14089 case Intrinsic::arm_neon_vld4: 14090 case Intrinsic::arm_neon_vld2lane: 14091 case Intrinsic::arm_neon_vld3lane: 14092 case Intrinsic::arm_neon_vld4lane: { 14093 Info.opc = ISD::INTRINSIC_W_CHAIN; 14094 // Conservatively set memVT to the entire set of vectors loaded. 14095 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14096 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14097 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14098 Info.ptrVal = I.getArgOperand(0); 14099 Info.offset = 0; 14100 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14101 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14102 // volatile loads with NEON intrinsics not supported 14103 Info.flags = MachineMemOperand::MOLoad; 14104 return true; 14105 } 14106 case Intrinsic::arm_neon_vst1: 14107 case Intrinsic::arm_neon_vst2: 14108 case Intrinsic::arm_neon_vst3: 14109 case Intrinsic::arm_neon_vst4: 14110 case Intrinsic::arm_neon_vst2lane: 14111 case Intrinsic::arm_neon_vst3lane: 14112 case Intrinsic::arm_neon_vst4lane: { 14113 Info.opc = ISD::INTRINSIC_VOID; 14114 // Conservatively set memVT to the entire set of vectors stored. 14115 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14116 unsigned NumElts = 0; 14117 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14118 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14119 if (!ArgTy->isVectorTy()) 14120 break; 14121 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14122 } 14123 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14124 Info.ptrVal = I.getArgOperand(0); 14125 Info.offset = 0; 14126 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14127 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14128 // volatile stores with NEON intrinsics not supported 14129 Info.flags = MachineMemOperand::MOStore; 14130 return true; 14131 } 14132 case Intrinsic::arm_ldaex: 14133 case Intrinsic::arm_ldrex: { 14134 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14135 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 14136 Info.opc = ISD::INTRINSIC_W_CHAIN; 14137 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14138 Info.ptrVal = I.getArgOperand(0); 14139 Info.offset = 0; 14140 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14141 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14142 return true; 14143 } 14144 case Intrinsic::arm_stlex: 14145 case Intrinsic::arm_strex: { 14146 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14147 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 14148 Info.opc = ISD::INTRINSIC_W_CHAIN; 14149 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14150 Info.ptrVal = I.getArgOperand(1); 14151 Info.offset = 0; 14152 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14153 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14154 return true; 14155 } 14156 case Intrinsic::arm_stlexd: 14157 case Intrinsic::arm_strexd: 14158 Info.opc = ISD::INTRINSIC_W_CHAIN; 14159 Info.memVT = MVT::i64; 14160 Info.ptrVal = I.getArgOperand(2); 14161 Info.offset = 0; 14162 Info.align = 8; 14163 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14164 return true; 14165 14166 case Intrinsic::arm_ldaexd: 14167 case Intrinsic::arm_ldrexd: 14168 Info.opc = ISD::INTRINSIC_W_CHAIN; 14169 Info.memVT = MVT::i64; 14170 Info.ptrVal = I.getArgOperand(0); 14171 Info.offset = 0; 14172 Info.align = 8; 14173 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14174 return true; 14175 14176 default: 14177 break; 14178 } 14179 14180 return false; 14181 } 14182 14183 /// Returns true if it is beneficial to convert a load of a constant 14184 /// to just the constant itself. 14185 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14186 Type *Ty) const { 14187 assert(Ty->isIntegerTy()); 14188 14189 unsigned Bits = Ty->getPrimitiveSizeInBits(); 14190 if (Bits == 0 || Bits > 32) 14191 return false; 14192 return true; 14193 } 14194 14195 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 14196 unsigned Index) const { 14197 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 14198 return false; 14199 14200 return (Index == 0 || Index == ResVT.getVectorNumElements()); 14201 } 14202 14203 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 14204 ARM_MB::MemBOpt Domain) const { 14205 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14206 14207 // First, if the target has no DMB, see what fallback we can use. 14208 if (!Subtarget->hasDataBarrier()) { 14209 // Some ARMv6 cpus can support data barriers with an mcr instruction. 14210 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 14211 // here. 14212 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 14213 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 14214 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 14215 Builder.getInt32(0), Builder.getInt32(7), 14216 Builder.getInt32(10), Builder.getInt32(5)}; 14217 return Builder.CreateCall(MCR, args); 14218 } else { 14219 // Instead of using barriers, atomic accesses on these subtargets use 14220 // libcalls. 14221 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 14222 } 14223 } else { 14224 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 14225 // Only a full system barrier exists in the M-class architectures. 14226 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 14227 Constant *CDomain = Builder.getInt32(Domain); 14228 return Builder.CreateCall(DMB, CDomain); 14229 } 14230 } 14231 14232 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 14233 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 14234 Instruction *Inst, 14235 AtomicOrdering Ord) const { 14236 switch (Ord) { 14237 case AtomicOrdering::NotAtomic: 14238 case AtomicOrdering::Unordered: 14239 llvm_unreachable("Invalid fence: unordered/non-atomic"); 14240 case AtomicOrdering::Monotonic: 14241 case AtomicOrdering::Acquire: 14242 return nullptr; // Nothing to do 14243 case AtomicOrdering::SequentiallyConsistent: 14244 if (!Inst->hasAtomicStore()) 14245 return nullptr; // Nothing to do 14246 LLVM_FALLTHROUGH; 14247 case AtomicOrdering::Release: 14248 case AtomicOrdering::AcquireRelease: 14249 if (Subtarget->preferISHSTBarriers()) 14250 return makeDMB(Builder, ARM_MB::ISHST); 14251 // FIXME: add a comment with a link to documentation justifying this. 14252 else 14253 return makeDMB(Builder, ARM_MB::ISH); 14254 } 14255 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 14256 } 14257 14258 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 14259 Instruction *Inst, 14260 AtomicOrdering Ord) const { 14261 switch (Ord) { 14262 case AtomicOrdering::NotAtomic: 14263 case AtomicOrdering::Unordered: 14264 llvm_unreachable("Invalid fence: unordered/not-atomic"); 14265 case AtomicOrdering::Monotonic: 14266 case AtomicOrdering::Release: 14267 return nullptr; // Nothing to do 14268 case AtomicOrdering::Acquire: 14269 case AtomicOrdering::AcquireRelease: 14270 case AtomicOrdering::SequentiallyConsistent: 14271 return makeDMB(Builder, ARM_MB::ISH); 14272 } 14273 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 14274 } 14275 14276 // Loads and stores less than 64-bits are already atomic; ones above that 14277 // are doomed anyway, so defer to the default libcall and blame the OS when 14278 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14279 // anything for those. 14280 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 14281 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 14282 return (Size == 64) && !Subtarget->isMClass(); 14283 } 14284 14285 // Loads and stores less than 64-bits are already atomic; ones above that 14286 // are doomed anyway, so defer to the default libcall and blame the OS when 14287 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14288 // anything for those. 14289 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 14290 // guarantee, see DDI0406C ARM architecture reference manual, 14291 // sections A8.8.72-74 LDRD) 14292 TargetLowering::AtomicExpansionKind 14293 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 14294 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 14295 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 14296 : AtomicExpansionKind::None; 14297 } 14298 14299 // For the real atomic operations, we have ldrex/strex up to 32 bits, 14300 // and up to 64 bits on the non-M profiles 14301 TargetLowering::AtomicExpansionKind 14302 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 14303 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 14304 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14305 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 14306 ? AtomicExpansionKind::LLSC 14307 : AtomicExpansionKind::None; 14308 } 14309 14310 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 14311 AtomicCmpXchgInst *AI) const { 14312 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 14313 // implement cmpxchg without spilling. If the address being exchanged is also 14314 // on the stack and close enough to the spill slot, this can lead to a 14315 // situation where the monitor always gets cleared and the atomic operation 14316 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 14317 bool hasAtomicCmpXchg = 14318 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14319 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 14320 } 14321 14322 bool ARMTargetLowering::shouldInsertFencesForAtomic( 14323 const Instruction *I) const { 14324 return InsertFencesForAtomic; 14325 } 14326 14327 // This has so far only been implemented for MachO. 14328 bool ARMTargetLowering::useLoadStackGuardNode() const { 14329 return Subtarget->isTargetMachO(); 14330 } 14331 14332 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 14333 unsigned &Cost) const { 14334 // If we do not have NEON, vector types are not natively supported. 14335 if (!Subtarget->hasNEON()) 14336 return false; 14337 14338 // Floating point values and vector values map to the same register file. 14339 // Therefore, although we could do a store extract of a vector type, this is 14340 // better to leave at float as we have more freedom in the addressing mode for 14341 // those. 14342 if (VectorTy->isFPOrFPVectorTy()) 14343 return false; 14344 14345 // If the index is unknown at compile time, this is very expensive to lower 14346 // and it is not possible to combine the store with the extract. 14347 if (!isa<ConstantInt>(Idx)) 14348 return false; 14349 14350 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 14351 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 14352 // We can do a store + vector extract on any vector that fits perfectly in a D 14353 // or Q register. 14354 if (BitWidth == 64 || BitWidth == 128) { 14355 Cost = 0; 14356 return true; 14357 } 14358 return false; 14359 } 14360 14361 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 14362 return Subtarget->hasV6T2Ops(); 14363 } 14364 14365 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 14366 return Subtarget->hasV6T2Ops(); 14367 } 14368 14369 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 14370 AtomicOrdering Ord) const { 14371 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14372 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 14373 bool IsAcquire = isAcquireOrStronger(Ord); 14374 14375 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 14376 // intrinsic must return {i32, i32} and we have to recombine them into a 14377 // single i64 here. 14378 if (ValTy->getPrimitiveSizeInBits() == 64) { 14379 Intrinsic::ID Int = 14380 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 14381 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 14382 14383 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14384 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 14385 14386 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 14387 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 14388 if (!Subtarget->isLittle()) 14389 std::swap (Lo, Hi); 14390 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 14391 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 14392 return Builder.CreateOr( 14393 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 14394 } 14395 14396 Type *Tys[] = { Addr->getType() }; 14397 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 14398 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 14399 14400 return Builder.CreateTruncOrBitCast( 14401 Builder.CreateCall(Ldrex, Addr), 14402 cast<PointerType>(Addr->getType())->getElementType()); 14403 } 14404 14405 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 14406 IRBuilder<> &Builder) const { 14407 if (!Subtarget->hasV7Ops()) 14408 return; 14409 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14410 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 14411 } 14412 14413 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 14414 Value *Addr, 14415 AtomicOrdering Ord) const { 14416 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14417 bool IsRelease = isReleaseOrStronger(Ord); 14418 14419 // Since the intrinsics must have legal type, the i64 intrinsics take two 14420 // parameters: "i32, i32". We must marshal Val into the appropriate form 14421 // before the call. 14422 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 14423 Intrinsic::ID Int = 14424 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 14425 Function *Strex = Intrinsic::getDeclaration(M, Int); 14426 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 14427 14428 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 14429 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 14430 if (!Subtarget->isLittle()) 14431 std::swap(Lo, Hi); 14432 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14433 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 14434 } 14435 14436 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 14437 Type *Tys[] = { Addr->getType() }; 14438 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 14439 14440 return Builder.CreateCall( 14441 Strex, {Builder.CreateZExtOrBitCast( 14442 Val, Strex->getFunctionType()->getParamType(0)), 14443 Addr}); 14444 } 14445 14446 /// A helper function for determining the number of interleaved accesses we 14447 /// will generate when lowering accesses of the given type. 14448 unsigned 14449 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 14450 const DataLayout &DL) const { 14451 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 14452 } 14453 14454 bool ARMTargetLowering::isLegalInterleavedAccessType( 14455 VectorType *VecTy, const DataLayout &DL) const { 14456 14457 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 14458 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 14459 14460 // Ensure the vector doesn't have f16 elements. Even though we could do an 14461 // i16 vldN, we can't hold the f16 vectors and will end up converting via 14462 // f32. 14463 if (VecTy->getElementType()->isHalfTy()) 14464 return false; 14465 14466 // Ensure the number of vector elements is greater than 1. 14467 if (VecTy->getNumElements() < 2) 14468 return false; 14469 14470 // Ensure the element type is legal. 14471 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 14472 return false; 14473 14474 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 14475 // 128 will be split into multiple interleaved accesses. 14476 return VecSize == 64 || VecSize % 128 == 0; 14477 } 14478 14479 /// Lower an interleaved load into a vldN intrinsic. 14480 /// 14481 /// E.g. Lower an interleaved load (Factor = 2): 14482 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 14483 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 14484 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 14485 /// 14486 /// Into: 14487 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 14488 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 14489 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 14490 bool ARMTargetLowering::lowerInterleavedLoad( 14491 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 14492 ArrayRef<unsigned> Indices, unsigned Factor) const { 14493 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14494 "Invalid interleave factor"); 14495 assert(!Shuffles.empty() && "Empty shufflevector input"); 14496 assert(Shuffles.size() == Indices.size() && 14497 "Unmatched number of shufflevectors and indices"); 14498 14499 VectorType *VecTy = Shuffles[0]->getType(); 14500 Type *EltTy = VecTy->getVectorElementType(); 14501 14502 const DataLayout &DL = LI->getModule()->getDataLayout(); 14503 14504 // Skip if we do not have NEON and skip illegal vector types. We can 14505 // "legalize" wide vector types into multiple interleaved accesses as long as 14506 // the vector types are divisible by 128. 14507 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 14508 return false; 14509 14510 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 14511 14512 // A pointer vector can not be the return type of the ldN intrinsics. Need to 14513 // load integer vectors first and then convert to pointer vectors. 14514 if (EltTy->isPointerTy()) 14515 VecTy = 14516 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 14517 14518 IRBuilder<> Builder(LI); 14519 14520 // The base address of the load. 14521 Value *BaseAddr = LI->getPointerOperand(); 14522 14523 if (NumLoads > 1) { 14524 // If we're going to generate more than one load, reset the sub-vector type 14525 // to something legal. 14526 VecTy = VectorType::get(VecTy->getVectorElementType(), 14527 VecTy->getVectorNumElements() / NumLoads); 14528 14529 // We will compute the pointer operand of each load from the original base 14530 // address using GEPs. Cast the base address to a pointer to the scalar 14531 // element type. 14532 BaseAddr = Builder.CreateBitCast( 14533 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 14534 LI->getPointerAddressSpace())); 14535 } 14536 14537 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 14538 14539 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 14540 Type *Tys[] = {VecTy, Int8Ptr}; 14541 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 14542 Intrinsic::arm_neon_vld3, 14543 Intrinsic::arm_neon_vld4}; 14544 Function *VldnFunc = 14545 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 14546 14547 // Holds sub-vectors extracted from the load intrinsic return values. The 14548 // sub-vectors are associated with the shufflevector instructions they will 14549 // replace. 14550 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 14551 14552 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 14553 // If we're generating more than one load, compute the base address of 14554 // subsequent loads as an offset from the previous. 14555 if (LoadCount > 0) 14556 BaseAddr = Builder.CreateConstGEP1_32( 14557 BaseAddr, VecTy->getVectorNumElements() * Factor); 14558 14559 SmallVector<Value *, 2> Ops; 14560 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14561 Ops.push_back(Builder.getInt32(LI->getAlignment())); 14562 14563 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 14564 14565 // Replace uses of each shufflevector with the corresponding vector loaded 14566 // by ldN. 14567 for (unsigned i = 0; i < Shuffles.size(); i++) { 14568 ShuffleVectorInst *SV = Shuffles[i]; 14569 unsigned Index = Indices[i]; 14570 14571 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 14572 14573 // Convert the integer vector to pointer vector if the element is pointer. 14574 if (EltTy->isPointerTy()) 14575 SubVec = Builder.CreateIntToPtr( 14576 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 14577 VecTy->getVectorNumElements())); 14578 14579 SubVecs[SV].push_back(SubVec); 14580 } 14581 } 14582 14583 // Replace uses of the shufflevector instructions with the sub-vectors 14584 // returned by the load intrinsic. If a shufflevector instruction is 14585 // associated with more than one sub-vector, those sub-vectors will be 14586 // concatenated into a single wide vector. 14587 for (ShuffleVectorInst *SVI : Shuffles) { 14588 auto &SubVec = SubVecs[SVI]; 14589 auto *WideVec = 14590 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 14591 SVI->replaceAllUsesWith(WideVec); 14592 } 14593 14594 return true; 14595 } 14596 14597 /// Lower an interleaved store into a vstN intrinsic. 14598 /// 14599 /// E.g. Lower an interleaved store (Factor = 3): 14600 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 14601 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 14602 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 14603 /// 14604 /// Into: 14605 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 14606 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 14607 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 14608 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14609 /// 14610 /// Note that the new shufflevectors will be removed and we'll only generate one 14611 /// vst3 instruction in CodeGen. 14612 /// 14613 /// Example for a more general valid mask (Factor 3). Lower: 14614 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 14615 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 14616 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 14617 /// 14618 /// Into: 14619 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 14620 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 14621 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 14622 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14623 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 14624 ShuffleVectorInst *SVI, 14625 unsigned Factor) const { 14626 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14627 "Invalid interleave factor"); 14628 14629 VectorType *VecTy = SVI->getType(); 14630 assert(VecTy->getVectorNumElements() % Factor == 0 && 14631 "Invalid interleaved store"); 14632 14633 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 14634 Type *EltTy = VecTy->getVectorElementType(); 14635 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 14636 14637 const DataLayout &DL = SI->getModule()->getDataLayout(); 14638 14639 // Skip if we do not have NEON and skip illegal vector types. We can 14640 // "legalize" wide vector types into multiple interleaved accesses as long as 14641 // the vector types are divisible by 128. 14642 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 14643 return false; 14644 14645 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 14646 14647 Value *Op0 = SVI->getOperand(0); 14648 Value *Op1 = SVI->getOperand(1); 14649 IRBuilder<> Builder(SI); 14650 14651 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 14652 // vectors to integer vectors. 14653 if (EltTy->isPointerTy()) { 14654 Type *IntTy = DL.getIntPtrType(EltTy); 14655 14656 // Convert to the corresponding integer vector. 14657 Type *IntVecTy = 14658 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 14659 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 14660 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 14661 14662 SubVecTy = VectorType::get(IntTy, LaneLen); 14663 } 14664 14665 // The base address of the store. 14666 Value *BaseAddr = SI->getPointerOperand(); 14667 14668 if (NumStores > 1) { 14669 // If we're going to generate more than one store, reset the lane length 14670 // and sub-vector type to something legal. 14671 LaneLen /= NumStores; 14672 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 14673 14674 // We will compute the pointer operand of each store from the original base 14675 // address using GEPs. Cast the base address to a pointer to the scalar 14676 // element type. 14677 BaseAddr = Builder.CreateBitCast( 14678 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 14679 SI->getPointerAddressSpace())); 14680 } 14681 14682 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 14683 14684 auto Mask = SVI->getShuffleMask(); 14685 14686 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 14687 Type *Tys[] = {Int8Ptr, SubVecTy}; 14688 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 14689 Intrinsic::arm_neon_vst3, 14690 Intrinsic::arm_neon_vst4}; 14691 14692 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 14693 // If we generating more than one store, we compute the base address of 14694 // subsequent stores as an offset from the previous. 14695 if (StoreCount > 0) 14696 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 14697 14698 SmallVector<Value *, 6> Ops; 14699 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14700 14701 Function *VstNFunc = 14702 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 14703 14704 // Split the shufflevector operands into sub vectors for the new vstN call. 14705 for (unsigned i = 0; i < Factor; i++) { 14706 unsigned IdxI = StoreCount * LaneLen * Factor + i; 14707 if (Mask[IdxI] >= 0) { 14708 Ops.push_back(Builder.CreateShuffleVector( 14709 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 14710 } else { 14711 unsigned StartMask = 0; 14712 for (unsigned j = 1; j < LaneLen; j++) { 14713 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 14714 if (Mask[IdxJ * Factor + IdxI] >= 0) { 14715 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 14716 break; 14717 } 14718 } 14719 // Note: If all elements in a chunk are undefs, StartMask=0! 14720 // Note: Filling undef gaps with random elements is ok, since 14721 // those elements were being written anyway (with undefs). 14722 // In the case of all undefs we're defaulting to using elems from 0 14723 // Note: StartMask cannot be negative, it's checked in 14724 // isReInterleaveMask 14725 Ops.push_back(Builder.CreateShuffleVector( 14726 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 14727 } 14728 } 14729 14730 Ops.push_back(Builder.getInt32(SI->getAlignment())); 14731 Builder.CreateCall(VstNFunc, Ops); 14732 } 14733 return true; 14734 } 14735 14736 enum HABaseType { 14737 HA_UNKNOWN = 0, 14738 HA_FLOAT, 14739 HA_DOUBLE, 14740 HA_VECT64, 14741 HA_VECT128 14742 }; 14743 14744 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 14745 uint64_t &Members) { 14746 if (auto *ST = dyn_cast<StructType>(Ty)) { 14747 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 14748 uint64_t SubMembers = 0; 14749 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 14750 return false; 14751 Members += SubMembers; 14752 } 14753 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 14754 uint64_t SubMembers = 0; 14755 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 14756 return false; 14757 Members += SubMembers * AT->getNumElements(); 14758 } else if (Ty->isFloatTy()) { 14759 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 14760 return false; 14761 Members = 1; 14762 Base = HA_FLOAT; 14763 } else if (Ty->isDoubleTy()) { 14764 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 14765 return false; 14766 Members = 1; 14767 Base = HA_DOUBLE; 14768 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 14769 Members = 1; 14770 switch (Base) { 14771 case HA_FLOAT: 14772 case HA_DOUBLE: 14773 return false; 14774 case HA_VECT64: 14775 return VT->getBitWidth() == 64; 14776 case HA_VECT128: 14777 return VT->getBitWidth() == 128; 14778 case HA_UNKNOWN: 14779 switch (VT->getBitWidth()) { 14780 case 64: 14781 Base = HA_VECT64; 14782 return true; 14783 case 128: 14784 Base = HA_VECT128; 14785 return true; 14786 default: 14787 return false; 14788 } 14789 } 14790 } 14791 14792 return (Members > 0 && Members <= 4); 14793 } 14794 14795 /// Return the correct alignment for the current calling convention. 14796 unsigned 14797 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 14798 DataLayout DL) const { 14799 if (!ArgTy->isVectorTy()) 14800 return DL.getABITypeAlignment(ArgTy); 14801 14802 // Avoid over-aligning vector parameters. It would require realigning the 14803 // stack and waste space for no real benefit. 14804 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment()); 14805 } 14806 14807 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 14808 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 14809 /// passing according to AAPCS rules. 14810 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 14811 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 14812 if (getEffectiveCallingConv(CallConv, isVarArg) != 14813 CallingConv::ARM_AAPCS_VFP) 14814 return false; 14815 14816 HABaseType Base = HA_UNKNOWN; 14817 uint64_t Members = 0; 14818 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 14819 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 14820 14821 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 14822 return IsHA || IsIntArray; 14823 } 14824 14825 unsigned ARMTargetLowering::getExceptionPointerRegister( 14826 const Constant *PersonalityFn) const { 14827 // Platforms which do not use SjLj EH may return values in these registers 14828 // via the personality function. 14829 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 14830 } 14831 14832 unsigned ARMTargetLowering::getExceptionSelectorRegister( 14833 const Constant *PersonalityFn) const { 14834 // Platforms which do not use SjLj EH may return values in these registers 14835 // via the personality function. 14836 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 14837 } 14838 14839 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14840 // Update IsSplitCSR in ARMFunctionInfo. 14841 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 14842 AFI->setIsSplitCSR(true); 14843 } 14844 14845 void ARMTargetLowering::insertCopiesSplitCSR( 14846 MachineBasicBlock *Entry, 14847 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14848 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 14849 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14850 if (!IStart) 14851 return; 14852 14853 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 14854 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14855 MachineBasicBlock::iterator MBBI = Entry->begin(); 14856 for (const MCPhysReg *I = IStart; *I; ++I) { 14857 const TargetRegisterClass *RC = nullptr; 14858 if (ARM::GPRRegClass.contains(*I)) 14859 RC = &ARM::GPRRegClass; 14860 else if (ARM::DPRRegClass.contains(*I)) 14861 RC = &ARM::DPRRegClass; 14862 else 14863 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14864 14865 unsigned NewVR = MRI->createVirtualRegister(RC); 14866 // Create copy from CSR to a virtual register. 14867 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14868 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14869 // nounwind. If we want to generalize this later, we may need to emit 14870 // CFI pseudo-instructions. 14871 assert(Entry->getParent()->getFunction().hasFnAttribute( 14872 Attribute::NoUnwind) && 14873 "Function should be nounwind in insertCopiesSplitCSR!"); 14874 Entry->addLiveIn(*I); 14875 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14876 .addReg(*I); 14877 14878 // Insert the copy-back instructions right before the terminator. 14879 for (auto *Exit : Exits) 14880 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14881 TII->get(TargetOpcode::COPY), *I) 14882 .addReg(NewVR); 14883 } 14884 } 14885 14886 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 14887 MF.getFrameInfo().computeMaxCallFrameSize(MF); 14888 TargetLoweringBase::finalizeLowering(MF); 14889 } 14890