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/MachineValueType.h" 57 #include "llvm/CodeGen/RuntimeLibcalls.h" 58 #include "llvm/CodeGen/SelectionDAG.h" 59 #include "llvm/CodeGen/SelectionDAGNodes.h" 60 #include "llvm/CodeGen/TargetInstrInfo.h" 61 #include "llvm/CodeGen/TargetLowering.h" 62 #include "llvm/CodeGen/TargetOpcodes.h" 63 #include "llvm/CodeGen/TargetRegisterInfo.h" 64 #include "llvm/CodeGen/TargetSubtargetInfo.h" 65 #include "llvm/CodeGen/ValueTypes.h" 66 #include "llvm/IR/Attributes.h" 67 #include "llvm/IR/CallingConv.h" 68 #include "llvm/IR/Constant.h" 69 #include "llvm/IR/Constants.h" 70 #include "llvm/IR/DataLayout.h" 71 #include "llvm/IR/DebugLoc.h" 72 #include "llvm/IR/DerivedTypes.h" 73 #include "llvm/IR/Function.h" 74 #include "llvm/IR/GlobalAlias.h" 75 #include "llvm/IR/GlobalValue.h" 76 #include "llvm/IR/GlobalVariable.h" 77 #include "llvm/IR/IRBuilder.h" 78 #include "llvm/IR/InlineAsm.h" 79 #include "llvm/IR/Instruction.h" 80 #include "llvm/IR/Instructions.h" 81 #include "llvm/IR/IntrinsicInst.h" 82 #include "llvm/IR/Intrinsics.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Type.h" 85 #include "llvm/IR/User.h" 86 #include "llvm/IR/Value.h" 87 #include "llvm/MC/MCInstrDesc.h" 88 #include "llvm/MC/MCInstrItineraries.h" 89 #include "llvm/MC/MCRegisterInfo.h" 90 #include "llvm/MC/MCSchedule.h" 91 #include "llvm/Support/AtomicOrdering.h" 92 #include "llvm/Support/BranchProbability.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CodeGen.h" 95 #include "llvm/Support/CommandLine.h" 96 #include "llvm/Support/Compiler.h" 97 #include "llvm/Support/Debug.h" 98 #include "llvm/Support/ErrorHandling.h" 99 #include "llvm/Support/KnownBits.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 for (MVT VT : MVT::vector_valuetypes()) { 526 for (MVT InnerVT : MVT::vector_valuetypes()) { 527 setTruncStoreAction(VT, InnerVT, Expand); 528 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 529 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 530 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 531 } 532 533 setOperationAction(ISD::MULHS, VT, Expand); 534 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 535 setOperationAction(ISD::MULHU, VT, Expand); 536 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 537 538 setOperationAction(ISD::BSWAP, VT, Expand); 539 } 540 541 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 542 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 543 544 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 545 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 546 547 if (Subtarget->hasNEON()) { 548 addDRTypeForNEON(MVT::v2f32); 549 addDRTypeForNEON(MVT::v8i8); 550 addDRTypeForNEON(MVT::v4i16); 551 addDRTypeForNEON(MVT::v2i32); 552 addDRTypeForNEON(MVT::v1i64); 553 554 addQRTypeForNEON(MVT::v4f32); 555 addQRTypeForNEON(MVT::v2f64); 556 addQRTypeForNEON(MVT::v16i8); 557 addQRTypeForNEON(MVT::v8i16); 558 addQRTypeForNEON(MVT::v4i32); 559 addQRTypeForNEON(MVT::v2i64); 560 561 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 562 // neither Neon nor VFP support any arithmetic operations on it. 563 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 564 // supported for v4f32. 565 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 566 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 567 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 568 // FIXME: Code duplication: FDIV and FREM are expanded always, see 569 // ARMTargetLowering::addTypeForNEON method for details. 570 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 571 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 572 // FIXME: Create unittest. 573 // In another words, find a way when "copysign" appears in DAG with vector 574 // operands. 575 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 576 // FIXME: Code duplication: SETCC has custom operation action, see 577 // ARMTargetLowering::addTypeForNEON method for details. 578 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 579 // FIXME: Create unittest for FNEG and for FABS. 580 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 581 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 582 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 583 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 584 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 585 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 586 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 587 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 588 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 589 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 590 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 591 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 592 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 593 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 594 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 595 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 596 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 597 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 598 599 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 600 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 601 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 602 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 603 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 604 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 605 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 606 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 607 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 608 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 609 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 610 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 611 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 612 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 613 614 // Mark v2f32 intrinsics. 615 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 616 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 617 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 618 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 619 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 620 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 621 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 622 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 623 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 624 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 625 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 626 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 627 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 628 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 629 630 // Neon does not support some operations on v1i64 and v2i64 types. 631 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 632 // Custom handling for some quad-vector types to detect VMULL. 633 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 634 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 635 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 636 // Custom handling for some vector types to avoid expensive expansions 637 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 638 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 639 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 640 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 641 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 642 // a destination type that is wider than the source, and nor does 643 // it have a FP_TO_[SU]INT instruction with a narrower destination than 644 // source. 645 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 646 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 647 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 648 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 649 650 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 651 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 652 653 // NEON does not have single instruction CTPOP for vectors with element 654 // types wider than 8-bits. However, custom lowering can leverage the 655 // v8i8/v16i8 vcnt instruction. 656 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 657 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 658 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 659 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 660 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 661 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 662 663 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 664 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 665 666 // NEON does not have single instruction CTTZ for vectors. 667 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 668 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 669 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 670 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 671 672 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 673 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 674 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 675 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 676 677 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 678 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 679 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 680 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 681 682 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 683 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 684 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 685 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 686 687 // NEON only has FMA instructions as of VFP4. 688 if (!Subtarget->hasVFP4()) { 689 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 690 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 691 } 692 693 setTargetDAGCombine(ISD::INTRINSIC_VOID); 694 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 695 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 696 setTargetDAGCombine(ISD::SHL); 697 setTargetDAGCombine(ISD::SRL); 698 setTargetDAGCombine(ISD::SRA); 699 setTargetDAGCombine(ISD::SIGN_EXTEND); 700 setTargetDAGCombine(ISD::ZERO_EXTEND); 701 setTargetDAGCombine(ISD::ANY_EXTEND); 702 setTargetDAGCombine(ISD::BUILD_VECTOR); 703 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 704 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 705 setTargetDAGCombine(ISD::STORE); 706 setTargetDAGCombine(ISD::FP_TO_SINT); 707 setTargetDAGCombine(ISD::FP_TO_UINT); 708 setTargetDAGCombine(ISD::FDIV); 709 setTargetDAGCombine(ISD::LOAD); 710 711 // It is legal to extload from v4i8 to v4i16 or v4i32. 712 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 713 MVT::v2i32}) { 714 for (MVT VT : MVT::integer_vector_valuetypes()) { 715 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 716 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 717 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 718 } 719 } 720 } 721 722 if (Subtarget->isFPOnlySP()) { 723 // When targeting a floating-point unit with only single-precision 724 // operations, f64 is legal for the few double-precision instructions which 725 // are present However, no double-precision operations other than moves, 726 // loads and stores are provided by the hardware. 727 setOperationAction(ISD::FADD, MVT::f64, Expand); 728 setOperationAction(ISD::FSUB, MVT::f64, Expand); 729 setOperationAction(ISD::FMUL, MVT::f64, Expand); 730 setOperationAction(ISD::FMA, MVT::f64, Expand); 731 setOperationAction(ISD::FDIV, MVT::f64, Expand); 732 setOperationAction(ISD::FREM, MVT::f64, Expand); 733 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 734 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 735 setOperationAction(ISD::FNEG, MVT::f64, Expand); 736 setOperationAction(ISD::FABS, MVT::f64, Expand); 737 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 738 setOperationAction(ISD::FSIN, MVT::f64, Expand); 739 setOperationAction(ISD::FCOS, MVT::f64, Expand); 740 setOperationAction(ISD::FPOW, MVT::f64, Expand); 741 setOperationAction(ISD::FLOG, MVT::f64, Expand); 742 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 743 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 744 setOperationAction(ISD::FEXP, MVT::f64, Expand); 745 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 746 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 747 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 748 setOperationAction(ISD::FRINT, MVT::f64, Expand); 749 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 750 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 751 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 752 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 753 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 754 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 755 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 756 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 757 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 758 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 759 } 760 761 computeRegisterProperties(Subtarget->getRegisterInfo()); 762 763 // ARM does not have floating-point extending loads. 764 for (MVT VT : MVT::fp_valuetypes()) { 765 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 766 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 767 } 768 769 // ... or truncating stores 770 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 771 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 772 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 773 774 // ARM does not have i1 sign extending load. 775 for (MVT VT : MVT::integer_valuetypes()) 776 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 777 778 // ARM supports all 4 flavors of integer indexed load / store. 779 if (!Subtarget->isThumb1Only()) { 780 for (unsigned im = (unsigned)ISD::PRE_INC; 781 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 782 setIndexedLoadAction(im, MVT::i1, Legal); 783 setIndexedLoadAction(im, MVT::i8, Legal); 784 setIndexedLoadAction(im, MVT::i16, Legal); 785 setIndexedLoadAction(im, MVT::i32, Legal); 786 setIndexedStoreAction(im, MVT::i1, Legal); 787 setIndexedStoreAction(im, MVT::i8, Legal); 788 setIndexedStoreAction(im, MVT::i16, Legal); 789 setIndexedStoreAction(im, MVT::i32, Legal); 790 } 791 } else { 792 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 793 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 794 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 795 } 796 797 setOperationAction(ISD::SADDO, MVT::i32, Custom); 798 setOperationAction(ISD::UADDO, MVT::i32, Custom); 799 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 800 setOperationAction(ISD::USUBO, MVT::i32, Custom); 801 802 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 803 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 804 805 // i64 operation support. 806 setOperationAction(ISD::MUL, MVT::i64, Expand); 807 setOperationAction(ISD::MULHU, MVT::i32, Expand); 808 if (Subtarget->isThumb1Only()) { 809 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 810 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 811 } 812 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 813 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 814 setOperationAction(ISD::MULHS, MVT::i32, Expand); 815 816 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 817 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 818 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 819 setOperationAction(ISD::SRL, MVT::i64, Custom); 820 setOperationAction(ISD::SRA, MVT::i64, Custom); 821 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 822 823 setOperationAction(ISD::ADDC, MVT::i32, Custom); 824 setOperationAction(ISD::ADDE, MVT::i32, Custom); 825 setOperationAction(ISD::SUBC, MVT::i32, Custom); 826 setOperationAction(ISD::SUBE, MVT::i32, Custom); 827 828 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 829 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 830 831 // ARM does not have ROTL. 832 setOperationAction(ISD::ROTL, MVT::i32, Expand); 833 for (MVT VT : MVT::vector_valuetypes()) { 834 setOperationAction(ISD::ROTL, VT, Expand); 835 setOperationAction(ISD::ROTR, VT, Expand); 836 } 837 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 838 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 839 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 840 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 841 842 // @llvm.readcyclecounter requires the Performance Monitors extension. 843 // Default to the 0 expansion on unsupported platforms. 844 // FIXME: Technically there are older ARM CPUs that have 845 // implementation-specific ways of obtaining this information. 846 if (Subtarget->hasPerfMon()) 847 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 848 849 // Only ARMv6 has BSWAP. 850 if (!Subtarget->hasV6Ops()) 851 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 852 853 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 854 : Subtarget->hasDivideInARMMode(); 855 if (!hasDivide) { 856 // These are expanded into libcalls if the cpu doesn't have HW divider. 857 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 858 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 859 } 860 861 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 862 setOperationAction(ISD::SDIV, MVT::i32, Custom); 863 setOperationAction(ISD::UDIV, MVT::i32, Custom); 864 865 setOperationAction(ISD::SDIV, MVT::i64, Custom); 866 setOperationAction(ISD::UDIV, MVT::i64, Custom); 867 } 868 869 setOperationAction(ISD::SREM, MVT::i32, Expand); 870 setOperationAction(ISD::UREM, MVT::i32, Expand); 871 872 // Register based DivRem for AEABI (RTABI 4.2) 873 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 874 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 875 Subtarget->isTargetWindows()) { 876 setOperationAction(ISD::SREM, MVT::i64, Custom); 877 setOperationAction(ISD::UREM, MVT::i64, Custom); 878 HasStandaloneRem = false; 879 880 if (Subtarget->isTargetWindows()) { 881 const struct { 882 const RTLIB::Libcall Op; 883 const char * const Name; 884 const CallingConv::ID CC; 885 } LibraryCalls[] = { 886 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 887 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 888 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 889 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 890 891 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 892 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 893 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 894 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 895 }; 896 897 for (const auto &LC : LibraryCalls) { 898 setLibcallName(LC.Op, LC.Name); 899 setLibcallCallingConv(LC.Op, LC.CC); 900 } 901 } else { 902 const struct { 903 const RTLIB::Libcall Op; 904 const char * const Name; 905 const CallingConv::ID CC; 906 } LibraryCalls[] = { 907 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 908 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 909 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 910 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 911 912 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 913 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 914 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 915 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 916 }; 917 918 for (const auto &LC : LibraryCalls) { 919 setLibcallName(LC.Op, LC.Name); 920 setLibcallCallingConv(LC.Op, LC.CC); 921 } 922 } 923 924 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 925 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 926 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 927 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 928 } else { 929 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 930 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 931 } 932 933 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 934 for (auto &VT : {MVT::f32, MVT::f64}) 935 setOperationAction(ISD::FPOWI, VT, Custom); 936 937 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 938 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 939 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 940 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 941 942 setOperationAction(ISD::TRAP, MVT::Other, Legal); 943 944 // Use the default implementation. 945 setOperationAction(ISD::VASTART, MVT::Other, Custom); 946 setOperationAction(ISD::VAARG, MVT::Other, Expand); 947 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 948 setOperationAction(ISD::VAEND, MVT::Other, Expand); 949 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 950 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 951 952 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 953 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 954 else 955 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 956 957 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 958 // the default expansion. 959 InsertFencesForAtomic = false; 960 if (Subtarget->hasAnyDataBarrier() && 961 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 962 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 963 // to ldrex/strex loops already. 964 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 965 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 966 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 967 968 // On v8, we have particularly efficient implementations of atomic fences 969 // if they can be combined with nearby atomic loads and stores. 970 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 971 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 972 InsertFencesForAtomic = true; 973 } 974 } else { 975 // If there's anything we can use as a barrier, go through custom lowering 976 // for ATOMIC_FENCE. 977 // If target has DMB in thumb, Fences can be inserted. 978 if (Subtarget->hasDataBarrier()) 979 InsertFencesForAtomic = true; 980 981 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 982 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 983 984 // Set them all for expansion, which will force libcalls. 985 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 986 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 987 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 988 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 989 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 990 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 991 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 992 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 993 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 994 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 995 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 996 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 997 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 998 // Unordered/Monotonic case. 999 if (!InsertFencesForAtomic) { 1000 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1001 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1002 } 1003 } 1004 1005 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1006 1007 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1008 if (!Subtarget->hasV6Ops()) { 1009 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1010 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1011 } 1012 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1013 1014 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1015 !Subtarget->isThumb1Only()) { 1016 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1017 // iff target supports vfp2. 1018 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1019 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1020 } 1021 1022 // We want to custom lower some of our intrinsics. 1023 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1024 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1025 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1026 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1027 if (Subtarget->useSjLjEH()) 1028 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1029 1030 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1031 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1032 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1033 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1034 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1035 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1036 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1037 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1038 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1039 1040 // Thumb-1 cannot currently select ARMISD::SUBE. 1041 if (!Subtarget->isThumb1Only()) 1042 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 1043 1044 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 1045 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1046 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1047 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1048 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1049 1050 // We don't support sin/cos/fmod/copysign/pow 1051 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1052 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1053 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1054 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1055 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1056 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1057 setOperationAction(ISD::FREM, MVT::f64, Expand); 1058 setOperationAction(ISD::FREM, MVT::f32, Expand); 1059 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1060 !Subtarget->isThumb1Only()) { 1061 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1062 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1063 } 1064 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1065 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1066 1067 if (!Subtarget->hasVFP4()) { 1068 setOperationAction(ISD::FMA, MVT::f64, Expand); 1069 setOperationAction(ISD::FMA, MVT::f32, Expand); 1070 } 1071 1072 // Various VFP goodness 1073 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1074 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1075 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1076 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1077 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1078 } 1079 1080 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1081 if (!Subtarget->hasFP16()) { 1082 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1083 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1084 } 1085 } 1086 1087 // Combine sin / cos into one node or libcall if possible. 1088 if (Subtarget->hasSinCos()) { 1089 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 1090 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 1091 if (Subtarget->isTargetWatchABI()) { 1092 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP); 1093 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP); 1094 } 1095 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) { 1096 // For iOS, we don't want to the normal expansion of a libcall to 1097 // sincos. We want to issue a libcall to __sincos_stret. 1098 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1099 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1100 } 1101 } 1102 1103 // FP-ARMv8 implements a lot of rounding-like FP operations. 1104 if (Subtarget->hasFPARMv8()) { 1105 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1106 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1107 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1108 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1109 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1110 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1111 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1112 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1113 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1114 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1115 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1116 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1117 1118 if (!Subtarget->isFPOnlySP()) { 1119 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1120 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1121 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1122 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1123 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1124 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1125 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1126 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1127 } 1128 } 1129 1130 if (Subtarget->hasNEON()) { 1131 // vmin and vmax aren't available in a scalar form, so we use 1132 // a NEON instruction with an undef lane instead. 1133 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1134 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1135 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1136 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1137 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1138 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1139 } 1140 1141 // We have target-specific dag combine patterns for the following nodes: 1142 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1143 setTargetDAGCombine(ISD::ADD); 1144 setTargetDAGCombine(ISD::SUB); 1145 setTargetDAGCombine(ISD::MUL); 1146 setTargetDAGCombine(ISD::AND); 1147 setTargetDAGCombine(ISD::OR); 1148 setTargetDAGCombine(ISD::XOR); 1149 1150 if (Subtarget->hasV6Ops()) 1151 setTargetDAGCombine(ISD::SRL); 1152 1153 setStackPointerRegisterToSaveRestore(ARM::SP); 1154 1155 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1156 !Subtarget->hasVFP2()) 1157 setSchedulingPreference(Sched::RegPressure); 1158 else 1159 setSchedulingPreference(Sched::Hybrid); 1160 1161 //// temporary - rewrite interface to use type 1162 MaxStoresPerMemset = 8; 1163 MaxStoresPerMemsetOptSize = 4; 1164 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1165 MaxStoresPerMemcpyOptSize = 2; 1166 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1167 MaxStoresPerMemmoveOptSize = 2; 1168 1169 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1170 // are at least 4 bytes aligned. 1171 setMinStackArgumentAlignment(4); 1172 1173 // Prefer likely predicted branches to selects on out-of-order cores. 1174 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1175 1176 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1177 } 1178 1179 bool ARMTargetLowering::useSoftFloat() const { 1180 return Subtarget->useSoftFloat(); 1181 } 1182 1183 // FIXME: It might make sense to define the representative register class as the 1184 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1185 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1186 // SPR's representative would be DPR_VFP2. This should work well if register 1187 // pressure tracking were modified such that a register use would increment the 1188 // pressure of the register class's representative and all of it's super 1189 // classes' representatives transitively. We have not implemented this because 1190 // of the difficulty prior to coalescing of modeling operand register classes 1191 // due to the common occurrence of cross class copies and subregister insertions 1192 // and extractions. 1193 std::pair<const TargetRegisterClass *, uint8_t> 1194 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1195 MVT VT) const { 1196 const TargetRegisterClass *RRC = nullptr; 1197 uint8_t Cost = 1; 1198 switch (VT.SimpleTy) { 1199 default: 1200 return TargetLowering::findRepresentativeClass(TRI, VT); 1201 // Use DPR as representative register class for all floating point 1202 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1203 // the cost is 1 for both f32 and f64. 1204 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1205 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1206 RRC = &ARM::DPRRegClass; 1207 // When NEON is used for SP, only half of the register file is available 1208 // because operations that define both SP and DP results will be constrained 1209 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1210 // coalescing by double-counting the SP regs. See the FIXME above. 1211 if (Subtarget->useNEONForSinglePrecisionFP()) 1212 Cost = 2; 1213 break; 1214 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1215 case MVT::v4f32: case MVT::v2f64: 1216 RRC = &ARM::DPRRegClass; 1217 Cost = 2; 1218 break; 1219 case MVT::v4i64: 1220 RRC = &ARM::DPRRegClass; 1221 Cost = 4; 1222 break; 1223 case MVT::v8i64: 1224 RRC = &ARM::DPRRegClass; 1225 Cost = 8; 1226 break; 1227 } 1228 return std::make_pair(RRC, Cost); 1229 } 1230 1231 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1232 switch ((ARMISD::NodeType)Opcode) { 1233 case ARMISD::FIRST_NUMBER: break; 1234 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1235 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1236 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1237 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1238 case ARMISD::CALL: return "ARMISD::CALL"; 1239 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1240 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1241 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1242 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1243 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1244 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1245 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1246 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1247 case ARMISD::CMP: return "ARMISD::CMP"; 1248 case ARMISD::CMN: return "ARMISD::CMN"; 1249 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1250 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1251 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1252 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1253 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1254 1255 case ARMISD::CMOV: return "ARMISD::CMOV"; 1256 1257 case ARMISD::SSAT: return "ARMISD::SSAT"; 1258 1259 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1260 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1261 case ARMISD::RRX: return "ARMISD::RRX"; 1262 1263 case ARMISD::ADDC: return "ARMISD::ADDC"; 1264 case ARMISD::ADDE: return "ARMISD::ADDE"; 1265 case ARMISD::SUBC: return "ARMISD::SUBC"; 1266 case ARMISD::SUBE: return "ARMISD::SUBE"; 1267 1268 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1269 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1270 1271 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1272 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1273 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1274 1275 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1276 1277 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1278 1279 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1280 1281 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1282 1283 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1284 1285 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1286 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1287 1288 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1289 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1290 case ARMISD::VCGE: return "ARMISD::VCGE"; 1291 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1292 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1293 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1294 case ARMISD::VCGT: return "ARMISD::VCGT"; 1295 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1296 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1297 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1298 case ARMISD::VTST: return "ARMISD::VTST"; 1299 1300 case ARMISD::VSHL: return "ARMISD::VSHL"; 1301 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1302 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1303 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1304 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1305 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1306 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1307 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1308 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1309 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1310 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1311 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1312 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1313 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1314 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1315 case ARMISD::VSLI: return "ARMISD::VSLI"; 1316 case ARMISD::VSRI: return "ARMISD::VSRI"; 1317 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1318 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1319 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1320 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1321 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1322 case ARMISD::VDUP: return "ARMISD::VDUP"; 1323 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1324 case ARMISD::VEXT: return "ARMISD::VEXT"; 1325 case ARMISD::VREV64: return "ARMISD::VREV64"; 1326 case ARMISD::VREV32: return "ARMISD::VREV32"; 1327 case ARMISD::VREV16: return "ARMISD::VREV16"; 1328 case ARMISD::VZIP: return "ARMISD::VZIP"; 1329 case ARMISD::VUZP: return "ARMISD::VUZP"; 1330 case ARMISD::VTRN: return "ARMISD::VTRN"; 1331 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1332 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1333 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1334 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1335 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1336 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1337 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1338 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1339 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1340 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1341 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1342 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1343 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1344 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1345 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1346 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1347 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1348 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1349 case ARMISD::BFI: return "ARMISD::BFI"; 1350 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1351 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1352 case ARMISD::VBSL: return "ARMISD::VBSL"; 1353 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1354 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1355 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1356 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1357 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1358 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1359 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1360 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1361 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1362 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1363 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1364 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1365 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1366 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1367 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1368 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1369 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1370 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1371 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1372 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1373 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1374 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1375 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1376 } 1377 return nullptr; 1378 } 1379 1380 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1381 EVT VT) const { 1382 if (!VT.isVector()) 1383 return getPointerTy(DL); 1384 return VT.changeVectorElementTypeToInteger(); 1385 } 1386 1387 /// getRegClassFor - Return the register class that should be used for the 1388 /// specified value type. 1389 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1390 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1391 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1392 // load / store 4 to 8 consecutive D registers. 1393 if (Subtarget->hasNEON()) { 1394 if (VT == MVT::v4i64) 1395 return &ARM::QQPRRegClass; 1396 if (VT == MVT::v8i64) 1397 return &ARM::QQQQPRRegClass; 1398 } 1399 return TargetLowering::getRegClassFor(VT); 1400 } 1401 1402 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1403 // source/dest is aligned and the copy size is large enough. We therefore want 1404 // to align such objects passed to memory intrinsics. 1405 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1406 unsigned &PrefAlign) const { 1407 if (!isa<MemIntrinsic>(CI)) 1408 return false; 1409 MinSize = 8; 1410 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1411 // cycle faster than 4-byte aligned LDM. 1412 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1413 return true; 1414 } 1415 1416 // Create a fast isel object. 1417 FastISel * 1418 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1419 const TargetLibraryInfo *libInfo) const { 1420 return ARM::createFastISel(funcInfo, libInfo); 1421 } 1422 1423 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1424 unsigned NumVals = N->getNumValues(); 1425 if (!NumVals) 1426 return Sched::RegPressure; 1427 1428 for (unsigned i = 0; i != NumVals; ++i) { 1429 EVT VT = N->getValueType(i); 1430 if (VT == MVT::Glue || VT == MVT::Other) 1431 continue; 1432 if (VT.isFloatingPoint() || VT.isVector()) 1433 return Sched::ILP; 1434 } 1435 1436 if (!N->isMachineOpcode()) 1437 return Sched::RegPressure; 1438 1439 // Load are scheduled for latency even if there instruction itinerary 1440 // is not available. 1441 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1442 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1443 1444 if (MCID.getNumDefs() == 0) 1445 return Sched::RegPressure; 1446 if (!Itins->isEmpty() && 1447 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1448 return Sched::ILP; 1449 1450 return Sched::RegPressure; 1451 } 1452 1453 //===----------------------------------------------------------------------===// 1454 // Lowering Code 1455 //===----------------------------------------------------------------------===// 1456 1457 static bool isSRL16(const SDValue &Op) { 1458 if (Op.getOpcode() != ISD::SRL) 1459 return false; 1460 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1461 return Const->getZExtValue() == 16; 1462 return false; 1463 } 1464 1465 static bool isSRA16(const SDValue &Op) { 1466 if (Op.getOpcode() != ISD::SRA) 1467 return false; 1468 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1469 return Const->getZExtValue() == 16; 1470 return false; 1471 } 1472 1473 static bool isSHL16(const SDValue &Op) { 1474 if (Op.getOpcode() != ISD::SHL) 1475 return false; 1476 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1477 return Const->getZExtValue() == 16; 1478 return false; 1479 } 1480 1481 // Check for a signed 16-bit value. We special case SRA because it makes it 1482 // more simple when also looking for SRAs that aren't sign extending a 1483 // smaller value. Without the check, we'd need to take extra care with 1484 // checking order for some operations. 1485 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1486 if (isSRA16(Op)) 1487 return isSHL16(Op.getOperand(0)); 1488 return DAG.ComputeNumSignBits(Op) == 17; 1489 } 1490 1491 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1492 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1493 switch (CC) { 1494 default: llvm_unreachable("Unknown condition code!"); 1495 case ISD::SETNE: return ARMCC::NE; 1496 case ISD::SETEQ: return ARMCC::EQ; 1497 case ISD::SETGT: return ARMCC::GT; 1498 case ISD::SETGE: return ARMCC::GE; 1499 case ISD::SETLT: return ARMCC::LT; 1500 case ISD::SETLE: return ARMCC::LE; 1501 case ISD::SETUGT: return ARMCC::HI; 1502 case ISD::SETUGE: return ARMCC::HS; 1503 case ISD::SETULT: return ARMCC::LO; 1504 case ISD::SETULE: return ARMCC::LS; 1505 } 1506 } 1507 1508 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1509 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1510 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1511 CondCode2 = ARMCC::AL; 1512 InvalidOnQNaN = true; 1513 switch (CC) { 1514 default: llvm_unreachable("Unknown FP condition!"); 1515 case ISD::SETEQ: 1516 case ISD::SETOEQ: 1517 CondCode = ARMCC::EQ; 1518 InvalidOnQNaN = false; 1519 break; 1520 case ISD::SETGT: 1521 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1522 case ISD::SETGE: 1523 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1524 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1525 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1526 case ISD::SETONE: 1527 CondCode = ARMCC::MI; 1528 CondCode2 = ARMCC::GT; 1529 InvalidOnQNaN = false; 1530 break; 1531 case ISD::SETO: CondCode = ARMCC::VC; break; 1532 case ISD::SETUO: CondCode = ARMCC::VS; break; 1533 case ISD::SETUEQ: 1534 CondCode = ARMCC::EQ; 1535 CondCode2 = ARMCC::VS; 1536 InvalidOnQNaN = false; 1537 break; 1538 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1539 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1540 case ISD::SETLT: 1541 case ISD::SETULT: CondCode = ARMCC::LT; break; 1542 case ISD::SETLE: 1543 case ISD::SETULE: CondCode = ARMCC::LE; break; 1544 case ISD::SETNE: 1545 case ISD::SETUNE: 1546 CondCode = ARMCC::NE; 1547 InvalidOnQNaN = false; 1548 break; 1549 } 1550 } 1551 1552 //===----------------------------------------------------------------------===// 1553 // Calling Convention Implementation 1554 //===----------------------------------------------------------------------===// 1555 1556 #include "ARMGenCallingConv.inc" 1557 1558 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1559 /// account presence of floating point hardware and calling convention 1560 /// limitations, such as support for variadic functions. 1561 CallingConv::ID 1562 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1563 bool isVarArg) const { 1564 switch (CC) { 1565 default: 1566 report_fatal_error("Unsupported calling convention"); 1567 case CallingConv::ARM_AAPCS: 1568 case CallingConv::ARM_APCS: 1569 case CallingConv::GHC: 1570 return CC; 1571 case CallingConv::PreserveMost: 1572 return CallingConv::PreserveMost; 1573 case CallingConv::ARM_AAPCS_VFP: 1574 case CallingConv::Swift: 1575 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1576 case CallingConv::C: 1577 if (!Subtarget->isAAPCS_ABI()) 1578 return CallingConv::ARM_APCS; 1579 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1580 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1581 !isVarArg) 1582 return CallingConv::ARM_AAPCS_VFP; 1583 else 1584 return CallingConv::ARM_AAPCS; 1585 case CallingConv::Fast: 1586 case CallingConv::CXX_FAST_TLS: 1587 if (!Subtarget->isAAPCS_ABI()) { 1588 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1589 return CallingConv::Fast; 1590 return CallingConv::ARM_APCS; 1591 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1592 return CallingConv::ARM_AAPCS_VFP; 1593 else 1594 return CallingConv::ARM_AAPCS; 1595 } 1596 } 1597 1598 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1599 bool isVarArg) const { 1600 return CCAssignFnForNode(CC, false, isVarArg); 1601 } 1602 1603 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1604 bool isVarArg) const { 1605 return CCAssignFnForNode(CC, true, isVarArg); 1606 } 1607 1608 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1609 /// CallingConvention. 1610 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1611 bool Return, 1612 bool isVarArg) const { 1613 switch (getEffectiveCallingConv(CC, isVarArg)) { 1614 default: 1615 report_fatal_error("Unsupported calling convention"); 1616 case CallingConv::ARM_APCS: 1617 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1618 case CallingConv::ARM_AAPCS: 1619 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1620 case CallingConv::ARM_AAPCS_VFP: 1621 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1622 case CallingConv::Fast: 1623 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1624 case CallingConv::GHC: 1625 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1626 case CallingConv::PreserveMost: 1627 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1628 } 1629 } 1630 1631 /// LowerCallResult - Lower the result values of a call into the 1632 /// appropriate copies out of appropriate physical registers. 1633 SDValue ARMTargetLowering::LowerCallResult( 1634 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1635 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1636 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1637 SDValue ThisVal) const { 1638 // Assign locations to each value returned by this call. 1639 SmallVector<CCValAssign, 16> RVLocs; 1640 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1641 *DAG.getContext()); 1642 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1643 1644 // Copy all of the result registers out of their specified physreg. 1645 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1646 CCValAssign VA = RVLocs[i]; 1647 1648 // Pass 'this' value directly from the argument to return value, to avoid 1649 // reg unit interference 1650 if (i == 0 && isThisReturn) { 1651 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1652 "unexpected return calling convention register assignment"); 1653 InVals.push_back(ThisVal); 1654 continue; 1655 } 1656 1657 SDValue Val; 1658 if (VA.needsCustom()) { 1659 // Handle f64 or half of a v2f64. 1660 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1661 InFlag); 1662 Chain = Lo.getValue(1); 1663 InFlag = Lo.getValue(2); 1664 VA = RVLocs[++i]; // skip ahead to next loc 1665 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1666 InFlag); 1667 Chain = Hi.getValue(1); 1668 InFlag = Hi.getValue(2); 1669 if (!Subtarget->isLittle()) 1670 std::swap (Lo, Hi); 1671 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1672 1673 if (VA.getLocVT() == MVT::v2f64) { 1674 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1675 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1676 DAG.getConstant(0, dl, MVT::i32)); 1677 1678 VA = RVLocs[++i]; // skip ahead to next loc 1679 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1680 Chain = Lo.getValue(1); 1681 InFlag = Lo.getValue(2); 1682 VA = RVLocs[++i]; // skip ahead to next loc 1683 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1684 Chain = Hi.getValue(1); 1685 InFlag = Hi.getValue(2); 1686 if (!Subtarget->isLittle()) 1687 std::swap (Lo, Hi); 1688 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1689 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1690 DAG.getConstant(1, dl, MVT::i32)); 1691 } 1692 } else { 1693 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1694 InFlag); 1695 Chain = Val.getValue(1); 1696 InFlag = Val.getValue(2); 1697 } 1698 1699 switch (VA.getLocInfo()) { 1700 default: llvm_unreachable("Unknown loc info!"); 1701 case CCValAssign::Full: break; 1702 case CCValAssign::BCvt: 1703 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1704 break; 1705 } 1706 1707 InVals.push_back(Val); 1708 } 1709 1710 return Chain; 1711 } 1712 1713 /// LowerMemOpCallTo - Store the argument to the stack. 1714 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1715 SDValue Arg, const SDLoc &dl, 1716 SelectionDAG &DAG, 1717 const CCValAssign &VA, 1718 ISD::ArgFlagsTy Flags) const { 1719 unsigned LocMemOffset = VA.getLocMemOffset(); 1720 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1721 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1722 StackPtr, PtrOff); 1723 return DAG.getStore( 1724 Chain, dl, Arg, PtrOff, 1725 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1726 } 1727 1728 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1729 SDValue Chain, SDValue &Arg, 1730 RegsToPassVector &RegsToPass, 1731 CCValAssign &VA, CCValAssign &NextVA, 1732 SDValue &StackPtr, 1733 SmallVectorImpl<SDValue> &MemOpChains, 1734 ISD::ArgFlagsTy Flags) const { 1735 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1736 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1737 unsigned id = Subtarget->isLittle() ? 0 : 1; 1738 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1739 1740 if (NextVA.isRegLoc()) 1741 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1742 else { 1743 assert(NextVA.isMemLoc()); 1744 if (!StackPtr.getNode()) 1745 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1746 getPointerTy(DAG.getDataLayout())); 1747 1748 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1749 dl, DAG, NextVA, 1750 Flags)); 1751 } 1752 } 1753 1754 /// LowerCall - Lowering a call into a callseq_start <- 1755 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1756 /// nodes. 1757 SDValue 1758 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1759 SmallVectorImpl<SDValue> &InVals) const { 1760 SelectionDAG &DAG = CLI.DAG; 1761 SDLoc &dl = CLI.DL; 1762 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1763 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1764 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1765 SDValue Chain = CLI.Chain; 1766 SDValue Callee = CLI.Callee; 1767 bool &isTailCall = CLI.IsTailCall; 1768 CallingConv::ID CallConv = CLI.CallConv; 1769 bool doesNotRet = CLI.DoesNotReturn; 1770 bool isVarArg = CLI.IsVarArg; 1771 1772 MachineFunction &MF = DAG.getMachineFunction(); 1773 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1774 bool isThisReturn = false; 1775 bool isSibCall = false; 1776 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 1777 1778 // Disable tail calls if they're not supported. 1779 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1780 isTailCall = false; 1781 1782 if (isTailCall) { 1783 // Check if it's really possible to do a tail call. 1784 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1785 isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(), 1786 Outs, OutVals, Ins, DAG); 1787 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1788 report_fatal_error("failed to perform tail call elimination on a call " 1789 "site marked musttail"); 1790 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1791 // detected sibcalls. 1792 if (isTailCall) { 1793 ++NumTailCalls; 1794 isSibCall = true; 1795 } 1796 } 1797 1798 // Analyze operands of the call, assigning locations to each operand. 1799 SmallVector<CCValAssign, 16> ArgLocs; 1800 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1801 *DAG.getContext()); 1802 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1803 1804 // Get a count of how many bytes are to be pushed on the stack. 1805 unsigned NumBytes = CCInfo.getNextStackOffset(); 1806 1807 // For tail calls, memory operands are available in our caller's stack. 1808 if (isSibCall) 1809 NumBytes = 0; 1810 1811 // Adjust the stack pointer for the new arguments... 1812 // These operations are automatically eliminated by the prolog/epilog pass 1813 if (!isSibCall) 1814 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 1815 1816 SDValue StackPtr = 1817 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1818 1819 RegsToPassVector RegsToPass; 1820 SmallVector<SDValue, 8> MemOpChains; 1821 1822 // Walk the register/memloc assignments, inserting copies/loads. In the case 1823 // of tail call optimization, arguments are handled later. 1824 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1825 i != e; 1826 ++i, ++realArgIdx) { 1827 CCValAssign &VA = ArgLocs[i]; 1828 SDValue Arg = OutVals[realArgIdx]; 1829 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1830 bool isByVal = Flags.isByVal(); 1831 1832 // Promote the value if needed. 1833 switch (VA.getLocInfo()) { 1834 default: llvm_unreachable("Unknown loc info!"); 1835 case CCValAssign::Full: break; 1836 case CCValAssign::SExt: 1837 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1838 break; 1839 case CCValAssign::ZExt: 1840 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1841 break; 1842 case CCValAssign::AExt: 1843 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1844 break; 1845 case CCValAssign::BCvt: 1846 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1847 break; 1848 } 1849 1850 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1851 if (VA.needsCustom()) { 1852 if (VA.getLocVT() == MVT::v2f64) { 1853 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1854 DAG.getConstant(0, dl, MVT::i32)); 1855 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1856 DAG.getConstant(1, dl, MVT::i32)); 1857 1858 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1859 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1860 1861 VA = ArgLocs[++i]; // skip ahead to next loc 1862 if (VA.isRegLoc()) { 1863 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1864 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1865 } else { 1866 assert(VA.isMemLoc()); 1867 1868 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1869 dl, DAG, VA, Flags)); 1870 } 1871 } else { 1872 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1873 StackPtr, MemOpChains, Flags); 1874 } 1875 } else if (VA.isRegLoc()) { 1876 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1877 Outs[0].VT == MVT::i32) { 1878 assert(VA.getLocVT() == MVT::i32 && 1879 "unexpected calling convention register assignment"); 1880 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1881 "unexpected use of 'returned'"); 1882 isThisReturn = true; 1883 } 1884 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1885 } else if (isByVal) { 1886 assert(VA.isMemLoc()); 1887 unsigned offset = 0; 1888 1889 // True if this byval aggregate will be split between registers 1890 // and memory. 1891 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1892 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1893 1894 if (CurByValIdx < ByValArgsCount) { 1895 1896 unsigned RegBegin, RegEnd; 1897 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1898 1899 EVT PtrVT = 1900 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1901 unsigned int i, j; 1902 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1903 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1904 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1905 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1906 MachinePointerInfo(), 1907 DAG.InferPtrAlignment(AddArg)); 1908 MemOpChains.push_back(Load.getValue(1)); 1909 RegsToPass.push_back(std::make_pair(j, Load)); 1910 } 1911 1912 // If parameter size outsides register area, "offset" value 1913 // helps us to calculate stack slot for remained part properly. 1914 offset = RegEnd - RegBegin; 1915 1916 CCInfo.nextInRegsParam(); 1917 } 1918 1919 if (Flags.getByValSize() > 4*offset) { 1920 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1921 unsigned LocMemOffset = VA.getLocMemOffset(); 1922 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1923 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1924 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1925 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1926 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1927 MVT::i32); 1928 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1929 MVT::i32); 1930 1931 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1932 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1933 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1934 Ops)); 1935 } 1936 } else if (!isSibCall) { 1937 assert(VA.isMemLoc()); 1938 1939 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1940 dl, DAG, VA, Flags)); 1941 } 1942 } 1943 1944 if (!MemOpChains.empty()) 1945 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1946 1947 // Build a sequence of copy-to-reg nodes chained together with token chain 1948 // and flag operands which copy the outgoing args into the appropriate regs. 1949 SDValue InFlag; 1950 // Tail call byval lowering might overwrite argument registers so in case of 1951 // tail call optimization the copies to registers are lowered later. 1952 if (!isTailCall) 1953 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1954 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1955 RegsToPass[i].second, InFlag); 1956 InFlag = Chain.getValue(1); 1957 } 1958 1959 // For tail calls lower the arguments to the 'real' stack slot. 1960 if (isTailCall) { 1961 // Force all the incoming stack arguments to be loaded from the stack 1962 // before any new outgoing arguments are stored to the stack, because the 1963 // outgoing stack slots may alias the incoming argument stack slots, and 1964 // the alias isn't otherwise explicit. This is slightly more conservative 1965 // than necessary, because it means that each store effectively depends 1966 // on every argument instead of just those arguments it would clobber. 1967 1968 // Do not flag preceding copytoreg stuff together with the following stuff. 1969 InFlag = SDValue(); 1970 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1971 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1972 RegsToPass[i].second, InFlag); 1973 InFlag = Chain.getValue(1); 1974 } 1975 InFlag = SDValue(); 1976 } 1977 1978 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1979 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1980 // node so that legalize doesn't hack it. 1981 bool isDirect = false; 1982 1983 const TargetMachine &TM = getTargetMachine(); 1984 const Module *Mod = MF.getFunction().getParent(); 1985 const GlobalValue *GV = nullptr; 1986 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1987 GV = G->getGlobal(); 1988 bool isStub = 1989 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 1990 1991 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 1992 bool isLocalARMFunc = false; 1993 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1994 auto PtrVt = getPointerTy(DAG.getDataLayout()); 1995 1996 if (Subtarget->genLongCalls()) { 1997 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 1998 "long-calls codegen is not position independent!"); 1999 // Handle a global address or an external symbol. If it's not one of 2000 // those, the target's already in a register, so we don't need to do 2001 // anything extra. 2002 if (isa<GlobalAddressSDNode>(Callee)) { 2003 // Create a constant pool entry for the callee address 2004 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2005 ARMConstantPoolValue *CPV = 2006 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2007 2008 // Get the address of the callee into a register 2009 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2010 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2011 Callee = DAG.getLoad( 2012 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2013 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2014 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2015 const char *Sym = S->getSymbol(); 2016 2017 // Create a constant pool entry for the callee address 2018 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2019 ARMConstantPoolValue *CPV = 2020 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2021 ARMPCLabelIndex, 0); 2022 // Get the address of the callee into a register 2023 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2024 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2025 Callee = DAG.getLoad( 2026 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2027 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2028 } 2029 } else if (isa<GlobalAddressSDNode>(Callee)) { 2030 // If we're optimizing for minimum size and the function is called three or 2031 // more times in this block, we can improve codesize by calling indirectly 2032 // as BLXr has a 16-bit encoding. 2033 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2034 auto *BB = CLI.CS.getParent(); 2035 bool PreferIndirect = 2036 Subtarget->isThumb() && MF.getFunction().optForMinSize() && 2037 count_if(GV->users(), [&BB](const User *U) { 2038 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2039 }) > 2; 2040 2041 if (!PreferIndirect) { 2042 isDirect = true; 2043 bool isDef = GV->isStrongDefinitionForLinker(); 2044 2045 // ARM call to a local ARM function is predicable. 2046 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2047 // tBX takes a register source operand. 2048 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2049 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2050 Callee = DAG.getNode( 2051 ARMISD::WrapperPIC, dl, PtrVt, 2052 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2053 Callee = DAG.getLoad( 2054 PtrVt, dl, DAG.getEntryNode(), Callee, 2055 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2056 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2057 MachineMemOperand::MOInvariant); 2058 } else if (Subtarget->isTargetCOFF()) { 2059 assert(Subtarget->isTargetWindows() && 2060 "Windows is the only supported COFF target"); 2061 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2062 ? ARMII::MO_DLLIMPORT 2063 : ARMII::MO_NO_FLAG; 2064 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2065 TargetFlags); 2066 if (GV->hasDLLImportStorageClass()) 2067 Callee = 2068 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2069 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2070 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2071 } else { 2072 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2073 } 2074 } 2075 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2076 isDirect = true; 2077 // tBX takes a register source operand. 2078 const char *Sym = S->getSymbol(); 2079 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2080 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2081 ARMConstantPoolValue *CPV = 2082 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2083 ARMPCLabelIndex, 4); 2084 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2085 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2086 Callee = DAG.getLoad( 2087 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2088 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2089 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2090 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2091 } else { 2092 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2093 } 2094 } 2095 2096 // FIXME: handle tail calls differently. 2097 unsigned CallOpc; 2098 if (Subtarget->isThumb()) { 2099 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2100 CallOpc = ARMISD::CALL_NOLINK; 2101 else 2102 CallOpc = ARMISD::CALL; 2103 } else { 2104 if (!isDirect && !Subtarget->hasV5TOps()) 2105 CallOpc = ARMISD::CALL_NOLINK; 2106 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2107 // Emit regular call when code size is the priority 2108 !MF.getFunction().optForMinSize()) 2109 // "mov lr, pc; b _foo" to avoid confusing the RSP 2110 CallOpc = ARMISD::CALL_NOLINK; 2111 else 2112 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2113 } 2114 2115 std::vector<SDValue> Ops; 2116 Ops.push_back(Chain); 2117 Ops.push_back(Callee); 2118 2119 // Add argument registers to the end of the list so that they are known live 2120 // into the call. 2121 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2122 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2123 RegsToPass[i].second.getValueType())); 2124 2125 // Add a register mask operand representing the call-preserved registers. 2126 if (!isTailCall) { 2127 const uint32_t *Mask; 2128 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2129 if (isThisReturn) { 2130 // For 'this' returns, use the R0-preserving mask if applicable 2131 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2132 if (!Mask) { 2133 // Set isThisReturn to false if the calling convention is not one that 2134 // allows 'returned' to be modeled in this way, so LowerCallResult does 2135 // not try to pass 'this' straight through 2136 isThisReturn = false; 2137 Mask = ARI->getCallPreservedMask(MF, CallConv); 2138 } 2139 } else 2140 Mask = ARI->getCallPreservedMask(MF, CallConv); 2141 2142 assert(Mask && "Missing call preserved mask for calling convention"); 2143 Ops.push_back(DAG.getRegisterMask(Mask)); 2144 } 2145 2146 if (InFlag.getNode()) 2147 Ops.push_back(InFlag); 2148 2149 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2150 if (isTailCall) { 2151 MF.getFrameInfo().setHasTailCall(); 2152 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2153 } 2154 2155 // Returns a chain and a flag for retval copy to use. 2156 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2157 InFlag = Chain.getValue(1); 2158 2159 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2160 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2161 if (!Ins.empty()) 2162 InFlag = Chain.getValue(1); 2163 2164 // Handle result values, copying them out of physregs into vregs that we 2165 // return. 2166 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2167 InVals, isThisReturn, 2168 isThisReturn ? OutVals[0] : SDValue()); 2169 } 2170 2171 /// HandleByVal - Every parameter *after* a byval parameter is passed 2172 /// on the stack. Remember the next parameter register to allocate, 2173 /// and then confiscate the rest of the parameter registers to insure 2174 /// this. 2175 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2176 unsigned Align) const { 2177 // Byval (as with any stack) slots are always at least 4 byte aligned. 2178 Align = std::max(Align, 4U); 2179 2180 unsigned Reg = State->AllocateReg(GPRArgRegs); 2181 if (!Reg) 2182 return; 2183 2184 unsigned AlignInRegs = Align / 4; 2185 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2186 for (unsigned i = 0; i < Waste; ++i) 2187 Reg = State->AllocateReg(GPRArgRegs); 2188 2189 if (!Reg) 2190 return; 2191 2192 unsigned Excess = 4 * (ARM::R4 - Reg); 2193 2194 // Special case when NSAA != SP and parameter size greater than size of 2195 // all remained GPR regs. In that case we can't split parameter, we must 2196 // send it to stack. We also must set NCRN to R4, so waste all 2197 // remained registers. 2198 const unsigned NSAAOffset = State->getNextStackOffset(); 2199 if (NSAAOffset != 0 && Size > Excess) { 2200 while (State->AllocateReg(GPRArgRegs)) 2201 ; 2202 return; 2203 } 2204 2205 // First register for byval parameter is the first register that wasn't 2206 // allocated before this method call, so it would be "reg". 2207 // If parameter is small enough to be saved in range [reg, r4), then 2208 // the end (first after last) register would be reg + param-size-in-regs, 2209 // else parameter would be splitted between registers and stack, 2210 // end register would be r4 in this case. 2211 unsigned ByValRegBegin = Reg; 2212 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2213 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2214 // Note, first register is allocated in the beginning of function already, 2215 // allocate remained amount of registers we need. 2216 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2217 State->AllocateReg(GPRArgRegs); 2218 // A byval parameter that is split between registers and memory needs its 2219 // size truncated here. 2220 // In the case where the entire structure fits in registers, we set the 2221 // size in memory to zero. 2222 Size = std::max<int>(Size - Excess, 0); 2223 } 2224 2225 /// MatchingStackOffset - Return true if the given stack call argument is 2226 /// already available in the same position (relatively) of the caller's 2227 /// incoming argument stack. 2228 static 2229 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2230 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2231 const TargetInstrInfo *TII) { 2232 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2233 int FI = std::numeric_limits<int>::max(); 2234 if (Arg.getOpcode() == ISD::CopyFromReg) { 2235 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2236 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2237 return false; 2238 MachineInstr *Def = MRI->getVRegDef(VR); 2239 if (!Def) 2240 return false; 2241 if (!Flags.isByVal()) { 2242 if (!TII->isLoadFromStackSlot(*Def, FI)) 2243 return false; 2244 } else { 2245 return false; 2246 } 2247 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2248 if (Flags.isByVal()) 2249 // ByVal argument is passed in as a pointer but it's now being 2250 // dereferenced. e.g. 2251 // define @foo(%struct.X* %A) { 2252 // tail call @bar(%struct.X* byval %A) 2253 // } 2254 return false; 2255 SDValue Ptr = Ld->getBasePtr(); 2256 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2257 if (!FINode) 2258 return false; 2259 FI = FINode->getIndex(); 2260 } else 2261 return false; 2262 2263 assert(FI != std::numeric_limits<int>::max()); 2264 if (!MFI.isFixedObjectIndex(FI)) 2265 return false; 2266 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2267 } 2268 2269 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2270 /// for tail call optimization. Targets which want to do tail call 2271 /// optimization should implement this function. 2272 bool 2273 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2274 CallingConv::ID CalleeCC, 2275 bool isVarArg, 2276 bool isCalleeStructRet, 2277 bool isCallerStructRet, 2278 const SmallVectorImpl<ISD::OutputArg> &Outs, 2279 const SmallVectorImpl<SDValue> &OutVals, 2280 const SmallVectorImpl<ISD::InputArg> &Ins, 2281 SelectionDAG& DAG) const { 2282 MachineFunction &MF = DAG.getMachineFunction(); 2283 const Function &CallerF = MF.getFunction(); 2284 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2285 2286 assert(Subtarget->supportsTailCall()); 2287 2288 // Tail calls to function pointers cannot be optimized for Thumb1 if the args 2289 // to the call take up r0-r3. The reason is that there are no legal registers 2290 // left to hold the pointer to the function to be called. 2291 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2292 !isa<GlobalAddressSDNode>(Callee.getNode())) 2293 return false; 2294 2295 // Look for obvious safe cases to perform tail call optimization that do not 2296 // require ABI changes. This is what gcc calls sibcall. 2297 2298 // Exception-handling functions need a special set of instructions to indicate 2299 // a return to the hardware. Tail-calling another function would probably 2300 // break this. 2301 if (CallerF.hasFnAttribute("interrupt")) 2302 return false; 2303 2304 // Also avoid sibcall optimization if either caller or callee uses struct 2305 // return semantics. 2306 if (isCalleeStructRet || isCallerStructRet) 2307 return false; 2308 2309 // Externally-defined functions with weak linkage should not be 2310 // tail-called on ARM when the OS does not support dynamic 2311 // pre-emption of symbols, as the AAELF spec requires normal calls 2312 // to undefined weak functions to be replaced with a NOP or jump to the 2313 // next instruction. The behaviour of branch instructions in this 2314 // situation (as used for tail calls) is implementation-defined, so we 2315 // cannot rely on the linker replacing the tail call with a return. 2316 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2317 const GlobalValue *GV = G->getGlobal(); 2318 const Triple &TT = getTargetMachine().getTargetTriple(); 2319 if (GV->hasExternalWeakLinkage() && 2320 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2321 return false; 2322 } 2323 2324 // Check that the call results are passed in the same way. 2325 LLVMContext &C = *DAG.getContext(); 2326 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2327 CCAssignFnForReturn(CalleeCC, isVarArg), 2328 CCAssignFnForReturn(CallerCC, isVarArg))) 2329 return false; 2330 // The callee has to preserve all registers the caller needs to preserve. 2331 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2332 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2333 if (CalleeCC != CallerCC) { 2334 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2335 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2336 return false; 2337 } 2338 2339 // If Caller's vararg or byval argument has been split between registers and 2340 // stack, do not perform tail call, since part of the argument is in caller's 2341 // local frame. 2342 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2343 if (AFI_Caller->getArgRegsSaveSize()) 2344 return false; 2345 2346 // If the callee takes no arguments then go on to check the results of the 2347 // call. 2348 if (!Outs.empty()) { 2349 // Check if stack adjustment is needed. For now, do not do this if any 2350 // argument is passed on the stack. 2351 SmallVector<CCValAssign, 16> ArgLocs; 2352 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2353 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2354 if (CCInfo.getNextStackOffset()) { 2355 // Check if the arguments are already laid out in the right way as 2356 // the caller's fixed stack objects. 2357 MachineFrameInfo &MFI = MF.getFrameInfo(); 2358 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2359 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2360 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2361 i != e; 2362 ++i, ++realArgIdx) { 2363 CCValAssign &VA = ArgLocs[i]; 2364 EVT RegVT = VA.getLocVT(); 2365 SDValue Arg = OutVals[realArgIdx]; 2366 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2367 if (VA.getLocInfo() == CCValAssign::Indirect) 2368 return false; 2369 if (VA.needsCustom()) { 2370 // f64 and vector types are split into multiple registers or 2371 // register/stack-slot combinations. The types will not match 2372 // the registers; give up on memory f64 refs until we figure 2373 // out what to do about this. 2374 if (!VA.isRegLoc()) 2375 return false; 2376 if (!ArgLocs[++i].isRegLoc()) 2377 return false; 2378 if (RegVT == MVT::v2f64) { 2379 if (!ArgLocs[++i].isRegLoc()) 2380 return false; 2381 if (!ArgLocs[++i].isRegLoc()) 2382 return false; 2383 } 2384 } else if (!VA.isRegLoc()) { 2385 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2386 MFI, MRI, TII)) 2387 return false; 2388 } 2389 } 2390 } 2391 2392 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2393 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2394 return false; 2395 } 2396 2397 return true; 2398 } 2399 2400 bool 2401 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2402 MachineFunction &MF, bool isVarArg, 2403 const SmallVectorImpl<ISD::OutputArg> &Outs, 2404 LLVMContext &Context) const { 2405 SmallVector<CCValAssign, 16> RVLocs; 2406 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2407 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2408 } 2409 2410 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2411 const SDLoc &DL, SelectionDAG &DAG) { 2412 const MachineFunction &MF = DAG.getMachineFunction(); 2413 const Function &F = MF.getFunction(); 2414 2415 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2416 2417 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2418 // version of the "preferred return address". These offsets affect the return 2419 // instruction if this is a return from PL1 without hypervisor extensions. 2420 // IRQ/FIQ: +4 "subs pc, lr, #4" 2421 // SWI: 0 "subs pc, lr, #0" 2422 // ABORT: +4 "subs pc, lr, #4" 2423 // UNDEF: +4/+2 "subs pc, lr, #0" 2424 // UNDEF varies depending on where the exception came from ARM or Thumb 2425 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2426 2427 int64_t LROffset; 2428 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2429 IntKind == "ABORT") 2430 LROffset = 4; 2431 else if (IntKind == "SWI" || IntKind == "UNDEF") 2432 LROffset = 0; 2433 else 2434 report_fatal_error("Unsupported interrupt attribute. If present, value " 2435 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2436 2437 RetOps.insert(RetOps.begin() + 1, 2438 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2439 2440 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2441 } 2442 2443 SDValue 2444 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2445 bool isVarArg, 2446 const SmallVectorImpl<ISD::OutputArg> &Outs, 2447 const SmallVectorImpl<SDValue> &OutVals, 2448 const SDLoc &dl, SelectionDAG &DAG) const { 2449 // CCValAssign - represent the assignment of the return value to a location. 2450 SmallVector<CCValAssign, 16> RVLocs; 2451 2452 // CCState - Info about the registers and stack slots. 2453 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2454 *DAG.getContext()); 2455 2456 // Analyze outgoing return values. 2457 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2458 2459 SDValue Flag; 2460 SmallVector<SDValue, 4> RetOps; 2461 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2462 bool isLittleEndian = Subtarget->isLittle(); 2463 2464 MachineFunction &MF = DAG.getMachineFunction(); 2465 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2466 AFI->setReturnRegsCount(RVLocs.size()); 2467 2468 // Copy the result values into the output registers. 2469 for (unsigned i = 0, realRVLocIdx = 0; 2470 i != RVLocs.size(); 2471 ++i, ++realRVLocIdx) { 2472 CCValAssign &VA = RVLocs[i]; 2473 assert(VA.isRegLoc() && "Can only return in registers!"); 2474 2475 SDValue Arg = OutVals[realRVLocIdx]; 2476 2477 switch (VA.getLocInfo()) { 2478 default: llvm_unreachable("Unknown loc info!"); 2479 case CCValAssign::Full: break; 2480 case CCValAssign::BCvt: 2481 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2482 break; 2483 } 2484 2485 if (VA.needsCustom()) { 2486 if (VA.getLocVT() == MVT::v2f64) { 2487 // Extract the first half and return it in two registers. 2488 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2489 DAG.getConstant(0, dl, MVT::i32)); 2490 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2491 DAG.getVTList(MVT::i32, MVT::i32), Half); 2492 2493 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2494 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2495 Flag); 2496 Flag = Chain.getValue(1); 2497 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2498 VA = RVLocs[++i]; // skip ahead to next loc 2499 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2500 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2501 Flag); 2502 Flag = Chain.getValue(1); 2503 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2504 VA = RVLocs[++i]; // skip ahead to next loc 2505 2506 // Extract the 2nd half and fall through to handle it as an f64 value. 2507 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2508 DAG.getConstant(1, dl, MVT::i32)); 2509 } 2510 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2511 // available. 2512 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2513 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2514 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2515 fmrrd.getValue(isLittleEndian ? 0 : 1), 2516 Flag); 2517 Flag = Chain.getValue(1); 2518 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2519 VA = RVLocs[++i]; // skip ahead to next loc 2520 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2521 fmrrd.getValue(isLittleEndian ? 1 : 0), 2522 Flag); 2523 } else 2524 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2525 2526 // Guarantee that all emitted copies are 2527 // stuck together, avoiding something bad. 2528 Flag = Chain.getValue(1); 2529 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2530 } 2531 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2532 const MCPhysReg *I = 2533 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2534 if (I) { 2535 for (; *I; ++I) { 2536 if (ARM::GPRRegClass.contains(*I)) 2537 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2538 else if (ARM::DPRRegClass.contains(*I)) 2539 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2540 else 2541 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2542 } 2543 } 2544 2545 // Update chain and glue. 2546 RetOps[0] = Chain; 2547 if (Flag.getNode()) 2548 RetOps.push_back(Flag); 2549 2550 // CPUs which aren't M-class use a special sequence to return from 2551 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2552 // though we use "subs pc, lr, #N"). 2553 // 2554 // M-class CPUs actually use a normal return sequence with a special 2555 // (hardware-provided) value in LR, so the normal code path works. 2556 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2557 !Subtarget->isMClass()) { 2558 if (Subtarget->isThumb1Only()) 2559 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2560 return LowerInterruptReturn(RetOps, dl, DAG); 2561 } 2562 2563 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2564 } 2565 2566 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2567 if (N->getNumValues() != 1) 2568 return false; 2569 if (!N->hasNUsesOfValue(1, 0)) 2570 return false; 2571 2572 SDValue TCChain = Chain; 2573 SDNode *Copy = *N->use_begin(); 2574 if (Copy->getOpcode() == ISD::CopyToReg) { 2575 // If the copy has a glue operand, we conservatively assume it isn't safe to 2576 // perform a tail call. 2577 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2578 return false; 2579 TCChain = Copy->getOperand(0); 2580 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2581 SDNode *VMov = Copy; 2582 // f64 returned in a pair of GPRs. 2583 SmallPtrSet<SDNode*, 2> Copies; 2584 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2585 UI != UE; ++UI) { 2586 if (UI->getOpcode() != ISD::CopyToReg) 2587 return false; 2588 Copies.insert(*UI); 2589 } 2590 if (Copies.size() > 2) 2591 return false; 2592 2593 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2594 UI != UE; ++UI) { 2595 SDValue UseChain = UI->getOperand(0); 2596 if (Copies.count(UseChain.getNode())) 2597 // Second CopyToReg 2598 Copy = *UI; 2599 else { 2600 // We are at the top of this chain. 2601 // If the copy has a glue operand, we conservatively assume it 2602 // isn't safe to perform a tail call. 2603 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2604 return false; 2605 // First CopyToReg 2606 TCChain = UseChain; 2607 } 2608 } 2609 } else if (Copy->getOpcode() == ISD::BITCAST) { 2610 // f32 returned in a single GPR. 2611 if (!Copy->hasOneUse()) 2612 return false; 2613 Copy = *Copy->use_begin(); 2614 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2615 return false; 2616 // If the copy has a glue operand, we conservatively assume it isn't safe to 2617 // perform a tail call. 2618 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2619 return false; 2620 TCChain = Copy->getOperand(0); 2621 } else { 2622 return false; 2623 } 2624 2625 bool HasRet = false; 2626 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2627 UI != UE; ++UI) { 2628 if (UI->getOpcode() != ARMISD::RET_FLAG && 2629 UI->getOpcode() != ARMISD::INTRET_FLAG) 2630 return false; 2631 HasRet = true; 2632 } 2633 2634 if (!HasRet) 2635 return false; 2636 2637 Chain = TCChain; 2638 return true; 2639 } 2640 2641 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2642 if (!Subtarget->supportsTailCall()) 2643 return false; 2644 2645 auto Attr = 2646 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2647 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2648 return false; 2649 2650 return true; 2651 } 2652 2653 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2654 // and pass the lower and high parts through. 2655 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2656 SDLoc DL(Op); 2657 SDValue WriteValue = Op->getOperand(2); 2658 2659 // This function is only supposed to be called for i64 type argument. 2660 assert(WriteValue.getValueType() == MVT::i64 2661 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2662 2663 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2664 DAG.getConstant(0, DL, MVT::i32)); 2665 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2666 DAG.getConstant(1, DL, MVT::i32)); 2667 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2668 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2669 } 2670 2671 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2672 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2673 // one of the above mentioned nodes. It has to be wrapped because otherwise 2674 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2675 // be used to form addressing mode. These wrapped nodes will be selected 2676 // into MOVi. 2677 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2678 SelectionDAG &DAG) const { 2679 EVT PtrVT = Op.getValueType(); 2680 // FIXME there is no actual debug info here 2681 SDLoc dl(Op); 2682 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2683 SDValue Res; 2684 2685 // When generating execute-only code Constant Pools must be promoted to the 2686 // global data section. It's a bit ugly that we can't share them across basic 2687 // blocks, but this way we guarantee that execute-only behaves correct with 2688 // position-independent addressing modes. 2689 if (Subtarget->genExecuteOnly()) { 2690 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2691 auto T = const_cast<Type*>(CP->getType()); 2692 auto C = const_cast<Constant*>(CP->getConstVal()); 2693 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2694 getFunction().getParent()); 2695 auto GV = new GlobalVariable( 2696 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2697 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2698 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2699 Twine(AFI->createPICLabelUId()) 2700 ); 2701 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2702 dl, PtrVT); 2703 return LowerGlobalAddress(GA, DAG); 2704 } 2705 2706 if (CP->isMachineConstantPoolEntry()) 2707 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2708 CP->getAlignment()); 2709 else 2710 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2711 CP->getAlignment()); 2712 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2713 } 2714 2715 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2716 return MachineJumpTableInfo::EK_Inline; 2717 } 2718 2719 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2720 SelectionDAG &DAG) const { 2721 MachineFunction &MF = DAG.getMachineFunction(); 2722 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2723 unsigned ARMPCLabelIndex = 0; 2724 SDLoc DL(Op); 2725 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2726 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2727 SDValue CPAddr; 2728 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2729 if (!IsPositionIndependent) { 2730 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2731 } else { 2732 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2733 ARMPCLabelIndex = AFI->createPICLabelUId(); 2734 ARMConstantPoolValue *CPV = 2735 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2736 ARMCP::CPBlockAddress, PCAdj); 2737 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2738 } 2739 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2740 SDValue Result = DAG.getLoad( 2741 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2742 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2743 if (!IsPositionIndependent) 2744 return Result; 2745 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2746 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2747 } 2748 2749 /// \brief Convert a TLS address reference into the correct sequence of loads 2750 /// and calls to compute the variable's address for Darwin, and return an 2751 /// SDValue containing the final node. 2752 2753 /// Darwin only has one TLS scheme which must be capable of dealing with the 2754 /// fully general situation, in the worst case. This means: 2755 /// + "extern __thread" declaration. 2756 /// + Defined in a possibly unknown dynamic library. 2757 /// 2758 /// The general system is that each __thread variable has a [3 x i32] descriptor 2759 /// which contains information used by the runtime to calculate the address. The 2760 /// only part of this the compiler needs to know about is the first word, which 2761 /// contains a function pointer that must be called with the address of the 2762 /// entire descriptor in "r0". 2763 /// 2764 /// Since this descriptor may be in a different unit, in general access must 2765 /// proceed along the usual ARM rules. A common sequence to produce is: 2766 /// 2767 /// movw rT1, :lower16:_var$non_lazy_ptr 2768 /// movt rT1, :upper16:_var$non_lazy_ptr 2769 /// ldr r0, [rT1] 2770 /// ldr rT2, [r0] 2771 /// blx rT2 2772 /// [...address now in r0...] 2773 SDValue 2774 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2775 SelectionDAG &DAG) const { 2776 assert(Subtarget->isTargetDarwin() && 2777 "This function expects a Darwin target"); 2778 SDLoc DL(Op); 2779 2780 // First step is to get the address of the actua global symbol. This is where 2781 // the TLS descriptor lives. 2782 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2783 2784 // The first entry in the descriptor is a function pointer that we must call 2785 // to obtain the address of the variable. 2786 SDValue Chain = DAG.getEntryNode(); 2787 SDValue FuncTLVGet = DAG.getLoad( 2788 MVT::i32, DL, Chain, DescAddr, 2789 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2790 /* Alignment = */ 4, 2791 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2792 MachineMemOperand::MOInvariant); 2793 Chain = FuncTLVGet.getValue(1); 2794 2795 MachineFunction &F = DAG.getMachineFunction(); 2796 MachineFrameInfo &MFI = F.getFrameInfo(); 2797 MFI.setAdjustsStack(true); 2798 2799 // TLS calls preserve all registers except those that absolutely must be 2800 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2801 // silly). 2802 auto TRI = 2803 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 2804 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2805 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2806 2807 // Finally, we can make the call. This is just a degenerate version of a 2808 // normal AArch64 call node: r0 takes the address of the descriptor, and 2809 // returns the address of the variable in this thread. 2810 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2811 Chain = 2812 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2813 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2814 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2815 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2816 } 2817 2818 SDValue 2819 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2820 SelectionDAG &DAG) const { 2821 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2822 2823 SDValue Chain = DAG.getEntryNode(); 2824 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2825 SDLoc DL(Op); 2826 2827 // Load the current TEB (thread environment block) 2828 SDValue Ops[] = {Chain, 2829 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2830 DAG.getConstant(15, DL, MVT::i32), 2831 DAG.getConstant(0, DL, MVT::i32), 2832 DAG.getConstant(13, DL, MVT::i32), 2833 DAG.getConstant(0, DL, MVT::i32), 2834 DAG.getConstant(2, DL, MVT::i32)}; 2835 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2836 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2837 2838 SDValue TEB = CurrentTEB.getValue(0); 2839 Chain = CurrentTEB.getValue(1); 2840 2841 // Load the ThreadLocalStoragePointer from the TEB 2842 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2843 SDValue TLSArray = 2844 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2845 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2846 2847 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2848 // offset into the TLSArray. 2849 2850 // Load the TLS index from the C runtime 2851 SDValue TLSIndex = 2852 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2853 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2854 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2855 2856 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2857 DAG.getConstant(2, DL, MVT::i32)); 2858 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2859 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2860 MachinePointerInfo()); 2861 2862 // Get the offset of the start of the .tls section (section base) 2863 const auto *GA = cast<GlobalAddressSDNode>(Op); 2864 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2865 SDValue Offset = DAG.getLoad( 2866 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2867 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2868 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2869 2870 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2871 } 2872 2873 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2874 SDValue 2875 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2876 SelectionDAG &DAG) const { 2877 SDLoc dl(GA); 2878 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2879 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2880 MachineFunction &MF = DAG.getMachineFunction(); 2881 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2882 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2883 ARMConstantPoolValue *CPV = 2884 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2885 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2886 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2887 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2888 Argument = DAG.getLoad( 2889 PtrVT, dl, DAG.getEntryNode(), Argument, 2890 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2891 SDValue Chain = Argument.getValue(1); 2892 2893 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2894 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2895 2896 // call __tls_get_addr. 2897 ArgListTy Args; 2898 ArgListEntry Entry; 2899 Entry.Node = Argument; 2900 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2901 Args.push_back(Entry); 2902 2903 // FIXME: is there useful debug info available here? 2904 TargetLowering::CallLoweringInfo CLI(DAG); 2905 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2906 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2907 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2908 2909 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2910 return CallResult.first; 2911 } 2912 2913 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2914 // "local exec" model. 2915 SDValue 2916 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2917 SelectionDAG &DAG, 2918 TLSModel::Model model) const { 2919 const GlobalValue *GV = GA->getGlobal(); 2920 SDLoc dl(GA); 2921 SDValue Offset; 2922 SDValue Chain = DAG.getEntryNode(); 2923 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2924 // Get the Thread Pointer 2925 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2926 2927 if (model == TLSModel::InitialExec) { 2928 MachineFunction &MF = DAG.getMachineFunction(); 2929 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2930 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2931 // Initial exec model. 2932 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2933 ARMConstantPoolValue *CPV = 2934 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2935 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2936 true); 2937 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2938 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2939 Offset = DAG.getLoad( 2940 PtrVT, dl, Chain, Offset, 2941 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2942 Chain = Offset.getValue(1); 2943 2944 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2945 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2946 2947 Offset = DAG.getLoad( 2948 PtrVT, dl, Chain, Offset, 2949 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2950 } else { 2951 // local exec model 2952 assert(model == TLSModel::LocalExec); 2953 ARMConstantPoolValue *CPV = 2954 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2955 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2956 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2957 Offset = DAG.getLoad( 2958 PtrVT, dl, Chain, Offset, 2959 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2960 } 2961 2962 // The address of the thread local variable is the add of the thread 2963 // pointer with the offset of the variable. 2964 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2965 } 2966 2967 SDValue 2968 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2969 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2970 if (DAG.getTarget().Options.EmulatedTLS) 2971 return LowerToTLSEmulatedModel(GA, DAG); 2972 2973 if (Subtarget->isTargetDarwin()) 2974 return LowerGlobalTLSAddressDarwin(Op, DAG); 2975 2976 if (Subtarget->isTargetWindows()) 2977 return LowerGlobalTLSAddressWindows(Op, DAG); 2978 2979 // TODO: implement the "local dynamic" model 2980 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 2981 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2982 2983 switch (model) { 2984 case TLSModel::GeneralDynamic: 2985 case TLSModel::LocalDynamic: 2986 return LowerToTLSGeneralDynamicModel(GA, DAG); 2987 case TLSModel::InitialExec: 2988 case TLSModel::LocalExec: 2989 return LowerToTLSExecModels(GA, DAG, model); 2990 } 2991 llvm_unreachable("bogus TLS model"); 2992 } 2993 2994 /// Return true if all users of V are within function F, looking through 2995 /// ConstantExprs. 2996 static bool allUsersAreInFunction(const Value *V, const Function *F) { 2997 SmallVector<const User*,4> Worklist; 2998 for (auto *U : V->users()) 2999 Worklist.push_back(U); 3000 while (!Worklist.empty()) { 3001 auto *U = Worklist.pop_back_val(); 3002 if (isa<ConstantExpr>(U)) { 3003 for (auto *UU : U->users()) 3004 Worklist.push_back(UU); 3005 continue; 3006 } 3007 3008 auto *I = dyn_cast<Instruction>(U); 3009 if (!I || I->getParent()->getParent() != F) 3010 return false; 3011 } 3012 return true; 3013 } 3014 3015 /// Return true if all users of V are within some (any) function, looking through 3016 /// ConstantExprs. In other words, are there any global constant users? 3017 static bool allUsersAreInFunctions(const Value *V) { 3018 SmallVector<const User*,4> Worklist; 3019 for (auto *U : V->users()) 3020 Worklist.push_back(U); 3021 while (!Worklist.empty()) { 3022 auto *U = Worklist.pop_back_val(); 3023 if (isa<ConstantExpr>(U)) { 3024 for (auto *UU : U->users()) 3025 Worklist.push_back(UU); 3026 continue; 3027 } 3028 3029 if (!isa<Instruction>(U)) 3030 return false; 3031 } 3032 return true; 3033 } 3034 3035 // Return true if T is an integer, float or an array/vector of either. 3036 static bool isSimpleType(Type *T) { 3037 if (T->isIntegerTy() || T->isFloatingPointTy()) 3038 return true; 3039 Type *SubT = nullptr; 3040 if (T->isArrayTy()) 3041 SubT = T->getArrayElementType(); 3042 else if (T->isVectorTy()) 3043 SubT = T->getVectorElementType(); 3044 else 3045 return false; 3046 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 3047 } 3048 3049 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 3050 EVT PtrVT, const SDLoc &dl) { 3051 // If we're creating a pool entry for a constant global with unnamed address, 3052 // and the global is small enough, we can emit it inline into the constant pool 3053 // to save ourselves an indirection. 3054 // 3055 // This is a win if the constant is only used in one function (so it doesn't 3056 // need to be duplicated) or duplicating the constant wouldn't increase code 3057 // size (implying the constant is no larger than 4 bytes). 3058 const Function &F = DAG.getMachineFunction().getFunction(); 3059 3060 // We rely on this decision to inline being idemopotent and unrelated to the 3061 // use-site. We know that if we inline a variable at one use site, we'll 3062 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3063 // doesn't know about this optimization, so bail out if it's enabled else 3064 // we could decide to inline here (and thus never emit the GV) but require 3065 // the GV from fast-isel generated code. 3066 if (!EnableConstpoolPromotion || 3067 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3068 return SDValue(); 3069 3070 auto *GVar = dyn_cast<GlobalVariable>(GV); 3071 if (!GVar || !GVar->hasInitializer() || 3072 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3073 !GVar->hasLocalLinkage()) 3074 return SDValue(); 3075 3076 // Ensure that we don't try and inline any type that contains pointers. If 3077 // we inline a value that contains relocations, we move the relocations from 3078 // .data to .text which is not ideal. 3079 auto *Init = GVar->getInitializer(); 3080 if (!isSimpleType(Init->getType())) 3081 return SDValue(); 3082 3083 // The constant islands pass can only really deal with alignment requests 3084 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3085 // any type wanting greater alignment requirements than 4 bytes. We also 3086 // can only promote constants that are multiples of 4 bytes in size or 3087 // are paddable to a multiple of 4. Currently we only try and pad constants 3088 // that are strings for simplicity. 3089 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3090 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3091 unsigned Align = GVar->getAlignment(); 3092 unsigned RequiredPadding = 4 - (Size % 4); 3093 bool PaddingPossible = 3094 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3095 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3096 Size == 0) 3097 return SDValue(); 3098 3099 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3100 MachineFunction &MF = DAG.getMachineFunction(); 3101 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3102 3103 // We can't bloat the constant pool too much, else the ConstantIslands pass 3104 // may fail to converge. If we haven't promoted this global yet (it may have 3105 // multiple uses), and promoting it would increase the constant pool size (Sz 3106 // > 4), ensure we have space to do so up to MaxTotal. 3107 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3108 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3109 ConstpoolPromotionMaxTotal) 3110 return SDValue(); 3111 3112 // This is only valid if all users are in a single function OR it has users 3113 // in multiple functions but it no larger than a pointer. We also check if 3114 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3115 // address taken. 3116 if (!allUsersAreInFunction(GVar, &F) && 3117 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3118 return SDValue(); 3119 3120 // We're going to inline this global. Pad it out if needed. 3121 if (RequiredPadding != 4) { 3122 StringRef S = CDAInit->getAsString(); 3123 3124 SmallVector<uint8_t,16> V(S.size()); 3125 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3126 while (RequiredPadding--) 3127 V.push_back(0); 3128 Init = ConstantDataArray::get(*DAG.getContext(), V); 3129 } 3130 3131 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3132 SDValue CPAddr = 3133 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3134 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3135 AFI->markGlobalAsPromotedToConstantPool(GVar); 3136 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3137 PaddedSize - 4); 3138 } 3139 ++NumConstpoolPromoted; 3140 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3141 } 3142 3143 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3144 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3145 GV = GA->getBaseObject(); 3146 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3147 isa<Function>(GV); 3148 } 3149 3150 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3151 SelectionDAG &DAG) const { 3152 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3153 default: llvm_unreachable("unknown object format"); 3154 case Triple::COFF: 3155 return LowerGlobalAddressWindows(Op, DAG); 3156 case Triple::ELF: 3157 return LowerGlobalAddressELF(Op, DAG); 3158 case Triple::MachO: 3159 return LowerGlobalAddressDarwin(Op, DAG); 3160 } 3161 } 3162 3163 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3164 SelectionDAG &DAG) const { 3165 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3166 SDLoc dl(Op); 3167 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3168 const TargetMachine &TM = getTargetMachine(); 3169 bool IsRO = isReadOnly(GV); 3170 3171 // promoteToConstantPool only if not generating XO text section 3172 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3173 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3174 return V; 3175 3176 if (isPositionIndependent()) { 3177 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3178 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3179 UseGOT_PREL ? ARMII::MO_GOT : 0); 3180 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3181 if (UseGOT_PREL) 3182 Result = 3183 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3184 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3185 return Result; 3186 } else if (Subtarget->isROPI() && IsRO) { 3187 // PC-relative. 3188 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3189 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3190 return Result; 3191 } else if (Subtarget->isRWPI() && !IsRO) { 3192 // SB-relative. 3193 SDValue RelAddr; 3194 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3195 ++NumMovwMovt; 3196 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3197 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3198 } else { // use literal pool for address constant 3199 ARMConstantPoolValue *CPV = 3200 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3201 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3202 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3203 RelAddr = DAG.getLoad( 3204 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3205 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3206 } 3207 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3208 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3209 return Result; 3210 } 3211 3212 // If we have T2 ops, we can materialize the address directly via movt/movw 3213 // pair. This is always cheaper. 3214 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3215 ++NumMovwMovt; 3216 // FIXME: Once remat is capable of dealing with instructions with register 3217 // operands, expand this into two nodes. 3218 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3219 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3220 } else { 3221 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3222 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3223 return DAG.getLoad( 3224 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3225 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3226 } 3227 } 3228 3229 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3230 SelectionDAG &DAG) const { 3231 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3232 "ROPI/RWPI not currently supported for Darwin"); 3233 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3234 SDLoc dl(Op); 3235 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3236 3237 if (Subtarget->useMovt(DAG.getMachineFunction())) 3238 ++NumMovwMovt; 3239 3240 // FIXME: Once remat is capable of dealing with instructions with register 3241 // operands, expand this into multiple nodes 3242 unsigned Wrapper = 3243 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3244 3245 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3246 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3247 3248 if (Subtarget->isGVIndirectSymbol(GV)) 3249 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3250 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3251 return Result; 3252 } 3253 3254 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3255 SelectionDAG &DAG) const { 3256 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3257 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3258 "Windows on ARM expects to use movw/movt"); 3259 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3260 "ROPI/RWPI not currently supported for Windows"); 3261 3262 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3263 const ARMII::TOF TargetFlags = 3264 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3265 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3266 SDValue Result; 3267 SDLoc DL(Op); 3268 3269 ++NumMovwMovt; 3270 3271 // FIXME: Once remat is capable of dealing with instructions with register 3272 // operands, expand this into two nodes. 3273 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3274 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3275 TargetFlags)); 3276 if (GV->hasDLLImportStorageClass()) 3277 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3278 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3279 return Result; 3280 } 3281 3282 SDValue 3283 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3284 SDLoc dl(Op); 3285 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3286 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3287 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3288 Op.getOperand(1), Val); 3289 } 3290 3291 SDValue 3292 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3293 SDLoc dl(Op); 3294 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3295 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3296 } 3297 3298 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3299 SelectionDAG &DAG) const { 3300 SDLoc dl(Op); 3301 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3302 Op.getOperand(0)); 3303 } 3304 3305 SDValue 3306 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3307 const ARMSubtarget *Subtarget) const { 3308 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3309 SDLoc dl(Op); 3310 switch (IntNo) { 3311 default: return SDValue(); // Don't custom lower most intrinsics. 3312 case Intrinsic::thread_pointer: { 3313 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3314 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3315 } 3316 case Intrinsic::eh_sjlj_lsda: { 3317 MachineFunction &MF = DAG.getMachineFunction(); 3318 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3319 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3320 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3321 SDValue CPAddr; 3322 bool IsPositionIndependent = isPositionIndependent(); 3323 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3324 ARMConstantPoolValue *CPV = 3325 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3326 ARMCP::CPLSDA, PCAdj); 3327 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3328 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3329 SDValue Result = DAG.getLoad( 3330 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3331 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3332 3333 if (IsPositionIndependent) { 3334 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3335 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3336 } 3337 return Result; 3338 } 3339 case Intrinsic::arm_neon_vabs: 3340 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3341 Op.getOperand(1)); 3342 case Intrinsic::arm_neon_vmulls: 3343 case Intrinsic::arm_neon_vmullu: { 3344 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3345 ? ARMISD::VMULLs : ARMISD::VMULLu; 3346 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3347 Op.getOperand(1), Op.getOperand(2)); 3348 } 3349 case Intrinsic::arm_neon_vminnm: 3350 case Intrinsic::arm_neon_vmaxnm: { 3351 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3352 ? ISD::FMINNUM : ISD::FMAXNUM; 3353 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3354 Op.getOperand(1), Op.getOperand(2)); 3355 } 3356 case Intrinsic::arm_neon_vminu: 3357 case Intrinsic::arm_neon_vmaxu: { 3358 if (Op.getValueType().isFloatingPoint()) 3359 return SDValue(); 3360 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3361 ? ISD::UMIN : ISD::UMAX; 3362 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3363 Op.getOperand(1), Op.getOperand(2)); 3364 } 3365 case Intrinsic::arm_neon_vmins: 3366 case Intrinsic::arm_neon_vmaxs: { 3367 // v{min,max}s is overloaded between signed integers and floats. 3368 if (!Op.getValueType().isFloatingPoint()) { 3369 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3370 ? ISD::SMIN : ISD::SMAX; 3371 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3372 Op.getOperand(1), Op.getOperand(2)); 3373 } 3374 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3375 ? ISD::FMINNAN : ISD::FMAXNAN; 3376 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3377 Op.getOperand(1), Op.getOperand(2)); 3378 } 3379 case Intrinsic::arm_neon_vtbl1: 3380 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3381 Op.getOperand(1), Op.getOperand(2)); 3382 case Intrinsic::arm_neon_vtbl2: 3383 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3384 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3385 } 3386 } 3387 3388 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3389 const ARMSubtarget *Subtarget) { 3390 SDLoc dl(Op); 3391 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3392 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3393 if (SSID == SyncScope::SingleThread) 3394 return Op; 3395 3396 if (!Subtarget->hasDataBarrier()) { 3397 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3398 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3399 // here. 3400 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3401 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3402 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3403 DAG.getConstant(0, dl, MVT::i32)); 3404 } 3405 3406 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3407 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3408 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3409 if (Subtarget->isMClass()) { 3410 // Only a full system barrier exists in the M-class architectures. 3411 Domain = ARM_MB::SY; 3412 } else if (Subtarget->preferISHSTBarriers() && 3413 Ord == AtomicOrdering::Release) { 3414 // Swift happens to implement ISHST barriers in a way that's compatible with 3415 // Release semantics but weaker than ISH so we'd be fools not to use 3416 // it. Beware: other processors probably don't! 3417 Domain = ARM_MB::ISHST; 3418 } 3419 3420 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3421 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3422 DAG.getConstant(Domain, dl, MVT::i32)); 3423 } 3424 3425 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3426 const ARMSubtarget *Subtarget) { 3427 // ARM pre v5TE and Thumb1 does not have preload instructions. 3428 if (!(Subtarget->isThumb2() || 3429 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3430 // Just preserve the chain. 3431 return Op.getOperand(0); 3432 3433 SDLoc dl(Op); 3434 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3435 if (!isRead && 3436 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3437 // ARMv7 with MP extension has PLDW. 3438 return Op.getOperand(0); 3439 3440 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3441 if (Subtarget->isThumb()) { 3442 // Invert the bits. 3443 isRead = ~isRead & 1; 3444 isData = ~isData & 1; 3445 } 3446 3447 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3448 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3449 DAG.getConstant(isData, dl, MVT::i32)); 3450 } 3451 3452 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3453 MachineFunction &MF = DAG.getMachineFunction(); 3454 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3455 3456 // vastart just stores the address of the VarArgsFrameIndex slot into the 3457 // memory location argument. 3458 SDLoc dl(Op); 3459 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3460 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3461 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3462 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3463 MachinePointerInfo(SV)); 3464 } 3465 3466 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3467 CCValAssign &NextVA, 3468 SDValue &Root, 3469 SelectionDAG &DAG, 3470 const SDLoc &dl) const { 3471 MachineFunction &MF = DAG.getMachineFunction(); 3472 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3473 3474 const TargetRegisterClass *RC; 3475 if (AFI->isThumb1OnlyFunction()) 3476 RC = &ARM::tGPRRegClass; 3477 else 3478 RC = &ARM::GPRRegClass; 3479 3480 // Transform the arguments stored in physical registers into virtual ones. 3481 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3482 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3483 3484 SDValue ArgValue2; 3485 if (NextVA.isMemLoc()) { 3486 MachineFrameInfo &MFI = MF.getFrameInfo(); 3487 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3488 3489 // Create load node to retrieve arguments from the stack. 3490 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3491 ArgValue2 = DAG.getLoad( 3492 MVT::i32, dl, Root, FIN, 3493 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3494 } else { 3495 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3496 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3497 } 3498 if (!Subtarget->isLittle()) 3499 std::swap (ArgValue, ArgValue2); 3500 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3501 } 3502 3503 // The remaining GPRs hold either the beginning of variable-argument 3504 // data, or the beginning of an aggregate passed by value (usually 3505 // byval). Either way, we allocate stack slots adjacent to the data 3506 // provided by our caller, and store the unallocated registers there. 3507 // If this is a variadic function, the va_list pointer will begin with 3508 // these values; otherwise, this reassembles a (byval) structure that 3509 // was split between registers and memory. 3510 // Return: The frame index registers were stored into. 3511 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3512 const SDLoc &dl, SDValue &Chain, 3513 const Value *OrigArg, 3514 unsigned InRegsParamRecordIdx, 3515 int ArgOffset, unsigned ArgSize) const { 3516 // Currently, two use-cases possible: 3517 // Case #1. Non-var-args function, and we meet first byval parameter. 3518 // Setup first unallocated register as first byval register; 3519 // eat all remained registers 3520 // (these two actions are performed by HandleByVal method). 3521 // Then, here, we initialize stack frame with 3522 // "store-reg" instructions. 3523 // Case #2. Var-args function, that doesn't contain byval parameters. 3524 // The same: eat all remained unallocated registers, 3525 // initialize stack frame. 3526 3527 MachineFunction &MF = DAG.getMachineFunction(); 3528 MachineFrameInfo &MFI = MF.getFrameInfo(); 3529 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3530 unsigned RBegin, REnd; 3531 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3532 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3533 } else { 3534 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3535 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3536 REnd = ARM::R4; 3537 } 3538 3539 if (REnd != RBegin) 3540 ArgOffset = -4 * (ARM::R4 - RBegin); 3541 3542 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3543 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3544 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3545 3546 SmallVector<SDValue, 4> MemOps; 3547 const TargetRegisterClass *RC = 3548 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3549 3550 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3551 unsigned VReg = MF.addLiveIn(Reg, RC); 3552 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3553 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3554 MachinePointerInfo(OrigArg, 4 * i)); 3555 MemOps.push_back(Store); 3556 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3557 } 3558 3559 if (!MemOps.empty()) 3560 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3561 return FrameIndex; 3562 } 3563 3564 // Setup stack frame, the va_list pointer will start from. 3565 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3566 const SDLoc &dl, SDValue &Chain, 3567 unsigned ArgOffset, 3568 unsigned TotalArgRegsSaveSize, 3569 bool ForceMutable) const { 3570 MachineFunction &MF = DAG.getMachineFunction(); 3571 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3572 3573 // Try to store any remaining integer argument regs 3574 // to their spots on the stack so that they may be loaded by dereferencing 3575 // the result of va_next. 3576 // If there is no regs to be stored, just point address after last 3577 // argument passed via stack. 3578 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3579 CCInfo.getInRegsParamsCount(), 3580 CCInfo.getNextStackOffset(), 4); 3581 AFI->setVarArgsFrameIndex(FrameIndex); 3582 } 3583 3584 SDValue ARMTargetLowering::LowerFormalArguments( 3585 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3586 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3587 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3588 MachineFunction &MF = DAG.getMachineFunction(); 3589 MachineFrameInfo &MFI = MF.getFrameInfo(); 3590 3591 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3592 3593 // Assign locations to all of the incoming arguments. 3594 SmallVector<CCValAssign, 16> ArgLocs; 3595 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3596 *DAG.getContext()); 3597 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3598 3599 SmallVector<SDValue, 16> ArgValues; 3600 SDValue ArgValue; 3601 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3602 unsigned CurArgIdx = 0; 3603 3604 // Initially ArgRegsSaveSize is zero. 3605 // Then we increase this value each time we meet byval parameter. 3606 // We also increase this value in case of varargs function. 3607 AFI->setArgRegsSaveSize(0); 3608 3609 // Calculate the amount of stack space that we need to allocate to store 3610 // byval and variadic arguments that are passed in registers. 3611 // We need to know this before we allocate the first byval or variadic 3612 // argument, as they will be allocated a stack slot below the CFA (Canonical 3613 // Frame Address, the stack pointer at entry to the function). 3614 unsigned ArgRegBegin = ARM::R4; 3615 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3616 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3617 break; 3618 3619 CCValAssign &VA = ArgLocs[i]; 3620 unsigned Index = VA.getValNo(); 3621 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3622 if (!Flags.isByVal()) 3623 continue; 3624 3625 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3626 unsigned RBegin, REnd; 3627 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3628 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3629 3630 CCInfo.nextInRegsParam(); 3631 } 3632 CCInfo.rewindByValRegsInfo(); 3633 3634 int lastInsIndex = -1; 3635 if (isVarArg && MFI.hasVAStart()) { 3636 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3637 if (RegIdx != array_lengthof(GPRArgRegs)) 3638 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3639 } 3640 3641 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3642 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3643 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3644 3645 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3646 CCValAssign &VA = ArgLocs[i]; 3647 if (Ins[VA.getValNo()].isOrigArg()) { 3648 std::advance(CurOrigArg, 3649 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3650 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3651 } 3652 // Arguments stored in registers. 3653 if (VA.isRegLoc()) { 3654 EVT RegVT = VA.getLocVT(); 3655 3656 if (VA.needsCustom()) { 3657 // f64 and vector types are split up into multiple registers or 3658 // combinations of registers and stack slots. 3659 if (VA.getLocVT() == MVT::v2f64) { 3660 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3661 Chain, DAG, dl); 3662 VA = ArgLocs[++i]; // skip ahead to next loc 3663 SDValue ArgValue2; 3664 if (VA.isMemLoc()) { 3665 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3666 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3667 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3668 MachinePointerInfo::getFixedStack( 3669 DAG.getMachineFunction(), FI)); 3670 } else { 3671 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3672 Chain, DAG, dl); 3673 } 3674 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3675 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3676 ArgValue, ArgValue1, 3677 DAG.getIntPtrConstant(0, dl)); 3678 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3679 ArgValue, ArgValue2, 3680 DAG.getIntPtrConstant(1, dl)); 3681 } else 3682 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3683 } else { 3684 const TargetRegisterClass *RC; 3685 3686 if (RegVT == MVT::f32) 3687 RC = &ARM::SPRRegClass; 3688 else if (RegVT == MVT::f64) 3689 RC = &ARM::DPRRegClass; 3690 else if (RegVT == MVT::v2f64) 3691 RC = &ARM::QPRRegClass; 3692 else if (RegVT == MVT::i32) 3693 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3694 : &ARM::GPRRegClass; 3695 else 3696 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3697 3698 // Transform the arguments in physical registers into virtual ones. 3699 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3700 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3701 } 3702 3703 // If this is an 8 or 16-bit value, it is really passed promoted 3704 // to 32 bits. Insert an assert[sz]ext to capture this, then 3705 // truncate to the right size. 3706 switch (VA.getLocInfo()) { 3707 default: llvm_unreachable("Unknown loc info!"); 3708 case CCValAssign::Full: break; 3709 case CCValAssign::BCvt: 3710 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3711 break; 3712 case CCValAssign::SExt: 3713 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3714 DAG.getValueType(VA.getValVT())); 3715 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3716 break; 3717 case CCValAssign::ZExt: 3718 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3719 DAG.getValueType(VA.getValVT())); 3720 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3721 break; 3722 } 3723 3724 InVals.push_back(ArgValue); 3725 } else { // VA.isRegLoc() 3726 // sanity check 3727 assert(VA.isMemLoc()); 3728 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3729 3730 int index = VA.getValNo(); 3731 3732 // Some Ins[] entries become multiple ArgLoc[] entries. 3733 // Process them only once. 3734 if (index != lastInsIndex) 3735 { 3736 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3737 // FIXME: For now, all byval parameter objects are marked mutable. 3738 // This can be changed with more analysis. 3739 // In case of tail call optimization mark all arguments mutable. 3740 // Since they could be overwritten by lowering of arguments in case of 3741 // a tail call. 3742 if (Flags.isByVal()) { 3743 assert(Ins[index].isOrigArg() && 3744 "Byval arguments cannot be implicit"); 3745 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3746 3747 int FrameIndex = StoreByValRegs( 3748 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3749 VA.getLocMemOffset(), Flags.getByValSize()); 3750 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3751 CCInfo.nextInRegsParam(); 3752 } else { 3753 unsigned FIOffset = VA.getLocMemOffset(); 3754 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3755 FIOffset, true); 3756 3757 // Create load nodes to retrieve arguments from the stack. 3758 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3759 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3760 MachinePointerInfo::getFixedStack( 3761 DAG.getMachineFunction(), FI))); 3762 } 3763 lastInsIndex = index; 3764 } 3765 } 3766 } 3767 3768 // varargs 3769 if (isVarArg && MFI.hasVAStart()) 3770 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3771 CCInfo.getNextStackOffset(), 3772 TotalArgRegsSaveSize); 3773 3774 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3775 3776 return Chain; 3777 } 3778 3779 /// isFloatingPointZero - Return true if this is +0.0. 3780 static bool isFloatingPointZero(SDValue Op) { 3781 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3782 return CFP->getValueAPF().isPosZero(); 3783 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3784 // Maybe this has already been legalized into the constant pool? 3785 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3786 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3787 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3788 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3789 return CFP->getValueAPF().isPosZero(); 3790 } 3791 } else if (Op->getOpcode() == ISD::BITCAST && 3792 Op->getValueType(0) == MVT::f64) { 3793 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3794 // created by LowerConstantFP(). 3795 SDValue BitcastOp = Op->getOperand(0); 3796 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3797 isNullConstant(BitcastOp->getOperand(0))) 3798 return true; 3799 } 3800 return false; 3801 } 3802 3803 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3804 /// the given operands. 3805 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3806 SDValue &ARMcc, SelectionDAG &DAG, 3807 const SDLoc &dl) const { 3808 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3809 unsigned C = RHSC->getZExtValue(); 3810 if (!isLegalICmpImmediate(C)) { 3811 // Constant does not fit, try adjusting it by one? 3812 switch (CC) { 3813 default: break; 3814 case ISD::SETLT: 3815 case ISD::SETGE: 3816 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3817 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3818 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3819 } 3820 break; 3821 case ISD::SETULT: 3822 case ISD::SETUGE: 3823 if (C != 0 && isLegalICmpImmediate(C-1)) { 3824 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3825 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3826 } 3827 break; 3828 case ISD::SETLE: 3829 case ISD::SETGT: 3830 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3831 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3832 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3833 } 3834 break; 3835 case ISD::SETULE: 3836 case ISD::SETUGT: 3837 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3838 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3839 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3840 } 3841 break; 3842 } 3843 } 3844 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 3845 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 3846 // In ARM and Thumb-2, the compare instructions can shift their second 3847 // operand. 3848 CC = ISD::getSetCCSwappedOperands(CC); 3849 std::swap(LHS, RHS); 3850 } 3851 3852 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3853 ARMISD::NodeType CompareType; 3854 switch (CondCode) { 3855 default: 3856 CompareType = ARMISD::CMP; 3857 break; 3858 case ARMCC::EQ: 3859 case ARMCC::NE: 3860 // Uses only Z Flag 3861 CompareType = ARMISD::CMPZ; 3862 break; 3863 } 3864 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3865 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3866 } 3867 3868 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3869 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3870 SelectionDAG &DAG, const SDLoc &dl, 3871 bool InvalidOnQNaN) const { 3872 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3873 SDValue Cmp; 3874 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3875 if (!isFloatingPointZero(RHS)) 3876 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3877 else 3878 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3879 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3880 } 3881 3882 /// duplicateCmp - Glue values can have only one use, so this function 3883 /// duplicates a comparison node. 3884 SDValue 3885 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3886 unsigned Opc = Cmp.getOpcode(); 3887 SDLoc DL(Cmp); 3888 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3889 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3890 3891 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3892 Cmp = Cmp.getOperand(0); 3893 Opc = Cmp.getOpcode(); 3894 if (Opc == ARMISD::CMPFP) 3895 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3896 Cmp.getOperand(1), Cmp.getOperand(2)); 3897 else { 3898 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3899 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3900 Cmp.getOperand(1)); 3901 } 3902 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3903 } 3904 3905 std::pair<SDValue, SDValue> 3906 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3907 SDValue &ARMcc) const { 3908 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3909 3910 SDValue Value, OverflowCmp; 3911 SDValue LHS = Op.getOperand(0); 3912 SDValue RHS = Op.getOperand(1); 3913 SDLoc dl(Op); 3914 3915 // FIXME: We are currently always generating CMPs because we don't support 3916 // generating CMN through the backend. This is not as good as the natural 3917 // CMP case because it causes a register dependency and cannot be folded 3918 // later. 3919 3920 switch (Op.getOpcode()) { 3921 default: 3922 llvm_unreachable("Unknown overflow instruction!"); 3923 case ISD::SADDO: 3924 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3925 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3926 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3927 break; 3928 case ISD::UADDO: 3929 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3930 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3931 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3932 break; 3933 case ISD::SSUBO: 3934 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3935 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3936 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3937 break; 3938 case ISD::USUBO: 3939 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3940 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3941 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3942 break; 3943 } // switch (...) 3944 3945 return std::make_pair(Value, OverflowCmp); 3946 } 3947 3948 SDValue 3949 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 3950 // Let legalize expand this if it isn't a legal type yet. 3951 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3952 return SDValue(); 3953 3954 SDValue Value, OverflowCmp; 3955 SDValue ARMcc; 3956 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 3957 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3958 SDLoc dl(Op); 3959 // We use 0 and 1 as false and true values. 3960 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 3961 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 3962 EVT VT = Op.getValueType(); 3963 3964 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 3965 ARMcc, CCR, OverflowCmp); 3966 3967 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 3968 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 3969 } 3970 3971 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 3972 SelectionDAG &DAG) { 3973 SDLoc DL(BoolCarry); 3974 EVT CarryVT = BoolCarry.getValueType(); 3975 3976 APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits()); 3977 // This converts the boolean value carry into the carry flag by doing 3978 // ARMISD::ADDC Carry, ~0 3979 return DAG.getNode(ARMISD::ADDC, DL, DAG.getVTList(CarryVT, MVT::i32), 3980 BoolCarry, DAG.getConstant(NegOne, DL, CarryVT)); 3981 } 3982 3983 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 3984 SelectionDAG &DAG) { 3985 SDLoc DL(Flags); 3986 3987 // Now convert the carry flag into a boolean carry. We do this 3988 // using ARMISD:ADDE 0, 0, Carry 3989 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 3990 DAG.getConstant(0, DL, MVT::i32), 3991 DAG.getConstant(0, DL, MVT::i32), Flags); 3992 } 3993 3994 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 3995 SelectionDAG &DAG) const { 3996 // Let legalize expand this if it isn't a legal type yet. 3997 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 3998 return SDValue(); 3999 4000 SDValue LHS = Op.getOperand(0); 4001 SDValue RHS = Op.getOperand(1); 4002 SDLoc dl(Op); 4003 4004 EVT VT = Op.getValueType(); 4005 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4006 SDValue Value; 4007 SDValue Overflow; 4008 switch (Op.getOpcode()) { 4009 default: 4010 llvm_unreachable("Unknown overflow instruction!"); 4011 case ISD::UADDO: 4012 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4013 // Convert the carry flag into a boolean value. 4014 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4015 break; 4016 case ISD::USUBO: { 4017 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4018 // Convert the carry flag into a boolean value. 4019 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4020 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4021 // value. So compute 1 - C. 4022 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4023 DAG.getConstant(1, dl, MVT::i32), Overflow); 4024 break; 4025 } 4026 } 4027 4028 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4029 } 4030 4031 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4032 SDValue Cond = Op.getOperand(0); 4033 SDValue SelectTrue = Op.getOperand(1); 4034 SDValue SelectFalse = Op.getOperand(2); 4035 SDLoc dl(Op); 4036 unsigned Opc = Cond.getOpcode(); 4037 4038 if (Cond.getResNo() == 1 && 4039 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4040 Opc == ISD::USUBO)) { 4041 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4042 return SDValue(); 4043 4044 SDValue Value, OverflowCmp; 4045 SDValue ARMcc; 4046 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4047 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4048 EVT VT = Op.getValueType(); 4049 4050 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4051 OverflowCmp, DAG); 4052 } 4053 4054 // Convert: 4055 // 4056 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4057 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4058 // 4059 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4060 const ConstantSDNode *CMOVTrue = 4061 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4062 const ConstantSDNode *CMOVFalse = 4063 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4064 4065 if (CMOVTrue && CMOVFalse) { 4066 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4067 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4068 4069 SDValue True; 4070 SDValue False; 4071 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4072 True = SelectTrue; 4073 False = SelectFalse; 4074 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4075 True = SelectFalse; 4076 False = SelectTrue; 4077 } 4078 4079 if (True.getNode() && False.getNode()) { 4080 EVT VT = Op.getValueType(); 4081 SDValue ARMcc = Cond.getOperand(2); 4082 SDValue CCR = Cond.getOperand(3); 4083 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4084 assert(True.getValueType() == VT); 4085 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4086 } 4087 } 4088 } 4089 4090 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4091 // undefined bits before doing a full-word comparison with zero. 4092 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4093 DAG.getConstant(1, dl, Cond.getValueType())); 4094 4095 return DAG.getSelectCC(dl, Cond, 4096 DAG.getConstant(0, dl, Cond.getValueType()), 4097 SelectTrue, SelectFalse, ISD::SETNE); 4098 } 4099 4100 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4101 bool &swpCmpOps, bool &swpVselOps) { 4102 // Start by selecting the GE condition code for opcodes that return true for 4103 // 'equality' 4104 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4105 CC == ISD::SETULE) 4106 CondCode = ARMCC::GE; 4107 4108 // and GT for opcodes that return false for 'equality'. 4109 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4110 CC == ISD::SETULT) 4111 CondCode = ARMCC::GT; 4112 4113 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4114 // to swap the compare operands. 4115 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4116 CC == ISD::SETULT) 4117 swpCmpOps = true; 4118 4119 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4120 // If we have an unordered opcode, we need to swap the operands to the VSEL 4121 // instruction (effectively negating the condition). 4122 // 4123 // This also has the effect of swapping which one of 'less' or 'greater' 4124 // returns true, so we also swap the compare operands. It also switches 4125 // whether we return true for 'equality', so we compensate by picking the 4126 // opposite condition code to our original choice. 4127 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4128 CC == ISD::SETUGT) { 4129 swpCmpOps = !swpCmpOps; 4130 swpVselOps = !swpVselOps; 4131 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4132 } 4133 4134 // 'ordered' is 'anything but unordered', so use the VS condition code and 4135 // swap the VSEL operands. 4136 if (CC == ISD::SETO) { 4137 CondCode = ARMCC::VS; 4138 swpVselOps = true; 4139 } 4140 4141 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4142 // code and swap the VSEL operands. 4143 if (CC == ISD::SETUNE) { 4144 CondCode = ARMCC::EQ; 4145 swpVselOps = true; 4146 } 4147 } 4148 4149 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4150 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4151 SDValue Cmp, SelectionDAG &DAG) const { 4152 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4153 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4154 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4155 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4156 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4157 4158 SDValue TrueLow = TrueVal.getValue(0); 4159 SDValue TrueHigh = TrueVal.getValue(1); 4160 SDValue FalseLow = FalseVal.getValue(0); 4161 SDValue FalseHigh = FalseVal.getValue(1); 4162 4163 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4164 ARMcc, CCR, Cmp); 4165 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4166 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4167 4168 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4169 } else { 4170 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4171 Cmp); 4172 } 4173 } 4174 4175 static bool isGTorGE(ISD::CondCode CC) { 4176 return CC == ISD::SETGT || CC == ISD::SETGE; 4177 } 4178 4179 static bool isLTorLE(ISD::CondCode CC) { 4180 return CC == ISD::SETLT || CC == ISD::SETLE; 4181 } 4182 4183 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4184 // All of these conditions (and their <= and >= counterparts) will do: 4185 // x < k ? k : x 4186 // x > k ? x : k 4187 // k < x ? x : k 4188 // k > x ? k : x 4189 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4190 const SDValue TrueVal, const SDValue FalseVal, 4191 const ISD::CondCode CC, const SDValue K) { 4192 return (isGTorGE(CC) && 4193 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4194 (isLTorLE(CC) && 4195 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4196 } 4197 4198 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4199 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4200 const SDValue TrueVal, const SDValue FalseVal, 4201 const ISD::CondCode CC, const SDValue K) { 4202 return (isGTorGE(CC) && 4203 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4204 (isLTorLE(CC) && 4205 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4206 } 4207 4208 // Check if two chained conditionals could be converted into SSAT. 4209 // 4210 // SSAT can replace a set of two conditional selectors that bound a number to an 4211 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4212 // 4213 // x < -k ? -k : (x > k ? k : x) 4214 // x < -k ? -k : (x < k ? x : k) 4215 // x > -k ? (x > k ? k : x) : -k 4216 // x < k ? (x < -k ? -k : x) : k 4217 // etc. 4218 // 4219 // It returns true if the conversion can be done, false otherwise. 4220 // Additionally, the variable is returned in parameter V and the constant in K. 4221 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4222 uint64_t &K) { 4223 SDValue LHS1 = Op.getOperand(0); 4224 SDValue RHS1 = Op.getOperand(1); 4225 SDValue TrueVal1 = Op.getOperand(2); 4226 SDValue FalseVal1 = Op.getOperand(3); 4227 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4228 4229 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4230 if (Op2.getOpcode() != ISD::SELECT_CC) 4231 return false; 4232 4233 SDValue LHS2 = Op2.getOperand(0); 4234 SDValue RHS2 = Op2.getOperand(1); 4235 SDValue TrueVal2 = Op2.getOperand(2); 4236 SDValue FalseVal2 = Op2.getOperand(3); 4237 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4238 4239 // Find out which are the constants and which are the variables 4240 // in each conditional 4241 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4242 ? &RHS1 4243 : nullptr; 4244 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4245 ? &RHS2 4246 : nullptr; 4247 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4248 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4249 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4250 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4251 4252 // We must detect cases where the original operations worked with 16- or 4253 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4254 // must work with sign-extended values but the select operations return 4255 // the original non-extended value. 4256 SDValue V2TmpReg = V2Tmp; 4257 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4258 V2TmpReg = V2Tmp->getOperand(0); 4259 4260 // Check that the registers and the constants have the correct values 4261 // in both conditionals 4262 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4263 V2TmpReg != V2) 4264 return false; 4265 4266 // Figure out which conditional is saturating the lower/upper bound. 4267 const SDValue *LowerCheckOp = 4268 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4269 ? &Op 4270 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4271 ? &Op2 4272 : nullptr; 4273 const SDValue *UpperCheckOp = 4274 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4275 ? &Op 4276 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4277 ? &Op2 4278 : nullptr; 4279 4280 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4281 return false; 4282 4283 // Check that the constant in the lower-bound check is 4284 // the opposite of the constant in the upper-bound check 4285 // in 1's complement. 4286 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4287 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4288 int64_t PosVal = std::max(Val1, Val2); 4289 4290 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4291 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4292 Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) { 4293 4294 V = V2; 4295 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4296 return true; 4297 } 4298 4299 return false; 4300 } 4301 4302 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4303 EVT VT = Op.getValueType(); 4304 SDLoc dl(Op); 4305 4306 // Try to convert two saturating conditional selects into a single SSAT 4307 SDValue SatValue; 4308 uint64_t SatConstant; 4309 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4310 isSaturatingConditional(Op, SatValue, SatConstant)) 4311 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4312 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4313 4314 SDValue LHS = Op.getOperand(0); 4315 SDValue RHS = Op.getOperand(1); 4316 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4317 SDValue TrueVal = Op.getOperand(2); 4318 SDValue FalseVal = Op.getOperand(3); 4319 4320 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4321 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4322 dl); 4323 4324 // If softenSetCCOperands only returned one value, we should compare it to 4325 // zero. 4326 if (!RHS.getNode()) { 4327 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4328 CC = ISD::SETNE; 4329 } 4330 } 4331 4332 if (LHS.getValueType() == MVT::i32) { 4333 // Try to generate VSEL on ARMv8. 4334 // The VSEL instruction can't use all the usual ARM condition 4335 // codes: it only has two bits to select the condition code, so it's 4336 // constrained to use only GE, GT, VS and EQ. 4337 // 4338 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4339 // swap the operands of the previous compare instruction (effectively 4340 // inverting the compare condition, swapping 'less' and 'greater') and 4341 // sometimes need to swap the operands to the VSEL (which inverts the 4342 // condition in the sense of firing whenever the previous condition didn't) 4343 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4344 TrueVal.getValueType() == MVT::f64)) { 4345 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4346 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4347 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4348 CC = ISD::getSetCCInverse(CC, true); 4349 std::swap(TrueVal, FalseVal); 4350 } 4351 } 4352 4353 SDValue ARMcc; 4354 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4355 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4356 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4357 } 4358 4359 ARMCC::CondCodes CondCode, CondCode2; 4360 bool InvalidOnQNaN; 4361 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4362 4363 // Try to generate VMAXNM/VMINNM on ARMv8. 4364 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4365 TrueVal.getValueType() == MVT::f64)) { 4366 bool swpCmpOps = false; 4367 bool swpVselOps = false; 4368 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4369 4370 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4371 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4372 if (swpCmpOps) 4373 std::swap(LHS, RHS); 4374 if (swpVselOps) 4375 std::swap(TrueVal, FalseVal); 4376 } 4377 } 4378 4379 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4380 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4381 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4382 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4383 if (CondCode2 != ARMCC::AL) { 4384 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4385 // FIXME: Needs another CMP because flag can have but one use. 4386 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4387 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4388 } 4389 return Result; 4390 } 4391 4392 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4393 /// to morph to an integer compare sequence. 4394 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4395 const ARMSubtarget *Subtarget) { 4396 SDNode *N = Op.getNode(); 4397 if (!N->hasOneUse()) 4398 // Otherwise it requires moving the value from fp to integer registers. 4399 return false; 4400 if (!N->getNumValues()) 4401 return false; 4402 EVT VT = Op.getValueType(); 4403 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4404 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4405 // vmrs are very slow, e.g. cortex-a8. 4406 return false; 4407 4408 if (isFloatingPointZero(Op)) { 4409 SeenZero = true; 4410 return true; 4411 } 4412 return ISD::isNormalLoad(N); 4413 } 4414 4415 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4416 if (isFloatingPointZero(Op)) 4417 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4418 4419 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4420 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4421 Ld->getPointerInfo(), Ld->getAlignment(), 4422 Ld->getMemOperand()->getFlags()); 4423 4424 llvm_unreachable("Unknown VFP cmp argument!"); 4425 } 4426 4427 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4428 SDValue &RetVal1, SDValue &RetVal2) { 4429 SDLoc dl(Op); 4430 4431 if (isFloatingPointZero(Op)) { 4432 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4433 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4434 return; 4435 } 4436 4437 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4438 SDValue Ptr = Ld->getBasePtr(); 4439 RetVal1 = 4440 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4441 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4442 4443 EVT PtrType = Ptr.getValueType(); 4444 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4445 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4446 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4447 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4448 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4449 Ld->getMemOperand()->getFlags()); 4450 return; 4451 } 4452 4453 llvm_unreachable("Unknown VFP cmp argument!"); 4454 } 4455 4456 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4457 /// f32 and even f64 comparisons to integer ones. 4458 SDValue 4459 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4460 SDValue Chain = Op.getOperand(0); 4461 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4462 SDValue LHS = Op.getOperand(2); 4463 SDValue RHS = Op.getOperand(3); 4464 SDValue Dest = Op.getOperand(4); 4465 SDLoc dl(Op); 4466 4467 bool LHSSeenZero = false; 4468 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4469 bool RHSSeenZero = false; 4470 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4471 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4472 // If unsafe fp math optimization is enabled and there are no other uses of 4473 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4474 // to an integer comparison. 4475 if (CC == ISD::SETOEQ) 4476 CC = ISD::SETEQ; 4477 else if (CC == ISD::SETUNE) 4478 CC = ISD::SETNE; 4479 4480 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4481 SDValue ARMcc; 4482 if (LHS.getValueType() == MVT::f32) { 4483 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4484 bitcastf32Toi32(LHS, DAG), Mask); 4485 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4486 bitcastf32Toi32(RHS, DAG), Mask); 4487 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4488 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4489 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4490 Chain, Dest, ARMcc, CCR, Cmp); 4491 } 4492 4493 SDValue LHS1, LHS2; 4494 SDValue RHS1, RHS2; 4495 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4496 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4497 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4498 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4499 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4500 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4501 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4502 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4503 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4504 } 4505 4506 return SDValue(); 4507 } 4508 4509 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4510 SDValue Chain = Op.getOperand(0); 4511 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4512 SDValue LHS = Op.getOperand(2); 4513 SDValue RHS = Op.getOperand(3); 4514 SDValue Dest = Op.getOperand(4); 4515 SDLoc dl(Op); 4516 4517 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4518 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4519 dl); 4520 4521 // If softenSetCCOperands only returned one value, we should compare it to 4522 // zero. 4523 if (!RHS.getNode()) { 4524 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4525 CC = ISD::SETNE; 4526 } 4527 } 4528 4529 if (LHS.getValueType() == MVT::i32) { 4530 SDValue ARMcc; 4531 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4532 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4533 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4534 Chain, Dest, ARMcc, CCR, Cmp); 4535 } 4536 4537 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4538 4539 if (getTargetMachine().Options.UnsafeFPMath && 4540 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4541 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4542 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4543 return Result; 4544 } 4545 4546 ARMCC::CondCodes CondCode, CondCode2; 4547 bool InvalidOnQNaN; 4548 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4549 4550 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4551 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4552 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4553 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4554 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4555 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4556 if (CondCode2 != ARMCC::AL) { 4557 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4558 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4559 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4560 } 4561 return Res; 4562 } 4563 4564 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4565 SDValue Chain = Op.getOperand(0); 4566 SDValue Table = Op.getOperand(1); 4567 SDValue Index = Op.getOperand(2); 4568 SDLoc dl(Op); 4569 4570 EVT PTy = getPointerTy(DAG.getDataLayout()); 4571 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4572 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4573 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4574 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4575 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 4576 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4577 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4578 // which does another jump to the destination. This also makes it easier 4579 // to translate it to TBB / TBH later (Thumb2 only). 4580 // FIXME: This might not work if the function is extremely large. 4581 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4582 Addr, Op.getOperand(2), JTI); 4583 } 4584 if (isPositionIndependent() || Subtarget->isROPI()) { 4585 Addr = 4586 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4587 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4588 Chain = Addr.getValue(1); 4589 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 4590 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4591 } else { 4592 Addr = 4593 DAG.getLoad(PTy, dl, Chain, Addr, 4594 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4595 Chain = Addr.getValue(1); 4596 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4597 } 4598 } 4599 4600 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4601 EVT VT = Op.getValueType(); 4602 SDLoc dl(Op); 4603 4604 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4605 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4606 return Op; 4607 return DAG.UnrollVectorOp(Op.getNode()); 4608 } 4609 4610 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4611 "Invalid type for custom lowering!"); 4612 if (VT != MVT::v4i16) 4613 return DAG.UnrollVectorOp(Op.getNode()); 4614 4615 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4616 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4617 } 4618 4619 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4620 EVT VT = Op.getValueType(); 4621 if (VT.isVector()) 4622 return LowerVectorFP_TO_INT(Op, DAG); 4623 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4624 RTLIB::Libcall LC; 4625 if (Op.getOpcode() == ISD::FP_TO_SINT) 4626 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4627 Op.getValueType()); 4628 else 4629 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4630 Op.getValueType()); 4631 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4632 /*isSigned*/ false, SDLoc(Op)).first; 4633 } 4634 4635 return Op; 4636 } 4637 4638 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4639 EVT VT = Op.getValueType(); 4640 SDLoc dl(Op); 4641 4642 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4643 if (VT.getVectorElementType() == MVT::f32) 4644 return Op; 4645 return DAG.UnrollVectorOp(Op.getNode()); 4646 } 4647 4648 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4649 "Invalid type for custom lowering!"); 4650 if (VT != MVT::v4f32) 4651 return DAG.UnrollVectorOp(Op.getNode()); 4652 4653 unsigned CastOpc; 4654 unsigned Opc; 4655 switch (Op.getOpcode()) { 4656 default: llvm_unreachable("Invalid opcode!"); 4657 case ISD::SINT_TO_FP: 4658 CastOpc = ISD::SIGN_EXTEND; 4659 Opc = ISD::SINT_TO_FP; 4660 break; 4661 case ISD::UINT_TO_FP: 4662 CastOpc = ISD::ZERO_EXTEND; 4663 Opc = ISD::UINT_TO_FP; 4664 break; 4665 } 4666 4667 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4668 return DAG.getNode(Opc, dl, VT, Op); 4669 } 4670 4671 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4672 EVT VT = Op.getValueType(); 4673 if (VT.isVector()) 4674 return LowerVectorINT_TO_FP(Op, DAG); 4675 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4676 RTLIB::Libcall LC; 4677 if (Op.getOpcode() == ISD::SINT_TO_FP) 4678 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4679 Op.getValueType()); 4680 else 4681 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4682 Op.getValueType()); 4683 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4684 /*isSigned*/ false, SDLoc(Op)).first; 4685 } 4686 4687 return Op; 4688 } 4689 4690 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4691 // Implement fcopysign with a fabs and a conditional fneg. 4692 SDValue Tmp0 = Op.getOperand(0); 4693 SDValue Tmp1 = Op.getOperand(1); 4694 SDLoc dl(Op); 4695 EVT VT = Op.getValueType(); 4696 EVT SrcVT = Tmp1.getValueType(); 4697 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4698 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4699 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4700 4701 if (UseNEON) { 4702 // Use VBSL to copy the sign bit. 4703 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4704 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4705 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4706 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4707 if (VT == MVT::f64) 4708 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4709 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4710 DAG.getConstant(32, dl, MVT::i32)); 4711 else /*if (VT == MVT::f32)*/ 4712 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4713 if (SrcVT == MVT::f32) { 4714 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4715 if (VT == MVT::f64) 4716 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4717 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4718 DAG.getConstant(32, dl, MVT::i32)); 4719 } else if (VT == MVT::f32) 4720 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4721 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4722 DAG.getConstant(32, dl, MVT::i32)); 4723 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4724 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4725 4726 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4727 dl, MVT::i32); 4728 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4729 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4730 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4731 4732 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4733 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4734 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4735 if (VT == MVT::f32) { 4736 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4737 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4738 DAG.getConstant(0, dl, MVT::i32)); 4739 } else { 4740 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4741 } 4742 4743 return Res; 4744 } 4745 4746 // Bitcast operand 1 to i32. 4747 if (SrcVT == MVT::f64) 4748 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4749 Tmp1).getValue(1); 4750 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4751 4752 // Or in the signbit with integer operations. 4753 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4754 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4755 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4756 if (VT == MVT::f32) { 4757 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4758 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4759 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4760 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4761 } 4762 4763 // f64: Or the high part with signbit and then combine two parts. 4764 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4765 Tmp0); 4766 SDValue Lo = Tmp0.getValue(0); 4767 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4768 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4769 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4770 } 4771 4772 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4773 MachineFunction &MF = DAG.getMachineFunction(); 4774 MachineFrameInfo &MFI = MF.getFrameInfo(); 4775 MFI.setReturnAddressIsTaken(true); 4776 4777 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4778 return SDValue(); 4779 4780 EVT VT = Op.getValueType(); 4781 SDLoc dl(Op); 4782 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4783 if (Depth) { 4784 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4785 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4786 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4787 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4788 MachinePointerInfo()); 4789 } 4790 4791 // Return LR, which contains the return address. Mark it an implicit live-in. 4792 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4793 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4794 } 4795 4796 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4797 const ARMBaseRegisterInfo &ARI = 4798 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4799 MachineFunction &MF = DAG.getMachineFunction(); 4800 MachineFrameInfo &MFI = MF.getFrameInfo(); 4801 MFI.setFrameAddressIsTaken(true); 4802 4803 EVT VT = Op.getValueType(); 4804 SDLoc dl(Op); // FIXME probably not meaningful 4805 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4806 unsigned FrameReg = ARI.getFrameRegister(MF); 4807 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4808 while (Depth--) 4809 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4810 MachinePointerInfo()); 4811 return FrameAddr; 4812 } 4813 4814 // FIXME? Maybe this could be a TableGen attribute on some registers and 4815 // this table could be generated automatically from RegInfo. 4816 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4817 SelectionDAG &DAG) const { 4818 unsigned Reg = StringSwitch<unsigned>(RegName) 4819 .Case("sp", ARM::SP) 4820 .Default(0); 4821 if (Reg) 4822 return Reg; 4823 report_fatal_error(Twine("Invalid register name \"" 4824 + StringRef(RegName) + "\".")); 4825 } 4826 4827 // Result is 64 bit value so split into two 32 bit values and return as a 4828 // pair of values. 4829 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 4830 SelectionDAG &DAG) { 4831 SDLoc DL(N); 4832 4833 // This function is only supposed to be called for i64 type destination. 4834 assert(N->getValueType(0) == MVT::i64 4835 && "ExpandREAD_REGISTER called for non-i64 type result."); 4836 4837 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 4838 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 4839 N->getOperand(0), 4840 N->getOperand(1)); 4841 4842 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 4843 Read.getValue(1))); 4844 Results.push_back(Read.getOperand(0)); 4845 } 4846 4847 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 4848 /// When \p DstVT, the destination type of \p BC, is on the vector 4849 /// register bank and the source of bitcast, \p Op, operates on the same bank, 4850 /// it might be possible to combine them, such that everything stays on the 4851 /// vector register bank. 4852 /// \p return The node that would replace \p BT, if the combine 4853 /// is possible. 4854 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 4855 SelectionDAG &DAG) { 4856 SDValue Op = BC->getOperand(0); 4857 EVT DstVT = BC->getValueType(0); 4858 4859 // The only vector instruction that can produce a scalar (remember, 4860 // since the bitcast was about to be turned into VMOVDRR, the source 4861 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 4862 // Moreover, we can do this combine only if there is one use. 4863 // Finally, if the destination type is not a vector, there is not 4864 // much point on forcing everything on the vector bank. 4865 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4866 !Op.hasOneUse()) 4867 return SDValue(); 4868 4869 // If the index is not constant, we will introduce an additional 4870 // multiply that will stick. 4871 // Give up in that case. 4872 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 4873 if (!Index) 4874 return SDValue(); 4875 unsigned DstNumElt = DstVT.getVectorNumElements(); 4876 4877 // Compute the new index. 4878 const APInt &APIntIndex = Index->getAPIntValue(); 4879 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 4880 NewIndex *= APIntIndex; 4881 // Check if the new constant index fits into i32. 4882 if (NewIndex.getBitWidth() > 32) 4883 return SDValue(); 4884 4885 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 4886 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 4887 SDLoc dl(Op); 4888 SDValue ExtractSrc = Op.getOperand(0); 4889 EVT VecVT = EVT::getVectorVT( 4890 *DAG.getContext(), DstVT.getScalarType(), 4891 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 4892 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 4893 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 4894 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 4895 } 4896 4897 /// ExpandBITCAST - If the target supports VFP, this function is called to 4898 /// expand a bit convert where either the source or destination type is i64 to 4899 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 4900 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 4901 /// vectors), since the legalizer won't know what to do with that. 4902 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 4903 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4904 SDLoc dl(N); 4905 SDValue Op = N->getOperand(0); 4906 4907 // This function is only supposed to be called for i64 types, either as the 4908 // source or destination of the bit convert. 4909 EVT SrcVT = Op.getValueType(); 4910 EVT DstVT = N->getValueType(0); 4911 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 4912 "ExpandBITCAST called for non-i64 type"); 4913 4914 // Turn i64->f64 into VMOVDRR. 4915 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 4916 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 4917 // if we can combine the bitcast with its source. 4918 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 4919 return Val; 4920 4921 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4922 DAG.getConstant(0, dl, MVT::i32)); 4923 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 4924 DAG.getConstant(1, dl, MVT::i32)); 4925 return DAG.getNode(ISD::BITCAST, dl, DstVT, 4926 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 4927 } 4928 4929 // Turn f64->i64 into VMOVRRD. 4930 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 4931 SDValue Cvt; 4932 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 4933 SrcVT.getVectorNumElements() > 1) 4934 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4935 DAG.getVTList(MVT::i32, MVT::i32), 4936 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 4937 else 4938 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 4939 DAG.getVTList(MVT::i32, MVT::i32), Op); 4940 // Merge the pieces into a single i64 value. 4941 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 4942 } 4943 4944 return SDValue(); 4945 } 4946 4947 /// getZeroVector - Returns a vector of specified type with all zero elements. 4948 /// Zero vectors are used to represent vector negation and in those cases 4949 /// will be implemented with the NEON VNEG instruction. However, VNEG does 4950 /// not support i64 elements, so sometimes the zero vectors will need to be 4951 /// explicitly constructed. Regardless, use a canonical VMOV to create the 4952 /// zero vector. 4953 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 4954 assert(VT.isVector() && "Expected a vector type"); 4955 // The canonical modified immediate encoding of a zero vector is....0! 4956 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 4957 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 4958 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 4959 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4960 } 4961 4962 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4963 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 4964 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 4965 SelectionDAG &DAG) const { 4966 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4967 EVT VT = Op.getValueType(); 4968 unsigned VTBits = VT.getSizeInBits(); 4969 SDLoc dl(Op); 4970 SDValue ShOpLo = Op.getOperand(0); 4971 SDValue ShOpHi = Op.getOperand(1); 4972 SDValue ShAmt = Op.getOperand(2); 4973 SDValue ARMcc; 4974 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4975 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4976 4977 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4978 4979 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 4980 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 4981 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4982 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 4983 DAG.getConstant(VTBits, dl, MVT::i32)); 4984 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4985 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 4986 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4987 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4988 ISD::SETGE, ARMcc, DAG, dl); 4989 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 4990 ARMcc, CCR, CmpLo); 4991 4992 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4993 SDValue HiBigShift = Opc == ISD::SRA 4994 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4995 DAG.getConstant(VTBits - 1, dl, VT)) 4996 : DAG.getConstant(0, dl, VT); 4997 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 4998 ISD::SETGE, ARMcc, DAG, dl); 4999 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5000 ARMcc, CCR, CmpHi); 5001 5002 SDValue Ops[2] = { Lo, Hi }; 5003 return DAG.getMergeValues(Ops, dl); 5004 } 5005 5006 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5007 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5008 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5009 SelectionDAG &DAG) const { 5010 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5011 EVT VT = Op.getValueType(); 5012 unsigned VTBits = VT.getSizeInBits(); 5013 SDLoc dl(Op); 5014 SDValue ShOpLo = Op.getOperand(0); 5015 SDValue ShOpHi = Op.getOperand(1); 5016 SDValue ShAmt = Op.getOperand(2); 5017 SDValue ARMcc; 5018 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5019 5020 assert(Op.getOpcode() == ISD::SHL_PARTS); 5021 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5022 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5023 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5024 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5025 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5026 5027 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5028 DAG.getConstant(VTBits, dl, MVT::i32)); 5029 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5030 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5031 ISD::SETGE, ARMcc, DAG, dl); 5032 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5033 ARMcc, CCR, CmpHi); 5034 5035 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5036 ISD::SETGE, ARMcc, DAG, dl); 5037 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5038 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5039 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5040 5041 SDValue Ops[2] = { Lo, Hi }; 5042 return DAG.getMergeValues(Ops, dl); 5043 } 5044 5045 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5046 SelectionDAG &DAG) const { 5047 // The rounding mode is in bits 23:22 of the FPSCR. 5048 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5049 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5050 // so that the shift + and get folded into a bitfield extract. 5051 SDLoc dl(Op); 5052 SDValue Ops[] = { DAG.getEntryNode(), 5053 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5054 5055 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5056 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5057 DAG.getConstant(1U << 22, dl, MVT::i32)); 5058 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5059 DAG.getConstant(22, dl, MVT::i32)); 5060 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5061 DAG.getConstant(3, dl, MVT::i32)); 5062 } 5063 5064 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5065 const ARMSubtarget *ST) { 5066 SDLoc dl(N); 5067 EVT VT = N->getValueType(0); 5068 if (VT.isVector()) { 5069 assert(ST->hasNEON()); 5070 5071 // Compute the least significant set bit: LSB = X & -X 5072 SDValue X = N->getOperand(0); 5073 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5074 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5075 5076 EVT ElemTy = VT.getVectorElementType(); 5077 5078 if (ElemTy == MVT::i8) { 5079 // Compute with: cttz(x) = ctpop(lsb - 1) 5080 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5081 DAG.getTargetConstant(1, dl, ElemTy)); 5082 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5083 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5084 } 5085 5086 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5087 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5088 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5089 unsigned NumBits = ElemTy.getSizeInBits(); 5090 SDValue WidthMinus1 = 5091 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5092 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5093 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5094 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5095 } 5096 5097 // Compute with: cttz(x) = ctpop(lsb - 1) 5098 5099 // Since we can only compute the number of bits in a byte with vcnt.8, we 5100 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 5101 // and i64. 5102 5103 // Compute LSB - 1. 5104 SDValue Bits; 5105 if (ElemTy == MVT::i64) { 5106 // Load constant 0xffff'ffff'ffff'ffff to register. 5107 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5108 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5109 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5110 } else { 5111 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5112 DAG.getTargetConstant(1, dl, ElemTy)); 5113 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5114 } 5115 5116 // Count #bits with vcnt.8. 5117 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5118 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 5119 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 5120 5121 // Gather the #bits with vpaddl (pairwise add.) 5122 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5123 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 5124 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5125 Cnt8); 5126 if (ElemTy == MVT::i16) 5127 return Cnt16; 5128 5129 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 5130 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 5131 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5132 Cnt16); 5133 if (ElemTy == MVT::i32) 5134 return Cnt32; 5135 5136 assert(ElemTy == MVT::i64); 5137 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5138 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5139 Cnt32); 5140 return Cnt64; 5141 } 5142 5143 if (!ST->hasV6T2Ops()) 5144 return SDValue(); 5145 5146 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5147 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5148 } 5149 5150 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 5151 /// for each 16-bit element from operand, repeated. The basic idea is to 5152 /// leverage vcnt to get the 8-bit counts, gather and add the results. 5153 /// 5154 /// Trace for v4i16: 5155 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5156 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 5157 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 5158 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 5159 /// [b0 b1 b2 b3 b4 b5 b6 b7] 5160 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 5161 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 5162 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 5163 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 5164 EVT VT = N->getValueType(0); 5165 SDLoc DL(N); 5166 5167 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5168 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5169 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5170 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5171 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5172 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5173 } 5174 5175 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5176 /// bit-count for each 16-bit element from the operand. We need slightly 5177 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5178 /// 64/128-bit registers. 5179 /// 5180 /// Trace for v4i16: 5181 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5182 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5183 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5184 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5185 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5186 EVT VT = N->getValueType(0); 5187 SDLoc DL(N); 5188 5189 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5190 if (VT.is64BitVector()) { 5191 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5192 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5193 DAG.getIntPtrConstant(0, DL)); 5194 } else { 5195 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5196 BitCounts, DAG.getIntPtrConstant(0, DL)); 5197 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5198 } 5199 } 5200 5201 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5202 /// bit-count for each 32-bit element from the operand. The idea here is 5203 /// to split the vector into 16-bit elements, leverage the 16-bit count 5204 /// routine, and then combine the results. 5205 /// 5206 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5207 /// input = [v0 v1 ] (vi: 32-bit elements) 5208 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5209 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5210 /// vrev: N0 = [k1 k0 k3 k2 ] 5211 /// [k0 k1 k2 k3 ] 5212 /// N1 =+[k1 k0 k3 k2 ] 5213 /// [k0 k2 k1 k3 ] 5214 /// N2 =+[k1 k3 k0 k2 ] 5215 /// [k0 k2 k1 k3 ] 5216 /// Extended =+[k1 k3 k0 k2 ] 5217 /// [k0 k2 ] 5218 /// Extracted=+[k1 k3 ] 5219 /// 5220 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5221 EVT VT = N->getValueType(0); 5222 SDLoc DL(N); 5223 5224 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5225 5226 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5227 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5228 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5229 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5230 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5231 5232 if (VT.is64BitVector()) { 5233 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5234 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5235 DAG.getIntPtrConstant(0, DL)); 5236 } else { 5237 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5238 DAG.getIntPtrConstant(0, DL)); 5239 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5240 } 5241 } 5242 5243 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5244 const ARMSubtarget *ST) { 5245 EVT VT = N->getValueType(0); 5246 5247 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5248 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5249 VT == MVT::v4i16 || VT == MVT::v8i16) && 5250 "Unexpected type for custom ctpop lowering"); 5251 5252 if (VT.getVectorElementType() == MVT::i32) 5253 return lowerCTPOP32BitElements(N, DAG); 5254 else 5255 return lowerCTPOP16BitElements(N, DAG); 5256 } 5257 5258 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5259 const ARMSubtarget *ST) { 5260 EVT VT = N->getValueType(0); 5261 SDLoc dl(N); 5262 5263 if (!VT.isVector()) 5264 return SDValue(); 5265 5266 // Lower vector shifts on NEON to use VSHL. 5267 assert(ST->hasNEON() && "unexpected vector shift"); 5268 5269 // Left shifts translate directly to the vshiftu intrinsic. 5270 if (N->getOpcode() == ISD::SHL) 5271 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5272 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5273 MVT::i32), 5274 N->getOperand(0), N->getOperand(1)); 5275 5276 assert((N->getOpcode() == ISD::SRA || 5277 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5278 5279 // NEON uses the same intrinsics for both left and right shifts. For 5280 // right shifts, the shift amounts are negative, so negate the vector of 5281 // shift amounts. 5282 EVT ShiftVT = N->getOperand(1).getValueType(); 5283 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5284 getZeroVector(ShiftVT, DAG, dl), 5285 N->getOperand(1)); 5286 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5287 Intrinsic::arm_neon_vshifts : 5288 Intrinsic::arm_neon_vshiftu); 5289 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5290 DAG.getConstant(vshiftInt, dl, MVT::i32), 5291 N->getOperand(0), NegatedCount); 5292 } 5293 5294 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5295 const ARMSubtarget *ST) { 5296 EVT VT = N->getValueType(0); 5297 SDLoc dl(N); 5298 5299 // We can get here for a node like i32 = ISD::SHL i32, i64 5300 if (VT != MVT::i64) 5301 return SDValue(); 5302 5303 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5304 "Unknown shift to lower!"); 5305 5306 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5307 if (!isOneConstant(N->getOperand(1))) 5308 return SDValue(); 5309 5310 // If we are in thumb mode, we don't have RRX. 5311 if (ST->isThumb1Only()) return SDValue(); 5312 5313 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5314 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5315 DAG.getConstant(0, dl, MVT::i32)); 5316 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5317 DAG.getConstant(1, dl, MVT::i32)); 5318 5319 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5320 // captures the result into a carry flag. 5321 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5322 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5323 5324 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5325 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5326 5327 // Merge the pieces into a single i64 value. 5328 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5329 } 5330 5331 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5332 SDValue TmpOp0, TmpOp1; 5333 bool Invert = false; 5334 bool Swap = false; 5335 unsigned Opc = 0; 5336 5337 SDValue Op0 = Op.getOperand(0); 5338 SDValue Op1 = Op.getOperand(1); 5339 SDValue CC = Op.getOperand(2); 5340 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5341 EVT VT = Op.getValueType(); 5342 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5343 SDLoc dl(Op); 5344 5345 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5346 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5347 // Special-case integer 64-bit equality comparisons. They aren't legal, 5348 // but they can be lowered with a few vector instructions. 5349 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5350 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5351 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5352 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5353 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5354 DAG.getCondCode(ISD::SETEQ)); 5355 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5356 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5357 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5358 if (SetCCOpcode == ISD::SETNE) 5359 Merged = DAG.getNOT(dl, Merged, CmpVT); 5360 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5361 return Merged; 5362 } 5363 5364 if (CmpVT.getVectorElementType() == MVT::i64) 5365 // 64-bit comparisons are not legal in general. 5366 return SDValue(); 5367 5368 if (Op1.getValueType().isFloatingPoint()) { 5369 switch (SetCCOpcode) { 5370 default: llvm_unreachable("Illegal FP comparison"); 5371 case ISD::SETUNE: 5372 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5373 case ISD::SETOEQ: 5374 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5375 case ISD::SETOLT: 5376 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5377 case ISD::SETOGT: 5378 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5379 case ISD::SETOLE: 5380 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5381 case ISD::SETOGE: 5382 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5383 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5384 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5385 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5386 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5387 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5388 case ISD::SETONE: 5389 // Expand this to (OLT | OGT). 5390 TmpOp0 = Op0; 5391 TmpOp1 = Op1; 5392 Opc = ISD::OR; 5393 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5394 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5395 break; 5396 case ISD::SETUO: 5397 Invert = true; 5398 LLVM_FALLTHROUGH; 5399 case ISD::SETO: 5400 // Expand this to (OLT | OGE). 5401 TmpOp0 = Op0; 5402 TmpOp1 = Op1; 5403 Opc = ISD::OR; 5404 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5405 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5406 break; 5407 } 5408 } else { 5409 // Integer comparisons. 5410 switch (SetCCOpcode) { 5411 default: llvm_unreachable("Illegal integer comparison"); 5412 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5413 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5414 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5415 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5416 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5417 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5418 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5419 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5420 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5421 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5422 } 5423 5424 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5425 if (Opc == ARMISD::VCEQ) { 5426 SDValue AndOp; 5427 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5428 AndOp = Op0; 5429 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5430 AndOp = Op1; 5431 5432 // Ignore bitconvert. 5433 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5434 AndOp = AndOp.getOperand(0); 5435 5436 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5437 Opc = ARMISD::VTST; 5438 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5439 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5440 Invert = !Invert; 5441 } 5442 } 5443 } 5444 5445 if (Swap) 5446 std::swap(Op0, Op1); 5447 5448 // If one of the operands is a constant vector zero, attempt to fold the 5449 // comparison to a specialized compare-against-zero form. 5450 SDValue SingleOp; 5451 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5452 SingleOp = Op0; 5453 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5454 if (Opc == ARMISD::VCGE) 5455 Opc = ARMISD::VCLEZ; 5456 else if (Opc == ARMISD::VCGT) 5457 Opc = ARMISD::VCLTZ; 5458 SingleOp = Op1; 5459 } 5460 5461 SDValue Result; 5462 if (SingleOp.getNode()) { 5463 switch (Opc) { 5464 case ARMISD::VCEQ: 5465 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5466 case ARMISD::VCGE: 5467 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5468 case ARMISD::VCLEZ: 5469 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5470 case ARMISD::VCGT: 5471 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5472 case ARMISD::VCLTZ: 5473 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5474 default: 5475 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5476 } 5477 } else { 5478 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5479 } 5480 5481 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5482 5483 if (Invert) 5484 Result = DAG.getNOT(dl, Result, VT); 5485 5486 return Result; 5487 } 5488 5489 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5490 SDValue LHS = Op.getOperand(0); 5491 SDValue RHS = Op.getOperand(1); 5492 SDValue Carry = Op.getOperand(2); 5493 SDValue Cond = Op.getOperand(3); 5494 SDLoc DL(Op); 5495 5496 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5497 5498 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5499 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5500 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5501 5502 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5503 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5504 SDValue ARMcc = DAG.getConstant( 5505 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5506 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5507 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5508 Cmp.getValue(1), SDValue()); 5509 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5510 CCR, Chain.getValue(1)); 5511 } 5512 5513 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5514 /// valid vector constant for a NEON instruction with a "modified immediate" 5515 /// operand (e.g., VMOV). If so, return the encoded value. 5516 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5517 unsigned SplatBitSize, SelectionDAG &DAG, 5518 const SDLoc &dl, EVT &VT, bool is128Bits, 5519 NEONModImmType type) { 5520 unsigned OpCmode, Imm; 5521 5522 // SplatBitSize is set to the smallest size that splats the vector, so a 5523 // zero vector will always have SplatBitSize == 8. However, NEON modified 5524 // immediate instructions others than VMOV do not support the 8-bit encoding 5525 // of a zero vector, and the default encoding of zero is supposed to be the 5526 // 32-bit version. 5527 if (SplatBits == 0) 5528 SplatBitSize = 32; 5529 5530 switch (SplatBitSize) { 5531 case 8: 5532 if (type != VMOVModImm) 5533 return SDValue(); 5534 // Any 1-byte value is OK. Op=0, Cmode=1110. 5535 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5536 OpCmode = 0xe; 5537 Imm = SplatBits; 5538 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5539 break; 5540 5541 case 16: 5542 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5543 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5544 if ((SplatBits & ~0xff) == 0) { 5545 // Value = 0x00nn: Op=x, Cmode=100x. 5546 OpCmode = 0x8; 5547 Imm = SplatBits; 5548 break; 5549 } 5550 if ((SplatBits & ~0xff00) == 0) { 5551 // Value = 0xnn00: Op=x, Cmode=101x. 5552 OpCmode = 0xa; 5553 Imm = SplatBits >> 8; 5554 break; 5555 } 5556 return SDValue(); 5557 5558 case 32: 5559 // NEON's 32-bit VMOV supports splat values where: 5560 // * only one byte is nonzero, or 5561 // * the least significant byte is 0xff and the second byte is nonzero, or 5562 // * the least significant 2 bytes are 0xff and the third is nonzero. 5563 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5564 if ((SplatBits & ~0xff) == 0) { 5565 // Value = 0x000000nn: Op=x, Cmode=000x. 5566 OpCmode = 0; 5567 Imm = SplatBits; 5568 break; 5569 } 5570 if ((SplatBits & ~0xff00) == 0) { 5571 // Value = 0x0000nn00: Op=x, Cmode=001x. 5572 OpCmode = 0x2; 5573 Imm = SplatBits >> 8; 5574 break; 5575 } 5576 if ((SplatBits & ~0xff0000) == 0) { 5577 // Value = 0x00nn0000: Op=x, Cmode=010x. 5578 OpCmode = 0x4; 5579 Imm = SplatBits >> 16; 5580 break; 5581 } 5582 if ((SplatBits & ~0xff000000) == 0) { 5583 // Value = 0xnn000000: Op=x, Cmode=011x. 5584 OpCmode = 0x6; 5585 Imm = SplatBits >> 24; 5586 break; 5587 } 5588 5589 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5590 if (type == OtherModImm) return SDValue(); 5591 5592 if ((SplatBits & ~0xffff) == 0 && 5593 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5594 // Value = 0x0000nnff: Op=x, Cmode=1100. 5595 OpCmode = 0xc; 5596 Imm = SplatBits >> 8; 5597 break; 5598 } 5599 5600 if ((SplatBits & ~0xffffff) == 0 && 5601 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5602 // Value = 0x00nnffff: Op=x, Cmode=1101. 5603 OpCmode = 0xd; 5604 Imm = SplatBits >> 16; 5605 break; 5606 } 5607 5608 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5609 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5610 // VMOV.I32. A (very) minor optimization would be to replicate the value 5611 // and fall through here to test for a valid 64-bit splat. But, then the 5612 // caller would also need to check and handle the change in size. 5613 return SDValue(); 5614 5615 case 64: { 5616 if (type != VMOVModImm) 5617 return SDValue(); 5618 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5619 uint64_t BitMask = 0xff; 5620 uint64_t Val = 0; 5621 unsigned ImmMask = 1; 5622 Imm = 0; 5623 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5624 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5625 Val |= BitMask; 5626 Imm |= ImmMask; 5627 } else if ((SplatBits & BitMask) != 0) { 5628 return SDValue(); 5629 } 5630 BitMask <<= 8; 5631 ImmMask <<= 1; 5632 } 5633 5634 if (DAG.getDataLayout().isBigEndian()) 5635 // swap higher and lower 32 bit word 5636 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5637 5638 // Op=1, Cmode=1110. 5639 OpCmode = 0x1e; 5640 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5641 break; 5642 } 5643 5644 default: 5645 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5646 } 5647 5648 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5649 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5650 } 5651 5652 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5653 const ARMSubtarget *ST) const { 5654 bool IsDouble = Op.getValueType() == MVT::f64; 5655 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5656 const APFloat &FPVal = CFP->getValueAPF(); 5657 5658 // Prevent floating-point constants from using literal loads 5659 // when execute-only is enabled. 5660 if (ST->genExecuteOnly()) { 5661 APInt INTVal = FPVal.bitcastToAPInt(); 5662 SDLoc DL(CFP); 5663 if (IsDouble) { 5664 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5665 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5666 if (!ST->isLittle()) 5667 std::swap(Lo, Hi); 5668 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5669 } else { 5670 return DAG.getConstant(INTVal, DL, MVT::i32); 5671 } 5672 } 5673 5674 if (!ST->hasVFP3()) 5675 return SDValue(); 5676 5677 // Use the default (constant pool) lowering for double constants when we have 5678 // an SP-only FPU 5679 if (IsDouble && Subtarget->isFPOnlySP()) 5680 return SDValue(); 5681 5682 // Try splatting with a VMOV.f32... 5683 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5684 5685 if (ImmVal != -1) { 5686 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5687 // We have code in place to select a valid ConstantFP already, no need to 5688 // do any mangling. 5689 return Op; 5690 } 5691 5692 // It's a float and we are trying to use NEON operations where 5693 // possible. Lower it to a splat followed by an extract. 5694 SDLoc DL(Op); 5695 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5696 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5697 NewVal); 5698 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5699 DAG.getConstant(0, DL, MVT::i32)); 5700 } 5701 5702 // The rest of our options are NEON only, make sure that's allowed before 5703 // proceeding.. 5704 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5705 return SDValue(); 5706 5707 EVT VMovVT; 5708 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5709 5710 // It wouldn't really be worth bothering for doubles except for one very 5711 // important value, which does happen to match: 0.0. So make sure we don't do 5712 // anything stupid. 5713 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5714 return SDValue(); 5715 5716 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5717 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5718 VMovVT, false, VMOVModImm); 5719 if (NewVal != SDValue()) { 5720 SDLoc DL(Op); 5721 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5722 NewVal); 5723 if (IsDouble) 5724 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5725 5726 // It's a float: cast and extract a vector element. 5727 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5728 VecConstant); 5729 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5730 DAG.getConstant(0, DL, MVT::i32)); 5731 } 5732 5733 // Finally, try a VMVN.i32 5734 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5735 false, VMVNModImm); 5736 if (NewVal != SDValue()) { 5737 SDLoc DL(Op); 5738 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5739 5740 if (IsDouble) 5741 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5742 5743 // It's a float: cast and extract a vector element. 5744 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5745 VecConstant); 5746 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5747 DAG.getConstant(0, DL, MVT::i32)); 5748 } 5749 5750 return SDValue(); 5751 } 5752 5753 // check if an VEXT instruction can handle the shuffle mask when the 5754 // vector sources of the shuffle are the same. 5755 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5756 unsigned NumElts = VT.getVectorNumElements(); 5757 5758 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5759 if (M[0] < 0) 5760 return false; 5761 5762 Imm = M[0]; 5763 5764 // If this is a VEXT shuffle, the immediate value is the index of the first 5765 // element. The other shuffle indices must be the successive elements after 5766 // the first one. 5767 unsigned ExpectedElt = Imm; 5768 for (unsigned i = 1; i < NumElts; ++i) { 5769 // Increment the expected index. If it wraps around, just follow it 5770 // back to index zero and keep going. 5771 ++ExpectedElt; 5772 if (ExpectedElt == NumElts) 5773 ExpectedElt = 0; 5774 5775 if (M[i] < 0) continue; // ignore UNDEF indices 5776 if (ExpectedElt != static_cast<unsigned>(M[i])) 5777 return false; 5778 } 5779 5780 return true; 5781 } 5782 5783 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 5784 bool &ReverseVEXT, unsigned &Imm) { 5785 unsigned NumElts = VT.getVectorNumElements(); 5786 ReverseVEXT = false; 5787 5788 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5789 if (M[0] < 0) 5790 return false; 5791 5792 Imm = M[0]; 5793 5794 // If this is a VEXT shuffle, the immediate value is the index of the first 5795 // element. The other shuffle indices must be the successive elements after 5796 // the first one. 5797 unsigned ExpectedElt = Imm; 5798 for (unsigned i = 1; i < NumElts; ++i) { 5799 // Increment the expected index. If it wraps around, it may still be 5800 // a VEXT but the source vectors must be swapped. 5801 ExpectedElt += 1; 5802 if (ExpectedElt == NumElts * 2) { 5803 ExpectedElt = 0; 5804 ReverseVEXT = true; 5805 } 5806 5807 if (M[i] < 0) continue; // ignore UNDEF indices 5808 if (ExpectedElt != static_cast<unsigned>(M[i])) 5809 return false; 5810 } 5811 5812 // Adjust the index value if the source operands will be swapped. 5813 if (ReverseVEXT) 5814 Imm -= NumElts; 5815 5816 return true; 5817 } 5818 5819 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 5820 /// instruction with the specified blocksize. (The order of the elements 5821 /// within each block of the vector is reversed.) 5822 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5823 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 5824 "Only possible block sizes for VREV are: 16, 32, 64"); 5825 5826 unsigned EltSz = VT.getScalarSizeInBits(); 5827 if (EltSz == 64) 5828 return false; 5829 5830 unsigned NumElts = VT.getVectorNumElements(); 5831 unsigned BlockElts = M[0] + 1; 5832 // If the first shuffle index is UNDEF, be optimistic. 5833 if (M[0] < 0) 5834 BlockElts = BlockSize / EltSz; 5835 5836 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5837 return false; 5838 5839 for (unsigned i = 0; i < NumElts; ++i) { 5840 if (M[i] < 0) continue; // ignore UNDEF indices 5841 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 5842 return false; 5843 } 5844 5845 return true; 5846 } 5847 5848 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 5849 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 5850 // range, then 0 is placed into the resulting vector. So pretty much any mask 5851 // of 8 elements can work here. 5852 return VT == MVT::v8i8 && M.size() == 8; 5853 } 5854 5855 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 5856 unsigned Index) { 5857 if (Mask.size() == Elements * 2) 5858 return Index / Elements; 5859 return Mask[Index] == 0 ? 0 : 1; 5860 } 5861 5862 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 5863 // checking that pairs of elements in the shuffle mask represent the same index 5864 // in each vector, incrementing the expected index by 2 at each step. 5865 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 5866 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 5867 // v2={e,f,g,h} 5868 // WhichResult gives the offset for each element in the mask based on which 5869 // of the two results it belongs to. 5870 // 5871 // The transpose can be represented either as: 5872 // result1 = shufflevector v1, v2, result1_shuffle_mask 5873 // result2 = shufflevector v1, v2, result2_shuffle_mask 5874 // where v1/v2 and the shuffle masks have the same number of elements 5875 // (here WhichResult (see below) indicates which result is being checked) 5876 // 5877 // or as: 5878 // results = shufflevector v1, v2, shuffle_mask 5879 // where both results are returned in one vector and the shuffle mask has twice 5880 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 5881 // want to check the low half and high half of the shuffle mask as if it were 5882 // the other case 5883 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5884 unsigned EltSz = VT.getScalarSizeInBits(); 5885 if (EltSz == 64) 5886 return false; 5887 5888 unsigned NumElts = VT.getVectorNumElements(); 5889 if (M.size() != NumElts && M.size() != NumElts*2) 5890 return false; 5891 5892 // If the mask is twice as long as the input vector then we need to check the 5893 // upper and lower parts of the mask with a matching value for WhichResult 5894 // FIXME: A mask with only even values will be rejected in case the first 5895 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 5896 // M[0] is used to determine WhichResult 5897 for (unsigned i = 0; i < M.size(); i += NumElts) { 5898 WhichResult = SelectPairHalf(NumElts, M, i); 5899 for (unsigned j = 0; j < NumElts; j += 2) { 5900 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5901 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 5902 return false; 5903 } 5904 } 5905 5906 if (M.size() == NumElts*2) 5907 WhichResult = 0; 5908 5909 return true; 5910 } 5911 5912 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 5913 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5914 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5915 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5916 unsigned EltSz = VT.getScalarSizeInBits(); 5917 if (EltSz == 64) 5918 return false; 5919 5920 unsigned NumElts = VT.getVectorNumElements(); 5921 if (M.size() != NumElts && M.size() != NumElts*2) 5922 return false; 5923 5924 for (unsigned i = 0; i < M.size(); i += NumElts) { 5925 WhichResult = SelectPairHalf(NumElts, M, i); 5926 for (unsigned j = 0; j < NumElts; j += 2) { 5927 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 5928 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 5929 return false; 5930 } 5931 } 5932 5933 if (M.size() == NumElts*2) 5934 WhichResult = 0; 5935 5936 return true; 5937 } 5938 5939 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 5940 // that the mask elements are either all even and in steps of size 2 or all odd 5941 // and in steps of size 2. 5942 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 5943 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 5944 // v2={e,f,g,h} 5945 // Requires similar checks to that of isVTRNMask with 5946 // respect the how results are returned. 5947 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5948 unsigned EltSz = VT.getScalarSizeInBits(); 5949 if (EltSz == 64) 5950 return false; 5951 5952 unsigned NumElts = VT.getVectorNumElements(); 5953 if (M.size() != NumElts && M.size() != NumElts*2) 5954 return false; 5955 5956 for (unsigned i = 0; i < M.size(); i += NumElts) { 5957 WhichResult = SelectPairHalf(NumElts, M, i); 5958 for (unsigned j = 0; j < NumElts; ++j) { 5959 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 5960 return false; 5961 } 5962 } 5963 5964 if (M.size() == NumElts*2) 5965 WhichResult = 0; 5966 5967 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 5968 if (VT.is64BitVector() && EltSz == 32) 5969 return false; 5970 5971 return true; 5972 } 5973 5974 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 5975 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5976 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5977 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 5978 unsigned EltSz = VT.getScalarSizeInBits(); 5979 if (EltSz == 64) 5980 return false; 5981 5982 unsigned NumElts = VT.getVectorNumElements(); 5983 if (M.size() != NumElts && M.size() != NumElts*2) 5984 return false; 5985 5986 unsigned Half = NumElts / 2; 5987 for (unsigned i = 0; i < M.size(); i += NumElts) { 5988 WhichResult = SelectPairHalf(NumElts, M, i); 5989 for (unsigned j = 0; j < NumElts; j += Half) { 5990 unsigned Idx = WhichResult; 5991 for (unsigned k = 0; k < Half; ++k) { 5992 int MIdx = M[i + j + k]; 5993 if (MIdx >= 0 && (unsigned) MIdx != Idx) 5994 return false; 5995 Idx += 2; 5996 } 5997 } 5998 } 5999 6000 if (M.size() == NumElts*2) 6001 WhichResult = 0; 6002 6003 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6004 if (VT.is64BitVector() && EltSz == 32) 6005 return false; 6006 6007 return true; 6008 } 6009 6010 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6011 // that pairs of elements of the shufflemask represent the same index in each 6012 // vector incrementing sequentially through the vectors. 6013 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6014 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6015 // v2={e,f,g,h} 6016 // Requires similar checks to that of isVTRNMask with respect the how results 6017 // are returned. 6018 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6019 unsigned EltSz = VT.getScalarSizeInBits(); 6020 if (EltSz == 64) 6021 return false; 6022 6023 unsigned NumElts = VT.getVectorNumElements(); 6024 if (M.size() != NumElts && M.size() != NumElts*2) 6025 return false; 6026 6027 for (unsigned i = 0; i < M.size(); i += NumElts) { 6028 WhichResult = SelectPairHalf(NumElts, M, i); 6029 unsigned Idx = WhichResult * NumElts / 2; 6030 for (unsigned j = 0; j < NumElts; j += 2) { 6031 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6032 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6033 return false; 6034 Idx += 1; 6035 } 6036 } 6037 6038 if (M.size() == NumElts*2) 6039 WhichResult = 0; 6040 6041 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6042 if (VT.is64BitVector() && EltSz == 32) 6043 return false; 6044 6045 return true; 6046 } 6047 6048 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6049 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6050 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6051 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6052 unsigned EltSz = VT.getScalarSizeInBits(); 6053 if (EltSz == 64) 6054 return false; 6055 6056 unsigned NumElts = VT.getVectorNumElements(); 6057 if (M.size() != NumElts && M.size() != NumElts*2) 6058 return false; 6059 6060 for (unsigned i = 0; i < M.size(); i += NumElts) { 6061 WhichResult = SelectPairHalf(NumElts, M, i); 6062 unsigned Idx = WhichResult * NumElts / 2; 6063 for (unsigned j = 0; j < NumElts; j += 2) { 6064 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6065 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6066 return false; 6067 Idx += 1; 6068 } 6069 } 6070 6071 if (M.size() == NumElts*2) 6072 WhichResult = 0; 6073 6074 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6075 if (VT.is64BitVector() && EltSz == 32) 6076 return false; 6077 6078 return true; 6079 } 6080 6081 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6082 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6083 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6084 unsigned &WhichResult, 6085 bool &isV_UNDEF) { 6086 isV_UNDEF = false; 6087 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6088 return ARMISD::VTRN; 6089 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6090 return ARMISD::VUZP; 6091 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6092 return ARMISD::VZIP; 6093 6094 isV_UNDEF = true; 6095 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6096 return ARMISD::VTRN; 6097 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6098 return ARMISD::VUZP; 6099 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6100 return ARMISD::VZIP; 6101 6102 return 0; 6103 } 6104 6105 /// \return true if this is a reverse operation on an vector. 6106 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6107 unsigned NumElts = VT.getVectorNumElements(); 6108 // Make sure the mask has the right size. 6109 if (NumElts != M.size()) 6110 return false; 6111 6112 // Look for <15, ..., 3, -1, 1, 0>. 6113 for (unsigned i = 0; i != NumElts; ++i) 6114 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6115 return false; 6116 6117 return true; 6118 } 6119 6120 // If N is an integer constant that can be moved into a register in one 6121 // instruction, return an SDValue of such a constant (will become a MOV 6122 // instruction). Otherwise return null. 6123 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6124 const ARMSubtarget *ST, const SDLoc &dl) { 6125 uint64_t Val; 6126 if (!isa<ConstantSDNode>(N)) 6127 return SDValue(); 6128 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6129 6130 if (ST->isThumb1Only()) { 6131 if (Val <= 255 || ~Val <= 255) 6132 return DAG.getConstant(Val, dl, MVT::i32); 6133 } else { 6134 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6135 return DAG.getConstant(Val, dl, MVT::i32); 6136 } 6137 return SDValue(); 6138 } 6139 6140 // If this is a case we can't handle, return null and let the default 6141 // expansion code take care of it. 6142 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6143 const ARMSubtarget *ST) const { 6144 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6145 SDLoc dl(Op); 6146 EVT VT = Op.getValueType(); 6147 6148 APInt SplatBits, SplatUndef; 6149 unsigned SplatBitSize; 6150 bool HasAnyUndefs; 6151 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6152 if (SplatUndef.isAllOnesValue()) 6153 return DAG.getUNDEF(VT); 6154 6155 if (SplatBitSize <= 64) { 6156 // Check if an immediate VMOV works. 6157 EVT VmovVT; 6158 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6159 SplatUndef.getZExtValue(), SplatBitSize, 6160 DAG, dl, VmovVT, VT.is128BitVector(), 6161 VMOVModImm); 6162 if (Val.getNode()) { 6163 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6164 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6165 } 6166 6167 // Try an immediate VMVN. 6168 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6169 Val = isNEONModifiedImm(NegatedImm, 6170 SplatUndef.getZExtValue(), SplatBitSize, 6171 DAG, dl, VmovVT, VT.is128BitVector(), 6172 VMVNModImm); 6173 if (Val.getNode()) { 6174 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6175 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6176 } 6177 6178 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6179 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6180 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6181 if (ImmVal != -1) { 6182 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6183 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6184 } 6185 } 6186 } 6187 } 6188 6189 // Scan through the operands to see if only one value is used. 6190 // 6191 // As an optimisation, even if more than one value is used it may be more 6192 // profitable to splat with one value then change some lanes. 6193 // 6194 // Heuristically we decide to do this if the vector has a "dominant" value, 6195 // defined as splatted to more than half of the lanes. 6196 unsigned NumElts = VT.getVectorNumElements(); 6197 bool isOnlyLowElement = true; 6198 bool usesOnlyOneValue = true; 6199 bool hasDominantValue = false; 6200 bool isConstant = true; 6201 6202 // Map of the number of times a particular SDValue appears in the 6203 // element list. 6204 DenseMap<SDValue, unsigned> ValueCounts; 6205 SDValue Value; 6206 for (unsigned i = 0; i < NumElts; ++i) { 6207 SDValue V = Op.getOperand(i); 6208 if (V.isUndef()) 6209 continue; 6210 if (i > 0) 6211 isOnlyLowElement = false; 6212 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6213 isConstant = false; 6214 6215 ValueCounts.insert(std::make_pair(V, 0)); 6216 unsigned &Count = ValueCounts[V]; 6217 6218 // Is this value dominant? (takes up more than half of the lanes) 6219 if (++Count > (NumElts / 2)) { 6220 hasDominantValue = true; 6221 Value = V; 6222 } 6223 } 6224 if (ValueCounts.size() != 1) 6225 usesOnlyOneValue = false; 6226 if (!Value.getNode() && !ValueCounts.empty()) 6227 Value = ValueCounts.begin()->first; 6228 6229 if (ValueCounts.empty()) 6230 return DAG.getUNDEF(VT); 6231 6232 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6233 // Keep going if we are hitting this case. 6234 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6235 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6236 6237 unsigned EltSize = VT.getScalarSizeInBits(); 6238 6239 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6240 // i32 and try again. 6241 if (hasDominantValue && EltSize <= 32) { 6242 if (!isConstant) { 6243 SDValue N; 6244 6245 // If we are VDUPing a value that comes directly from a vector, that will 6246 // cause an unnecessary move to and from a GPR, where instead we could 6247 // just use VDUPLANE. We can only do this if the lane being extracted 6248 // is at a constant index, as the VDUP from lane instructions only have 6249 // constant-index forms. 6250 ConstantSDNode *constIndex; 6251 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6252 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6253 // We need to create a new undef vector to use for the VDUPLANE if the 6254 // size of the vector from which we get the value is different than the 6255 // size of the vector that we need to create. We will insert the element 6256 // such that the register coalescer will remove unnecessary copies. 6257 if (VT != Value->getOperand(0).getValueType()) { 6258 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6259 VT.getVectorNumElements(); 6260 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6261 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6262 Value, DAG.getConstant(index, dl, MVT::i32)), 6263 DAG.getConstant(index, dl, MVT::i32)); 6264 } else 6265 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6266 Value->getOperand(0), Value->getOperand(1)); 6267 } else 6268 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6269 6270 if (!usesOnlyOneValue) { 6271 // The dominant value was splatted as 'N', but we now have to insert 6272 // all differing elements. 6273 for (unsigned I = 0; I < NumElts; ++I) { 6274 if (Op.getOperand(I) == Value) 6275 continue; 6276 SmallVector<SDValue, 3> Ops; 6277 Ops.push_back(N); 6278 Ops.push_back(Op.getOperand(I)); 6279 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6280 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6281 } 6282 } 6283 return N; 6284 } 6285 if (VT.getVectorElementType().isFloatingPoint()) { 6286 SmallVector<SDValue, 8> Ops; 6287 for (unsigned i = 0; i < NumElts; ++i) 6288 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6289 Op.getOperand(i))); 6290 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6291 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6292 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6293 if (Val.getNode()) 6294 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6295 } 6296 if (usesOnlyOneValue) { 6297 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6298 if (isConstant && Val.getNode()) 6299 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6300 } 6301 } 6302 6303 // If all elements are constants and the case above didn't get hit, fall back 6304 // to the default expansion, which will generate a load from the constant 6305 // pool. 6306 if (isConstant) 6307 return SDValue(); 6308 6309 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6310 if (NumElts >= 4) { 6311 SDValue shuffle = ReconstructShuffle(Op, DAG); 6312 if (shuffle != SDValue()) 6313 return shuffle; 6314 } 6315 6316 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6317 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6318 // into two 64-bit vectors; we might discover a better way to lower it. 6319 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6320 EVT ExtVT = VT.getVectorElementType(); 6321 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6322 SDValue Lower = 6323 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6324 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6325 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6326 SDValue Upper = DAG.getBuildVector( 6327 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6328 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6329 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6330 if (Lower && Upper) 6331 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6332 } 6333 6334 // Vectors with 32- or 64-bit elements can be built by directly assigning 6335 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6336 // will be legalized. 6337 if (EltSize >= 32) { 6338 // Do the expansion with floating-point types, since that is what the VFP 6339 // registers are defined to use, and since i64 is not legal. 6340 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6341 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6342 SmallVector<SDValue, 8> Ops; 6343 for (unsigned i = 0; i < NumElts; ++i) 6344 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6345 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6346 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6347 } 6348 6349 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6350 // know the default expansion would otherwise fall back on something even 6351 // worse. For a vector with one or two non-undef values, that's 6352 // scalar_to_vector for the elements followed by a shuffle (provided the 6353 // shuffle is valid for the target) and materialization element by element 6354 // on the stack followed by a load for everything else. 6355 if (!isConstant && !usesOnlyOneValue) { 6356 SDValue Vec = DAG.getUNDEF(VT); 6357 for (unsigned i = 0 ; i < NumElts; ++i) { 6358 SDValue V = Op.getOperand(i); 6359 if (V.isUndef()) 6360 continue; 6361 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6362 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6363 } 6364 return Vec; 6365 } 6366 6367 return SDValue(); 6368 } 6369 6370 // Gather data to see if the operation can be modelled as a 6371 // shuffle in combination with VEXTs. 6372 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6373 SelectionDAG &DAG) const { 6374 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6375 SDLoc dl(Op); 6376 EVT VT = Op.getValueType(); 6377 unsigned NumElts = VT.getVectorNumElements(); 6378 6379 struct ShuffleSourceInfo { 6380 SDValue Vec; 6381 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6382 unsigned MaxElt = 0; 6383 6384 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6385 // be compatible with the shuffle we intend to construct. As a result 6386 // ShuffleVec will be some sliding window into the original Vec. 6387 SDValue ShuffleVec; 6388 6389 // Code should guarantee that element i in Vec starts at element "WindowBase 6390 // + i * WindowScale in ShuffleVec". 6391 int WindowBase = 0; 6392 int WindowScale = 1; 6393 6394 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6395 6396 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6397 }; 6398 6399 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6400 // node. 6401 SmallVector<ShuffleSourceInfo, 2> Sources; 6402 for (unsigned i = 0; i < NumElts; ++i) { 6403 SDValue V = Op.getOperand(i); 6404 if (V.isUndef()) 6405 continue; 6406 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6407 // A shuffle can only come from building a vector from various 6408 // elements of other vectors. 6409 return SDValue(); 6410 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6411 // Furthermore, shuffles require a constant mask, whereas extractelts 6412 // accept variable indices. 6413 return SDValue(); 6414 } 6415 6416 // Add this element source to the list if it's not already there. 6417 SDValue SourceVec = V.getOperand(0); 6418 auto Source = llvm::find(Sources, SourceVec); 6419 if (Source == Sources.end()) 6420 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6421 6422 // Update the minimum and maximum lane number seen. 6423 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6424 Source->MinElt = std::min(Source->MinElt, EltNo); 6425 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6426 } 6427 6428 // Currently only do something sane when at most two source vectors 6429 // are involved. 6430 if (Sources.size() > 2) 6431 return SDValue(); 6432 6433 // Find out the smallest element size among result and two sources, and use 6434 // it as element size to build the shuffle_vector. 6435 EVT SmallestEltTy = VT.getVectorElementType(); 6436 for (auto &Source : Sources) { 6437 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6438 if (SrcEltTy.bitsLT(SmallestEltTy)) 6439 SmallestEltTy = SrcEltTy; 6440 } 6441 unsigned ResMultiplier = 6442 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6443 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6444 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6445 6446 // If the source vector is too wide or too narrow, we may nevertheless be able 6447 // to construct a compatible shuffle either by concatenating it with UNDEF or 6448 // extracting a suitable range of elements. 6449 for (auto &Src : Sources) { 6450 EVT SrcVT = Src.ShuffleVec.getValueType(); 6451 6452 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6453 continue; 6454 6455 // This stage of the search produces a source with the same element type as 6456 // the original, but with a total width matching the BUILD_VECTOR output. 6457 EVT EltVT = SrcVT.getVectorElementType(); 6458 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6459 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6460 6461 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6462 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6463 return SDValue(); 6464 // We can pad out the smaller vector for free, so if it's part of a 6465 // shuffle... 6466 Src.ShuffleVec = 6467 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6468 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6469 continue; 6470 } 6471 6472 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6473 return SDValue(); 6474 6475 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6476 // Span too large for a VEXT to cope 6477 return SDValue(); 6478 } 6479 6480 if (Src.MinElt >= NumSrcElts) { 6481 // The extraction can just take the second half 6482 Src.ShuffleVec = 6483 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6484 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6485 Src.WindowBase = -NumSrcElts; 6486 } else if (Src.MaxElt < NumSrcElts) { 6487 // The extraction can just take the first half 6488 Src.ShuffleVec = 6489 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6490 DAG.getConstant(0, dl, MVT::i32)); 6491 } else { 6492 // An actual VEXT is needed 6493 SDValue VEXTSrc1 = 6494 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6495 DAG.getConstant(0, dl, MVT::i32)); 6496 SDValue VEXTSrc2 = 6497 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6498 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6499 6500 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6501 VEXTSrc2, 6502 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6503 Src.WindowBase = -Src.MinElt; 6504 } 6505 } 6506 6507 // Another possible incompatibility occurs from the vector element types. We 6508 // can fix this by bitcasting the source vectors to the same type we intend 6509 // for the shuffle. 6510 for (auto &Src : Sources) { 6511 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6512 if (SrcEltTy == SmallestEltTy) 6513 continue; 6514 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6515 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6516 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6517 Src.WindowBase *= Src.WindowScale; 6518 } 6519 6520 // Final sanity check before we try to actually produce a shuffle. 6521 DEBUG( 6522 for (auto Src : Sources) 6523 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6524 ); 6525 6526 // The stars all align, our next step is to produce the mask for the shuffle. 6527 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6528 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6529 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6530 SDValue Entry = Op.getOperand(i); 6531 if (Entry.isUndef()) 6532 continue; 6533 6534 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6535 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6536 6537 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6538 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6539 // segment. 6540 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6541 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6542 VT.getScalarSizeInBits()); 6543 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6544 6545 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6546 // starting at the appropriate offset. 6547 int *LaneMask = &Mask[i * ResMultiplier]; 6548 6549 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6550 ExtractBase += NumElts * (Src - Sources.begin()); 6551 for (int j = 0; j < LanesDefined; ++j) 6552 LaneMask[j] = ExtractBase + j; 6553 } 6554 6555 // Final check before we try to produce nonsense... 6556 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6557 return SDValue(); 6558 6559 // We can't handle more than two sources. This should have already 6560 // been checked before this point. 6561 assert(Sources.size() <= 2 && "Too many sources!"); 6562 6563 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6564 for (unsigned i = 0; i < Sources.size(); ++i) 6565 ShuffleOps[i] = Sources[i].ShuffleVec; 6566 6567 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6568 ShuffleOps[1], Mask); 6569 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6570 } 6571 6572 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6573 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6574 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6575 /// are assumed to be legal. 6576 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 6577 if (VT.getVectorNumElements() == 4 && 6578 (VT.is128BitVector() || VT.is64BitVector())) { 6579 unsigned PFIndexes[4]; 6580 for (unsigned i = 0; i != 4; ++i) { 6581 if (M[i] < 0) 6582 PFIndexes[i] = 8; 6583 else 6584 PFIndexes[i] = M[i]; 6585 } 6586 6587 // Compute the index in the perfect shuffle table. 6588 unsigned PFTableIndex = 6589 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6590 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6591 unsigned Cost = (PFEntry >> 30); 6592 6593 if (Cost <= 4) 6594 return true; 6595 } 6596 6597 bool ReverseVEXT, isV_UNDEF; 6598 unsigned Imm, WhichResult; 6599 6600 unsigned EltSize = VT.getScalarSizeInBits(); 6601 return (EltSize >= 32 || 6602 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6603 isVREVMask(M, VT, 64) || 6604 isVREVMask(M, VT, 32) || 6605 isVREVMask(M, VT, 16) || 6606 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6607 isVTBLMask(M, VT) || 6608 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6609 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6610 } 6611 6612 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6613 /// the specified operations to build the shuffle. 6614 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6615 SDValue RHS, SelectionDAG &DAG, 6616 const SDLoc &dl) { 6617 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6618 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6619 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6620 6621 enum { 6622 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6623 OP_VREV, 6624 OP_VDUP0, 6625 OP_VDUP1, 6626 OP_VDUP2, 6627 OP_VDUP3, 6628 OP_VEXT1, 6629 OP_VEXT2, 6630 OP_VEXT3, 6631 OP_VUZPL, // VUZP, left result 6632 OP_VUZPR, // VUZP, right result 6633 OP_VZIPL, // VZIP, left result 6634 OP_VZIPR, // VZIP, right result 6635 OP_VTRNL, // VTRN, left result 6636 OP_VTRNR // VTRN, right result 6637 }; 6638 6639 if (OpNum == OP_COPY) { 6640 if (LHSID == (1*9+2)*9+3) return LHS; 6641 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6642 return RHS; 6643 } 6644 6645 SDValue OpLHS, OpRHS; 6646 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6647 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6648 EVT VT = OpLHS.getValueType(); 6649 6650 switch (OpNum) { 6651 default: llvm_unreachable("Unknown shuffle opcode!"); 6652 case OP_VREV: 6653 // VREV divides the vector in half and swaps within the half. 6654 if (VT.getVectorElementType() == MVT::i32 || 6655 VT.getVectorElementType() == MVT::f32) 6656 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6657 // vrev <4 x i16> -> VREV32 6658 if (VT.getVectorElementType() == MVT::i16) 6659 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6660 // vrev <4 x i8> -> VREV16 6661 assert(VT.getVectorElementType() == MVT::i8); 6662 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6663 case OP_VDUP0: 6664 case OP_VDUP1: 6665 case OP_VDUP2: 6666 case OP_VDUP3: 6667 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6668 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6669 case OP_VEXT1: 6670 case OP_VEXT2: 6671 case OP_VEXT3: 6672 return DAG.getNode(ARMISD::VEXT, dl, VT, 6673 OpLHS, OpRHS, 6674 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6675 case OP_VUZPL: 6676 case OP_VUZPR: 6677 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6678 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6679 case OP_VZIPL: 6680 case OP_VZIPR: 6681 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6682 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6683 case OP_VTRNL: 6684 case OP_VTRNR: 6685 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6686 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6687 } 6688 } 6689 6690 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6691 ArrayRef<int> ShuffleMask, 6692 SelectionDAG &DAG) { 6693 // Check to see if we can use the VTBL instruction. 6694 SDValue V1 = Op.getOperand(0); 6695 SDValue V2 = Op.getOperand(1); 6696 SDLoc DL(Op); 6697 6698 SmallVector<SDValue, 8> VTBLMask; 6699 for (ArrayRef<int>::iterator 6700 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6701 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6702 6703 if (V2.getNode()->isUndef()) 6704 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6705 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6706 6707 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6708 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6709 } 6710 6711 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6712 SelectionDAG &DAG) { 6713 SDLoc DL(Op); 6714 SDValue OpLHS = Op.getOperand(0); 6715 EVT VT = OpLHS.getValueType(); 6716 6717 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6718 "Expect an v8i16/v16i8 type"); 6719 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6720 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6721 // extract the first 8 bytes into the top double word and the last 8 bytes 6722 // into the bottom double word. The v8i16 case is similar. 6723 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6724 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6725 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6726 } 6727 6728 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6729 SDValue V1 = Op.getOperand(0); 6730 SDValue V2 = Op.getOperand(1); 6731 SDLoc dl(Op); 6732 EVT VT = Op.getValueType(); 6733 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6734 6735 // Convert shuffles that are directly supported on NEON to target-specific 6736 // DAG nodes, instead of keeping them as shuffles and matching them again 6737 // during code selection. This is more efficient and avoids the possibility 6738 // of inconsistencies between legalization and selection. 6739 // FIXME: floating-point vectors should be canonicalized to integer vectors 6740 // of the same time so that they get CSEd properly. 6741 ArrayRef<int> ShuffleMask = SVN->getMask(); 6742 6743 unsigned EltSize = VT.getScalarSizeInBits(); 6744 if (EltSize <= 32) { 6745 if (SVN->isSplat()) { 6746 int Lane = SVN->getSplatIndex(); 6747 // If this is undef splat, generate it via "just" vdup, if possible. 6748 if (Lane == -1) Lane = 0; 6749 6750 // Test if V1 is a SCALAR_TO_VECTOR. 6751 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6752 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6753 } 6754 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 6755 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 6756 // reaches it). 6757 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 6758 !isa<ConstantSDNode>(V1.getOperand(0))) { 6759 bool IsScalarToVector = true; 6760 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 6761 if (!V1.getOperand(i).isUndef()) { 6762 IsScalarToVector = false; 6763 break; 6764 } 6765 if (IsScalarToVector) 6766 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6767 } 6768 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 6769 DAG.getConstant(Lane, dl, MVT::i32)); 6770 } 6771 6772 bool ReverseVEXT; 6773 unsigned Imm; 6774 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 6775 if (ReverseVEXT) 6776 std::swap(V1, V2); 6777 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 6778 DAG.getConstant(Imm, dl, MVT::i32)); 6779 } 6780 6781 if (isVREVMask(ShuffleMask, VT, 64)) 6782 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 6783 if (isVREVMask(ShuffleMask, VT, 32)) 6784 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 6785 if (isVREVMask(ShuffleMask, VT, 16)) 6786 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 6787 6788 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 6789 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 6790 DAG.getConstant(Imm, dl, MVT::i32)); 6791 } 6792 6793 // Check for Neon shuffles that modify both input vectors in place. 6794 // If both results are used, i.e., if there are two shuffles with the same 6795 // source operands and with masks corresponding to both results of one of 6796 // these operations, DAG memoization will ensure that a single node is 6797 // used for both shuffles. 6798 unsigned WhichResult; 6799 bool isV_UNDEF; 6800 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6801 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 6802 if (isV_UNDEF) 6803 V2 = V1; 6804 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 6805 .getValue(WhichResult); 6806 } 6807 6808 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 6809 // shuffles that produce a result larger than their operands with: 6810 // shuffle(concat(v1, undef), concat(v2, undef)) 6811 // -> 6812 // shuffle(concat(v1, v2), undef) 6813 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 6814 // 6815 // This is useful in the general case, but there are special cases where 6816 // native shuffles produce larger results: the two-result ops. 6817 // 6818 // Look through the concat when lowering them: 6819 // shuffle(concat(v1, v2), undef) 6820 // -> 6821 // concat(VZIP(v1, v2):0, :1) 6822 // 6823 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 6824 SDValue SubV1 = V1->getOperand(0); 6825 SDValue SubV2 = V1->getOperand(1); 6826 EVT SubVT = SubV1.getValueType(); 6827 6828 // We expect these to have been canonicalized to -1. 6829 assert(llvm::all_of(ShuffleMask, [&](int i) { 6830 return i < (int)VT.getVectorNumElements(); 6831 }) && "Unexpected shuffle index into UNDEF operand!"); 6832 6833 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 6834 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 6835 if (isV_UNDEF) 6836 SubV2 = SubV1; 6837 assert((WhichResult == 0) && 6838 "In-place shuffle of concat can only have one result!"); 6839 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 6840 SubV1, SubV2); 6841 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 6842 Res.getValue(1)); 6843 } 6844 } 6845 } 6846 6847 // If the shuffle is not directly supported and it has 4 elements, use 6848 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6849 unsigned NumElts = VT.getVectorNumElements(); 6850 if (NumElts == 4) { 6851 unsigned PFIndexes[4]; 6852 for (unsigned i = 0; i != 4; ++i) { 6853 if (ShuffleMask[i] < 0) 6854 PFIndexes[i] = 8; 6855 else 6856 PFIndexes[i] = ShuffleMask[i]; 6857 } 6858 6859 // Compute the index in the perfect shuffle table. 6860 unsigned PFTableIndex = 6861 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6862 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6863 unsigned Cost = (PFEntry >> 30); 6864 6865 if (Cost <= 4) 6866 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6867 } 6868 6869 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 6870 if (EltSize >= 32) { 6871 // Do the expansion with floating-point types, since that is what the VFP 6872 // registers are defined to use, and since i64 is not legal. 6873 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6874 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6875 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 6876 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 6877 SmallVector<SDValue, 8> Ops; 6878 for (unsigned i = 0; i < NumElts; ++i) { 6879 if (ShuffleMask[i] < 0) 6880 Ops.push_back(DAG.getUNDEF(EltVT)); 6881 else 6882 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6883 ShuffleMask[i] < (int)NumElts ? V1 : V2, 6884 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 6885 dl, MVT::i32))); 6886 } 6887 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6888 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6889 } 6890 6891 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 6892 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 6893 6894 if (VT == MVT::v8i8) 6895 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 6896 return NewOp; 6897 6898 return SDValue(); 6899 } 6900 6901 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6902 // INSERT_VECTOR_ELT is legal only for immediate indexes. 6903 SDValue Lane = Op.getOperand(2); 6904 if (!isa<ConstantSDNode>(Lane)) 6905 return SDValue(); 6906 6907 return Op; 6908 } 6909 6910 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 6911 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 6912 SDValue Lane = Op.getOperand(1); 6913 if (!isa<ConstantSDNode>(Lane)) 6914 return SDValue(); 6915 6916 SDValue Vec = Op.getOperand(0); 6917 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 6918 SDLoc dl(Op); 6919 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 6920 } 6921 6922 return Op; 6923 } 6924 6925 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6926 // The only time a CONCAT_VECTORS operation can have legal types is when 6927 // two 64-bit vectors are concatenated to a 128-bit vector. 6928 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 6929 "unexpected CONCAT_VECTORS"); 6930 SDLoc dl(Op); 6931 SDValue Val = DAG.getUNDEF(MVT::v2f64); 6932 SDValue Op0 = Op.getOperand(0); 6933 SDValue Op1 = Op.getOperand(1); 6934 if (!Op0.isUndef()) 6935 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6936 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 6937 DAG.getIntPtrConstant(0, dl)); 6938 if (!Op1.isUndef()) 6939 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 6940 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 6941 DAG.getIntPtrConstant(1, dl)); 6942 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 6943 } 6944 6945 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 6946 /// element has been zero/sign-extended, depending on the isSigned parameter, 6947 /// from an integer type half its size. 6948 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 6949 bool isSigned) { 6950 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 6951 EVT VT = N->getValueType(0); 6952 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 6953 SDNode *BVN = N->getOperand(0).getNode(); 6954 if (BVN->getValueType(0) != MVT::v4i32 || 6955 BVN->getOpcode() != ISD::BUILD_VECTOR) 6956 return false; 6957 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 6958 unsigned HiElt = 1 - LoElt; 6959 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 6960 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 6961 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 6962 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 6963 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 6964 return false; 6965 if (isSigned) { 6966 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 6967 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 6968 return true; 6969 } else { 6970 if (Hi0->isNullValue() && Hi1->isNullValue()) 6971 return true; 6972 } 6973 return false; 6974 } 6975 6976 if (N->getOpcode() != ISD::BUILD_VECTOR) 6977 return false; 6978 6979 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 6980 SDNode *Elt = N->getOperand(i).getNode(); 6981 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 6982 unsigned EltSize = VT.getScalarSizeInBits(); 6983 unsigned HalfSize = EltSize / 2; 6984 if (isSigned) { 6985 if (!isIntN(HalfSize, C->getSExtValue())) 6986 return false; 6987 } else { 6988 if (!isUIntN(HalfSize, C->getZExtValue())) 6989 return false; 6990 } 6991 continue; 6992 } 6993 return false; 6994 } 6995 6996 return true; 6997 } 6998 6999 /// isSignExtended - Check if a node is a vector value that is sign-extended 7000 /// or a constant BUILD_VECTOR with sign-extended elements. 7001 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7002 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7003 return true; 7004 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7005 return true; 7006 return false; 7007 } 7008 7009 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7010 /// or a constant BUILD_VECTOR with zero-extended elements. 7011 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7012 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7013 return true; 7014 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7015 return true; 7016 return false; 7017 } 7018 7019 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7020 if (OrigVT.getSizeInBits() >= 64) 7021 return OrigVT; 7022 7023 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7024 7025 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7026 switch (OrigSimpleTy) { 7027 default: llvm_unreachable("Unexpected Vector Type"); 7028 case MVT::v2i8: 7029 case MVT::v2i16: 7030 return MVT::v2i32; 7031 case MVT::v4i8: 7032 return MVT::v4i16; 7033 } 7034 } 7035 7036 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7037 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7038 /// We insert the required extension here to get the vector to fill a D register. 7039 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7040 const EVT &OrigTy, 7041 const EVT &ExtTy, 7042 unsigned ExtOpcode) { 7043 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7044 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7045 // 64-bits we need to insert a new extension so that it will be 64-bits. 7046 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7047 if (OrigTy.getSizeInBits() >= 64) 7048 return N; 7049 7050 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7051 EVT NewVT = getExtensionTo64Bits(OrigTy); 7052 7053 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7054 } 7055 7056 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7057 /// does not do any sign/zero extension. If the original vector is less 7058 /// than 64 bits, an appropriate extension will be added after the load to 7059 /// reach a total size of 64 bits. We have to add the extension separately 7060 /// because ARM does not have a sign/zero extending load for vectors. 7061 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7062 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7063 7064 // The load already has the right type. 7065 if (ExtendedTy == LD->getMemoryVT()) 7066 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7067 LD->getBasePtr(), LD->getPointerInfo(), 7068 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7069 7070 // We need to create a zextload/sextload. We cannot just create a load 7071 // followed by a zext/zext node because LowerMUL is also run during normal 7072 // operation legalization where we can't create illegal types. 7073 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7074 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7075 LD->getMemoryVT(), LD->getAlignment(), 7076 LD->getMemOperand()->getFlags()); 7077 } 7078 7079 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7080 /// extending load, or BUILD_VECTOR with extended elements, return the 7081 /// unextended value. The unextended vector should be 64 bits so that it can 7082 /// be used as an operand to a VMULL instruction. If the original vector size 7083 /// before extension is less than 64 bits we add a an extension to resize 7084 /// the vector to 64 bits. 7085 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7086 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7087 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7088 N->getOperand(0)->getValueType(0), 7089 N->getValueType(0), 7090 N->getOpcode()); 7091 7092 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7093 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7094 "Expected extending load"); 7095 7096 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7097 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7098 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7099 SDValue extLoad = 7100 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7101 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7102 7103 return newLoad; 7104 } 7105 7106 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7107 // have been legalized as a BITCAST from v4i32. 7108 if (N->getOpcode() == ISD::BITCAST) { 7109 SDNode *BVN = N->getOperand(0).getNode(); 7110 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7111 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7112 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7113 return DAG.getBuildVector( 7114 MVT::v2i32, SDLoc(N), 7115 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7116 } 7117 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7118 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7119 EVT VT = N->getValueType(0); 7120 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7121 unsigned NumElts = VT.getVectorNumElements(); 7122 MVT TruncVT = MVT::getIntegerVT(EltSize); 7123 SmallVector<SDValue, 8> Ops; 7124 SDLoc dl(N); 7125 for (unsigned i = 0; i != NumElts; ++i) { 7126 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7127 const APInt &CInt = C->getAPIntValue(); 7128 // Element types smaller than 32 bits are not legal, so use i32 elements. 7129 // The values are implicitly truncated so sext vs. zext doesn't matter. 7130 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7131 } 7132 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7133 } 7134 7135 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7136 unsigned Opcode = N->getOpcode(); 7137 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7138 SDNode *N0 = N->getOperand(0).getNode(); 7139 SDNode *N1 = N->getOperand(1).getNode(); 7140 return N0->hasOneUse() && N1->hasOneUse() && 7141 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7142 } 7143 return false; 7144 } 7145 7146 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7147 unsigned Opcode = N->getOpcode(); 7148 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7149 SDNode *N0 = N->getOperand(0).getNode(); 7150 SDNode *N1 = N->getOperand(1).getNode(); 7151 return N0->hasOneUse() && N1->hasOneUse() && 7152 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7153 } 7154 return false; 7155 } 7156 7157 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7158 // Multiplications are only custom-lowered for 128-bit vectors so that 7159 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7160 EVT VT = Op.getValueType(); 7161 assert(VT.is128BitVector() && VT.isInteger() && 7162 "unexpected type for custom-lowering ISD::MUL"); 7163 SDNode *N0 = Op.getOperand(0).getNode(); 7164 SDNode *N1 = Op.getOperand(1).getNode(); 7165 unsigned NewOpc = 0; 7166 bool isMLA = false; 7167 bool isN0SExt = isSignExtended(N0, DAG); 7168 bool isN1SExt = isSignExtended(N1, DAG); 7169 if (isN0SExt && isN1SExt) 7170 NewOpc = ARMISD::VMULLs; 7171 else { 7172 bool isN0ZExt = isZeroExtended(N0, DAG); 7173 bool isN1ZExt = isZeroExtended(N1, DAG); 7174 if (isN0ZExt && isN1ZExt) 7175 NewOpc = ARMISD::VMULLu; 7176 else if (isN1SExt || isN1ZExt) { 7177 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7178 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7179 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7180 NewOpc = ARMISD::VMULLs; 7181 isMLA = true; 7182 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7183 NewOpc = ARMISD::VMULLu; 7184 isMLA = true; 7185 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7186 std::swap(N0, N1); 7187 NewOpc = ARMISD::VMULLu; 7188 isMLA = true; 7189 } 7190 } 7191 7192 if (!NewOpc) { 7193 if (VT == MVT::v2i64) 7194 // Fall through to expand this. It is not legal. 7195 return SDValue(); 7196 else 7197 // Other vector multiplications are legal. 7198 return Op; 7199 } 7200 } 7201 7202 // Legalize to a VMULL instruction. 7203 SDLoc DL(Op); 7204 SDValue Op0; 7205 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7206 if (!isMLA) { 7207 Op0 = SkipExtensionForVMULL(N0, DAG); 7208 assert(Op0.getValueType().is64BitVector() && 7209 Op1.getValueType().is64BitVector() && 7210 "unexpected types for extended operands to VMULL"); 7211 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7212 } 7213 7214 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7215 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7216 // vmull q0, d4, d6 7217 // vmlal q0, d5, d6 7218 // is faster than 7219 // vaddl q0, d4, d5 7220 // vmovl q1, d6 7221 // vmul q0, q0, q1 7222 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7223 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7224 EVT Op1VT = Op1.getValueType(); 7225 return DAG.getNode(N0->getOpcode(), DL, VT, 7226 DAG.getNode(NewOpc, DL, VT, 7227 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7228 DAG.getNode(NewOpc, DL, VT, 7229 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7230 } 7231 7232 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7233 SelectionDAG &DAG) { 7234 // TODO: Should this propagate fast-math-flags? 7235 7236 // Convert to float 7237 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7238 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7239 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7240 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7241 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7242 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7243 // Get reciprocal estimate. 7244 // float4 recip = vrecpeq_f32(yf); 7245 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7246 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7247 Y); 7248 // Because char has a smaller range than uchar, we can actually get away 7249 // without any newton steps. This requires that we use a weird bias 7250 // of 0xb000, however (again, this has been exhaustively tested). 7251 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7252 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7253 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7254 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7255 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7256 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7257 // Convert back to short. 7258 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7259 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7260 return X; 7261 } 7262 7263 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7264 SelectionDAG &DAG) { 7265 // TODO: Should this propagate fast-math-flags? 7266 7267 SDValue N2; 7268 // Convert to float. 7269 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7270 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7271 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7272 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7273 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7274 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7275 7276 // Use reciprocal estimate and one refinement step. 7277 // float4 recip = vrecpeq_f32(yf); 7278 // recip *= vrecpsq_f32(yf, recip); 7279 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7280 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7281 N1); 7282 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7283 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7284 N1, N2); 7285 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7286 // Because short has a smaller range than ushort, we can actually get away 7287 // with only a single newton step. This requires that we use a weird bias 7288 // of 89, however (again, this has been exhaustively tested). 7289 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7290 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7291 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7292 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7293 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7294 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7295 // Convert back to integer and return. 7296 // return vmovn_s32(vcvt_s32_f32(result)); 7297 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7298 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7299 return N0; 7300 } 7301 7302 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7303 EVT VT = Op.getValueType(); 7304 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7305 "unexpected type for custom-lowering ISD::SDIV"); 7306 7307 SDLoc dl(Op); 7308 SDValue N0 = Op.getOperand(0); 7309 SDValue N1 = Op.getOperand(1); 7310 SDValue N2, N3; 7311 7312 if (VT == MVT::v8i8) { 7313 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7314 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7315 7316 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7317 DAG.getIntPtrConstant(4, dl)); 7318 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7319 DAG.getIntPtrConstant(4, dl)); 7320 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7321 DAG.getIntPtrConstant(0, dl)); 7322 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7323 DAG.getIntPtrConstant(0, dl)); 7324 7325 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7326 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7327 7328 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7329 N0 = LowerCONCAT_VECTORS(N0, DAG); 7330 7331 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7332 return N0; 7333 } 7334 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7335 } 7336 7337 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7338 // TODO: Should this propagate fast-math-flags? 7339 EVT VT = Op.getValueType(); 7340 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7341 "unexpected type for custom-lowering ISD::UDIV"); 7342 7343 SDLoc dl(Op); 7344 SDValue N0 = Op.getOperand(0); 7345 SDValue N1 = Op.getOperand(1); 7346 SDValue N2, N3; 7347 7348 if (VT == MVT::v8i8) { 7349 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7350 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7351 7352 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7353 DAG.getIntPtrConstant(4, dl)); 7354 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7355 DAG.getIntPtrConstant(4, dl)); 7356 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7357 DAG.getIntPtrConstant(0, dl)); 7358 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7359 DAG.getIntPtrConstant(0, dl)); 7360 7361 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7362 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7363 7364 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7365 N0 = LowerCONCAT_VECTORS(N0, DAG); 7366 7367 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7368 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7369 MVT::i32), 7370 N0); 7371 return N0; 7372 } 7373 7374 // v4i16 sdiv ... Convert to float. 7375 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7376 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7377 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7378 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7379 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7380 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7381 7382 // Use reciprocal estimate and two refinement steps. 7383 // float4 recip = vrecpeq_f32(yf); 7384 // recip *= vrecpsq_f32(yf, recip); 7385 // recip *= vrecpsq_f32(yf, recip); 7386 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7387 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7388 BN1); 7389 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7390 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7391 BN1, N2); 7392 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7393 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7394 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7395 BN1, N2); 7396 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7397 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7398 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7399 // and that it will never cause us to return an answer too large). 7400 // float4 result = as_float4(as_int4(xf*recip) + 2); 7401 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7402 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7403 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7404 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7405 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7406 // Convert back to integer and return. 7407 // return vmovn_u32(vcvt_s32_f32(result)); 7408 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7409 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7410 return N0; 7411 } 7412 7413 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7414 EVT VT = Op.getNode()->getValueType(0); 7415 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7416 7417 unsigned Opc; 7418 bool ExtraOp = false; 7419 switch (Op.getOpcode()) { 7420 default: llvm_unreachable("Invalid code"); 7421 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7422 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7423 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7424 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7425 } 7426 7427 if (!ExtraOp) 7428 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7429 Op.getOperand(1)); 7430 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7431 Op.getOperand(1), Op.getOperand(2)); 7432 } 7433 7434 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 7435 SDNode *N = Op.getNode(); 7436 EVT VT = N->getValueType(0); 7437 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7438 7439 SDValue Carry = Op.getOperand(2); 7440 EVT CarryVT = Carry.getValueType(); 7441 7442 SDLoc DL(Op); 7443 7444 APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits()); 7445 7446 SDValue Result; 7447 if (Op.getOpcode() == ISD::ADDCARRY) { 7448 // This converts the boolean value carry into the carry flag. 7449 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7450 7451 // Do the addition proper using the carry flag we wanted. 7452 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 7453 Op.getOperand(1), Carry.getValue(1)); 7454 7455 // Now convert the carry flag into a boolean value. 7456 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7457 } else { 7458 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 7459 // have to invert the carry first. 7460 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7461 DAG.getConstant(1, DL, MVT::i32), Carry); 7462 // This converts the boolean value carry into the carry flag. 7463 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7464 7465 // Do the subtraction proper using the carry flag we wanted. 7466 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 7467 Op.getOperand(1), Carry.getValue(1)); 7468 7469 // Now convert the carry flag into a boolean value. 7470 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7471 // But the carry returned by ARMISD::SUBE is not a borrow as expected 7472 // by ISD::SUBCARRY, so compute 1 - C. 7473 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7474 DAG.getConstant(1, DL, MVT::i32), Carry); 7475 } 7476 7477 // Return both values. 7478 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 7479 } 7480 7481 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7482 assert(Subtarget->isTargetDarwin()); 7483 7484 // For iOS, we want to call an alternative entry point: __sincos_stret, 7485 // return values are passed via sret. 7486 SDLoc dl(Op); 7487 SDValue Arg = Op.getOperand(0); 7488 EVT ArgVT = Arg.getValueType(); 7489 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7490 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7491 7492 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7493 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7494 7495 // Pair of floats / doubles used to pass the result. 7496 Type *RetTy = StructType::get(ArgTy, ArgTy); 7497 auto &DL = DAG.getDataLayout(); 7498 7499 ArgListTy Args; 7500 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7501 SDValue SRet; 7502 if (ShouldUseSRet) { 7503 // Create stack object for sret. 7504 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7505 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7506 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7507 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7508 7509 ArgListEntry Entry; 7510 Entry.Node = SRet; 7511 Entry.Ty = RetTy->getPointerTo(); 7512 Entry.IsSExt = false; 7513 Entry.IsZExt = false; 7514 Entry.IsSRet = true; 7515 Args.push_back(Entry); 7516 RetTy = Type::getVoidTy(*DAG.getContext()); 7517 } 7518 7519 ArgListEntry Entry; 7520 Entry.Node = Arg; 7521 Entry.Ty = ArgTy; 7522 Entry.IsSExt = false; 7523 Entry.IsZExt = false; 7524 Args.push_back(Entry); 7525 7526 const char *LibcallName = 7527 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 7528 RTLIB::Libcall LC = 7529 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32; 7530 CallingConv::ID CC = getLibcallCallingConv(LC); 7531 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7532 7533 TargetLowering::CallLoweringInfo CLI(DAG); 7534 CLI.setDebugLoc(dl) 7535 .setChain(DAG.getEntryNode()) 7536 .setCallee(CC, RetTy, Callee, std::move(Args)) 7537 .setDiscardResult(ShouldUseSRet); 7538 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7539 7540 if (!ShouldUseSRet) 7541 return CallResult.first; 7542 7543 SDValue LoadSin = 7544 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7545 7546 // Address of cos field. 7547 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7548 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7549 SDValue LoadCos = 7550 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7551 7552 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7553 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7554 LoadSin.getValue(0), LoadCos.getValue(0)); 7555 } 7556 7557 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7558 bool Signed, 7559 SDValue &Chain) const { 7560 EVT VT = Op.getValueType(); 7561 assert((VT == MVT::i32 || VT == MVT::i64) && 7562 "unexpected type for custom lowering DIV"); 7563 SDLoc dl(Op); 7564 7565 const auto &DL = DAG.getDataLayout(); 7566 const auto &TLI = DAG.getTargetLoweringInfo(); 7567 7568 const char *Name = nullptr; 7569 if (Signed) 7570 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7571 else 7572 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7573 7574 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7575 7576 ARMTargetLowering::ArgListTy Args; 7577 7578 for (auto AI : {1, 0}) { 7579 ArgListEntry Arg; 7580 Arg.Node = Op.getOperand(AI); 7581 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7582 Args.push_back(Arg); 7583 } 7584 7585 CallLoweringInfo CLI(DAG); 7586 CLI.setDebugLoc(dl) 7587 .setChain(Chain) 7588 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7589 ES, std::move(Args)); 7590 7591 return LowerCallTo(CLI).first; 7592 } 7593 7594 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7595 bool Signed) const { 7596 assert(Op.getValueType() == MVT::i32 && 7597 "unexpected type for custom lowering DIV"); 7598 SDLoc dl(Op); 7599 7600 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7601 DAG.getEntryNode(), Op.getOperand(1)); 7602 7603 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7604 } 7605 7606 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7607 SDLoc DL(N); 7608 SDValue Op = N->getOperand(1); 7609 if (N->getValueType(0) == MVT::i32) 7610 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7611 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7612 DAG.getConstant(0, DL, MVT::i32)); 7613 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7614 DAG.getConstant(1, DL, MVT::i32)); 7615 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7616 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7617 } 7618 7619 void ARMTargetLowering::ExpandDIV_Windows( 7620 SDValue Op, SelectionDAG &DAG, bool Signed, 7621 SmallVectorImpl<SDValue> &Results) const { 7622 const auto &DL = DAG.getDataLayout(); 7623 const auto &TLI = DAG.getTargetLoweringInfo(); 7624 7625 assert(Op.getValueType() == MVT::i64 && 7626 "unexpected type for custom lowering DIV"); 7627 SDLoc dl(Op); 7628 7629 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7630 7631 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7632 7633 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7634 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7635 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7636 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7637 7638 Results.push_back(Lower); 7639 Results.push_back(Upper); 7640 } 7641 7642 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7643 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7644 // Acquire/Release load/store is not legal for targets without a dmb or 7645 // equivalent available. 7646 return SDValue(); 7647 7648 // Monotonic load/store is legal for all targets. 7649 return Op; 7650 } 7651 7652 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7653 SmallVectorImpl<SDValue> &Results, 7654 SelectionDAG &DAG, 7655 const ARMSubtarget *Subtarget) { 7656 SDLoc DL(N); 7657 // Under Power Management extensions, the cycle-count is: 7658 // mrc p15, #0, <Rt>, c9, c13, #0 7659 SDValue Ops[] = { N->getOperand(0), // Chain 7660 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7661 DAG.getConstant(15, DL, MVT::i32), 7662 DAG.getConstant(0, DL, MVT::i32), 7663 DAG.getConstant(9, DL, MVT::i32), 7664 DAG.getConstant(13, DL, MVT::i32), 7665 DAG.getConstant(0, DL, MVT::i32) 7666 }; 7667 7668 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7669 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7670 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7671 DAG.getConstant(0, DL, MVT::i32))); 7672 Results.push_back(Cycles32.getValue(1)); 7673 } 7674 7675 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7676 SDLoc dl(V.getNode()); 7677 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7678 SDValue VHi = DAG.getAnyExtOrTrunc( 7679 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7680 dl, MVT::i32); 7681 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7682 if (isBigEndian) 7683 std::swap (VLo, VHi); 7684 SDValue RegClass = 7685 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7686 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7687 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7688 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7689 return SDValue( 7690 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7691 } 7692 7693 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7694 SmallVectorImpl<SDValue> & Results, 7695 SelectionDAG &DAG) { 7696 assert(N->getValueType(0) == MVT::i64 && 7697 "AtomicCmpSwap on types less than 64 should be legal"); 7698 SDValue Ops[] = {N->getOperand(1), 7699 createGPRPairNode(DAG, N->getOperand(2)), 7700 createGPRPairNode(DAG, N->getOperand(3)), 7701 N->getOperand(0)}; 7702 SDNode *CmpSwap = DAG.getMachineNode( 7703 ARM::CMP_SWAP_64, SDLoc(N), 7704 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7705 7706 MachineFunction &MF = DAG.getMachineFunction(); 7707 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7708 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7709 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7710 7711 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7712 7713 Results.push_back( 7714 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 7715 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7716 Results.push_back( 7717 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 7718 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7719 Results.push_back(SDValue(CmpSwap, 2)); 7720 } 7721 7722 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 7723 SelectionDAG &DAG) { 7724 const auto &TLI = DAG.getTargetLoweringInfo(); 7725 7726 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 7727 "Custom lowering is MSVCRT specific!"); 7728 7729 SDLoc dl(Op); 7730 SDValue Val = Op.getOperand(0); 7731 MVT Ty = Val->getSimpleValueType(0); 7732 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 7733 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 7734 TLI.getPointerTy(DAG.getDataLayout())); 7735 7736 TargetLowering::ArgListTy Args; 7737 TargetLowering::ArgListEntry Entry; 7738 7739 Entry.Node = Val; 7740 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7741 Entry.IsZExt = true; 7742 Args.push_back(Entry); 7743 7744 Entry.Node = Exponent; 7745 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 7746 Entry.IsZExt = true; 7747 Args.push_back(Entry); 7748 7749 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7750 7751 // In the in-chain to the call is the entry node If we are emitting a 7752 // tailcall, the chain will be mutated if the node has a non-entry input 7753 // chain. 7754 SDValue InChain = DAG.getEntryNode(); 7755 SDValue TCChain = InChain; 7756 7757 const Function &F = DAG.getMachineFunction().getFunction(); 7758 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 7759 F.getReturnType() == LCRTy; 7760 if (IsTC) 7761 InChain = TCChain; 7762 7763 TargetLowering::CallLoweringInfo CLI(DAG); 7764 CLI.setDebugLoc(dl) 7765 .setChain(InChain) 7766 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 7767 .setTailCall(IsTC); 7768 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 7769 7770 // Return the chain (the DAG root) if it is a tail call 7771 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 7772 } 7773 7774 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7775 DEBUG(dbgs() << "Lowering node: "; Op.dump()); 7776 switch (Op.getOpcode()) { 7777 default: llvm_unreachable("Don't know how to custom lower this!"); 7778 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 7779 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 7780 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 7781 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 7782 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 7783 case ISD::SELECT: return LowerSELECT(Op, DAG); 7784 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 7785 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 7786 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 7787 case ISD::VASTART: return LowerVASTART(Op, DAG); 7788 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 7789 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 7790 case ISD::SINT_TO_FP: 7791 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 7792 case ISD::FP_TO_SINT: 7793 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 7794 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 7795 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 7796 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 7797 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 7798 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 7799 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 7800 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 7801 Subtarget); 7802 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 7803 case ISD::SHL: 7804 case ISD::SRL: 7805 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 7806 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 7807 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 7808 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 7809 case ISD::SRL_PARTS: 7810 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 7811 case ISD::CTTZ: 7812 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 7813 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 7814 case ISD::SETCC: return LowerVSETCC(Op, DAG); 7815 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 7816 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 7817 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 7818 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 7819 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 7820 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 7821 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 7822 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 7823 case ISD::MUL: return LowerMUL(Op, DAG); 7824 case ISD::SDIV: 7825 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7826 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 7827 return LowerSDIV(Op, DAG); 7828 case ISD::UDIV: 7829 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 7830 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 7831 return LowerUDIV(Op, DAG); 7832 case ISD::ADDC: 7833 case ISD::ADDE: 7834 case ISD::SUBC: 7835 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 7836 case ISD::ADDCARRY: 7837 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 7838 case ISD::SADDO: 7839 case ISD::SSUBO: 7840 return LowerSignedALUO(Op, DAG); 7841 case ISD::UADDO: 7842 case ISD::USUBO: 7843 return LowerUnsignedALUO(Op, DAG); 7844 case ISD::ATOMIC_LOAD: 7845 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 7846 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 7847 case ISD::SDIVREM: 7848 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 7849 case ISD::DYNAMIC_STACKALLOC: 7850 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment()) 7851 return LowerDYNAMIC_STACKALLOC(Op, DAG); 7852 llvm_unreachable("Don't know how to custom lower this!"); 7853 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 7854 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 7855 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 7856 case ARMISD::WIN__DBZCHK: return SDValue(); 7857 } 7858 } 7859 7860 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 7861 SelectionDAG &DAG) { 7862 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7863 unsigned Opc = 0; 7864 if (IntNo == Intrinsic::arm_smlald) 7865 Opc = ARMISD::SMLALD; 7866 else if (IntNo == Intrinsic::arm_smlaldx) 7867 Opc = ARMISD::SMLALDX; 7868 else if (IntNo == Intrinsic::arm_smlsld) 7869 Opc = ARMISD::SMLSLD; 7870 else if (IntNo == Intrinsic::arm_smlsldx) 7871 Opc = ARMISD::SMLSLDX; 7872 else 7873 return; 7874 7875 SDLoc dl(N); 7876 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7877 N->getOperand(3), 7878 DAG.getConstant(0, dl, MVT::i32)); 7879 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7880 N->getOperand(3), 7881 DAG.getConstant(1, dl, MVT::i32)); 7882 7883 SDValue LongMul = DAG.getNode(Opc, dl, 7884 DAG.getVTList(MVT::i32, MVT::i32), 7885 N->getOperand(1), N->getOperand(2), 7886 Lo, Hi); 7887 Results.push_back(LongMul.getValue(0)); 7888 Results.push_back(LongMul.getValue(1)); 7889 } 7890 7891 /// ReplaceNodeResults - Replace the results of node with an illegal result 7892 /// type with new values built out of custom code. 7893 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 7894 SmallVectorImpl<SDValue> &Results, 7895 SelectionDAG &DAG) const { 7896 SDValue Res; 7897 switch (N->getOpcode()) { 7898 default: 7899 llvm_unreachable("Don't know how to custom expand this!"); 7900 case ISD::READ_REGISTER: 7901 ExpandREAD_REGISTER(N, Results, DAG); 7902 break; 7903 case ISD::BITCAST: 7904 Res = ExpandBITCAST(N, DAG); 7905 break; 7906 case ISD::SRL: 7907 case ISD::SRA: 7908 Res = Expand64BitShift(N, DAG, Subtarget); 7909 break; 7910 case ISD::SREM: 7911 case ISD::UREM: 7912 Res = LowerREM(N, DAG); 7913 break; 7914 case ISD::SDIVREM: 7915 case ISD::UDIVREM: 7916 Res = LowerDivRem(SDValue(N, 0), DAG); 7917 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 7918 Results.push_back(Res.getValue(0)); 7919 Results.push_back(Res.getValue(1)); 7920 return; 7921 case ISD::READCYCLECOUNTER: 7922 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 7923 return; 7924 case ISD::UDIV: 7925 case ISD::SDIV: 7926 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 7927 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 7928 Results); 7929 case ISD::ATOMIC_CMP_SWAP: 7930 ReplaceCMP_SWAP_64Results(N, Results, DAG); 7931 return; 7932 case ISD::INTRINSIC_WO_CHAIN: 7933 return ReplaceLongIntrinsic(N, Results, DAG); 7934 } 7935 if (Res.getNode()) 7936 Results.push_back(Res); 7937 } 7938 7939 //===----------------------------------------------------------------------===// 7940 // ARM Scheduler Hooks 7941 //===----------------------------------------------------------------------===// 7942 7943 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 7944 /// registers the function context. 7945 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 7946 MachineBasicBlock *MBB, 7947 MachineBasicBlock *DispatchBB, 7948 int FI) const { 7949 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 7950 "ROPI/RWPI not currently supported with SjLj"); 7951 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 7952 DebugLoc dl = MI.getDebugLoc(); 7953 MachineFunction *MF = MBB->getParent(); 7954 MachineRegisterInfo *MRI = &MF->getRegInfo(); 7955 MachineConstantPool *MCP = MF->getConstantPool(); 7956 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 7957 const Function &F = MF->getFunction(); 7958 7959 bool isThumb = Subtarget->isThumb(); 7960 bool isThumb2 = Subtarget->isThumb2(); 7961 7962 unsigned PCLabelId = AFI->createPICLabelUId(); 7963 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 7964 ARMConstantPoolValue *CPV = 7965 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 7966 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 7967 7968 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 7969 : &ARM::GPRRegClass; 7970 7971 // Grab constant pool and fixed stack memory operands. 7972 MachineMemOperand *CPMMO = 7973 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 7974 MachineMemOperand::MOLoad, 4, 4); 7975 7976 MachineMemOperand *FIMMOSt = 7977 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 7978 MachineMemOperand::MOStore, 4, 4); 7979 7980 // Load the address of the dispatch MBB into the jump buffer. 7981 if (isThumb2) { 7982 // Incoming value: jbuf 7983 // ldr.n r5, LCPI1_1 7984 // orr r5, r5, #1 7985 // add r5, pc 7986 // str r5, [$jbuf, #+4] ; &jbuf[1] 7987 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 7988 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 7989 .addConstantPoolIndex(CPI) 7990 .addMemOperand(CPMMO) 7991 .add(predOps(ARMCC::AL)); 7992 // Set the low bit because of thumb mode. 7993 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 7994 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 7995 .addReg(NewVReg1, RegState::Kill) 7996 .addImm(0x01) 7997 .add(predOps(ARMCC::AL)) 7998 .add(condCodeOp()); 7999 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8000 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8001 .addReg(NewVReg2, RegState::Kill) 8002 .addImm(PCLabelId); 8003 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8004 .addReg(NewVReg3, RegState::Kill) 8005 .addFrameIndex(FI) 8006 .addImm(36) // &jbuf[1] :: pc 8007 .addMemOperand(FIMMOSt) 8008 .add(predOps(ARMCC::AL)); 8009 } else if (isThumb) { 8010 // Incoming value: jbuf 8011 // ldr.n r1, LCPI1_4 8012 // add r1, pc 8013 // mov r2, #1 8014 // orrs r1, r2 8015 // add r2, $jbuf, #+4 ; &jbuf[1] 8016 // str r1, [r2] 8017 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8018 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8019 .addConstantPoolIndex(CPI) 8020 .addMemOperand(CPMMO) 8021 .add(predOps(ARMCC::AL)); 8022 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8023 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8024 .addReg(NewVReg1, RegState::Kill) 8025 .addImm(PCLabelId); 8026 // Set the low bit because of thumb mode. 8027 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8028 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8029 .addReg(ARM::CPSR, RegState::Define) 8030 .addImm(1) 8031 .add(predOps(ARMCC::AL)); 8032 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8033 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8034 .addReg(ARM::CPSR, RegState::Define) 8035 .addReg(NewVReg2, RegState::Kill) 8036 .addReg(NewVReg3, RegState::Kill) 8037 .add(predOps(ARMCC::AL)); 8038 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8039 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8040 .addFrameIndex(FI) 8041 .addImm(36); // &jbuf[1] :: pc 8042 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8043 .addReg(NewVReg4, RegState::Kill) 8044 .addReg(NewVReg5, RegState::Kill) 8045 .addImm(0) 8046 .addMemOperand(FIMMOSt) 8047 .add(predOps(ARMCC::AL)); 8048 } else { 8049 // Incoming value: jbuf 8050 // ldr r1, LCPI1_1 8051 // add r1, pc, r1 8052 // str r1, [$jbuf, #+4] ; &jbuf[1] 8053 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8054 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8055 .addConstantPoolIndex(CPI) 8056 .addImm(0) 8057 .addMemOperand(CPMMO) 8058 .add(predOps(ARMCC::AL)); 8059 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8060 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8061 .addReg(NewVReg1, RegState::Kill) 8062 .addImm(PCLabelId) 8063 .add(predOps(ARMCC::AL)); 8064 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8065 .addReg(NewVReg2, RegState::Kill) 8066 .addFrameIndex(FI) 8067 .addImm(36) // &jbuf[1] :: pc 8068 .addMemOperand(FIMMOSt) 8069 .add(predOps(ARMCC::AL)); 8070 } 8071 } 8072 8073 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8074 MachineBasicBlock *MBB) const { 8075 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8076 DebugLoc dl = MI.getDebugLoc(); 8077 MachineFunction *MF = MBB->getParent(); 8078 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8079 MachineFrameInfo &MFI = MF->getFrameInfo(); 8080 int FI = MFI.getFunctionContextIndex(); 8081 8082 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8083 : &ARM::GPRnopcRegClass; 8084 8085 // Get a mapping of the call site numbers to all of the landing pads they're 8086 // associated with. 8087 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8088 unsigned MaxCSNum = 0; 8089 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8090 ++BB) { 8091 if (!BB->isEHPad()) continue; 8092 8093 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8094 // pad. 8095 for (MachineBasicBlock::iterator 8096 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8097 if (!II->isEHLabel()) continue; 8098 8099 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8100 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8101 8102 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8103 for (SmallVectorImpl<unsigned>::iterator 8104 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8105 CSI != CSE; ++CSI) { 8106 CallSiteNumToLPad[*CSI].push_back(&*BB); 8107 MaxCSNum = std::max(MaxCSNum, *CSI); 8108 } 8109 break; 8110 } 8111 } 8112 8113 // Get an ordered list of the machine basic blocks for the jump table. 8114 std::vector<MachineBasicBlock*> LPadList; 8115 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8116 LPadList.reserve(CallSiteNumToLPad.size()); 8117 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8118 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8119 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8120 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8121 LPadList.push_back(*II); 8122 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8123 } 8124 } 8125 8126 assert(!LPadList.empty() && 8127 "No landing pad destinations for the dispatch jump table!"); 8128 8129 // Create the jump table and associated information. 8130 MachineJumpTableInfo *JTI = 8131 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8132 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8133 8134 // Create the MBBs for the dispatch code. 8135 8136 // Shove the dispatch's address into the return slot in the function context. 8137 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8138 DispatchBB->setIsEHPad(); 8139 8140 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8141 unsigned trap_opcode; 8142 if (Subtarget->isThumb()) 8143 trap_opcode = ARM::tTRAP; 8144 else 8145 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8146 8147 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8148 DispatchBB->addSuccessor(TrapBB); 8149 8150 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8151 DispatchBB->addSuccessor(DispContBB); 8152 8153 // Insert and MBBs. 8154 MF->insert(MF->end(), DispatchBB); 8155 MF->insert(MF->end(), DispContBB); 8156 MF->insert(MF->end(), TrapBB); 8157 8158 // Insert code into the entry block that creates and registers the function 8159 // context. 8160 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8161 8162 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8163 MachinePointerInfo::getFixedStack(*MF, FI), 8164 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8165 8166 MachineInstrBuilder MIB; 8167 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8168 8169 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8170 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8171 8172 // Add a register mask with no preserved registers. This results in all 8173 // registers being marked as clobbered. This can't work if the dispatch block 8174 // is in a Thumb1 function and is linked with ARM code which uses the FP 8175 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8176 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8177 8178 bool IsPositionIndependent = isPositionIndependent(); 8179 unsigned NumLPads = LPadList.size(); 8180 if (Subtarget->isThumb2()) { 8181 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8182 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8183 .addFrameIndex(FI) 8184 .addImm(4) 8185 .addMemOperand(FIMMOLd) 8186 .add(predOps(ARMCC::AL)); 8187 8188 if (NumLPads < 256) { 8189 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8190 .addReg(NewVReg1) 8191 .addImm(LPadList.size()) 8192 .add(predOps(ARMCC::AL)); 8193 } else { 8194 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8195 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8196 .addImm(NumLPads & 0xFFFF) 8197 .add(predOps(ARMCC::AL)); 8198 8199 unsigned VReg2 = VReg1; 8200 if ((NumLPads & 0xFFFF0000) != 0) { 8201 VReg2 = MRI->createVirtualRegister(TRC); 8202 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8203 .addReg(VReg1) 8204 .addImm(NumLPads >> 16) 8205 .add(predOps(ARMCC::AL)); 8206 } 8207 8208 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8209 .addReg(NewVReg1) 8210 .addReg(VReg2) 8211 .add(predOps(ARMCC::AL)); 8212 } 8213 8214 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8215 .addMBB(TrapBB) 8216 .addImm(ARMCC::HI) 8217 .addReg(ARM::CPSR); 8218 8219 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8220 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8221 .addJumpTableIndex(MJTI) 8222 .add(predOps(ARMCC::AL)); 8223 8224 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8225 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8226 .addReg(NewVReg3, RegState::Kill) 8227 .addReg(NewVReg1) 8228 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8229 .add(predOps(ARMCC::AL)) 8230 .add(condCodeOp()); 8231 8232 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8233 .addReg(NewVReg4, RegState::Kill) 8234 .addReg(NewVReg1) 8235 .addJumpTableIndex(MJTI); 8236 } else if (Subtarget->isThumb()) { 8237 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8238 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8239 .addFrameIndex(FI) 8240 .addImm(1) 8241 .addMemOperand(FIMMOLd) 8242 .add(predOps(ARMCC::AL)); 8243 8244 if (NumLPads < 256) { 8245 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8246 .addReg(NewVReg1) 8247 .addImm(NumLPads) 8248 .add(predOps(ARMCC::AL)); 8249 } else { 8250 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8251 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8252 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8253 8254 // MachineConstantPool wants an explicit alignment. 8255 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8256 if (Align == 0) 8257 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8258 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8259 8260 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8261 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8262 .addReg(VReg1, RegState::Define) 8263 .addConstantPoolIndex(Idx) 8264 .add(predOps(ARMCC::AL)); 8265 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8266 .addReg(NewVReg1) 8267 .addReg(VReg1) 8268 .add(predOps(ARMCC::AL)); 8269 } 8270 8271 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8272 .addMBB(TrapBB) 8273 .addImm(ARMCC::HI) 8274 .addReg(ARM::CPSR); 8275 8276 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8277 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8278 .addReg(ARM::CPSR, RegState::Define) 8279 .addReg(NewVReg1) 8280 .addImm(2) 8281 .add(predOps(ARMCC::AL)); 8282 8283 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8284 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8285 .addJumpTableIndex(MJTI) 8286 .add(predOps(ARMCC::AL)); 8287 8288 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8289 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8290 .addReg(ARM::CPSR, RegState::Define) 8291 .addReg(NewVReg2, RegState::Kill) 8292 .addReg(NewVReg3) 8293 .add(predOps(ARMCC::AL)); 8294 8295 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8296 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8297 8298 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8299 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8300 .addReg(NewVReg4, RegState::Kill) 8301 .addImm(0) 8302 .addMemOperand(JTMMOLd) 8303 .add(predOps(ARMCC::AL)); 8304 8305 unsigned NewVReg6 = NewVReg5; 8306 if (IsPositionIndependent) { 8307 NewVReg6 = MRI->createVirtualRegister(TRC); 8308 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8309 .addReg(ARM::CPSR, RegState::Define) 8310 .addReg(NewVReg5, RegState::Kill) 8311 .addReg(NewVReg3) 8312 .add(predOps(ARMCC::AL)); 8313 } 8314 8315 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8316 .addReg(NewVReg6, RegState::Kill) 8317 .addJumpTableIndex(MJTI); 8318 } else { 8319 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8320 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8321 .addFrameIndex(FI) 8322 .addImm(4) 8323 .addMemOperand(FIMMOLd) 8324 .add(predOps(ARMCC::AL)); 8325 8326 if (NumLPads < 256) { 8327 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8328 .addReg(NewVReg1) 8329 .addImm(NumLPads) 8330 .add(predOps(ARMCC::AL)); 8331 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8332 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8333 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8334 .addImm(NumLPads & 0xFFFF) 8335 .add(predOps(ARMCC::AL)); 8336 8337 unsigned VReg2 = VReg1; 8338 if ((NumLPads & 0xFFFF0000) != 0) { 8339 VReg2 = MRI->createVirtualRegister(TRC); 8340 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8341 .addReg(VReg1) 8342 .addImm(NumLPads >> 16) 8343 .add(predOps(ARMCC::AL)); 8344 } 8345 8346 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8347 .addReg(NewVReg1) 8348 .addReg(VReg2) 8349 .add(predOps(ARMCC::AL)); 8350 } else { 8351 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8352 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8353 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8354 8355 // MachineConstantPool wants an explicit alignment. 8356 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8357 if (Align == 0) 8358 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8359 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8360 8361 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8362 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8363 .addReg(VReg1, RegState::Define) 8364 .addConstantPoolIndex(Idx) 8365 .addImm(0) 8366 .add(predOps(ARMCC::AL)); 8367 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8368 .addReg(NewVReg1) 8369 .addReg(VReg1, RegState::Kill) 8370 .add(predOps(ARMCC::AL)); 8371 } 8372 8373 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8374 .addMBB(TrapBB) 8375 .addImm(ARMCC::HI) 8376 .addReg(ARM::CPSR); 8377 8378 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8379 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8380 .addReg(NewVReg1) 8381 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8382 .add(predOps(ARMCC::AL)) 8383 .add(condCodeOp()); 8384 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8385 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8386 .addJumpTableIndex(MJTI) 8387 .add(predOps(ARMCC::AL)); 8388 8389 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8390 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8391 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8392 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8393 .addReg(NewVReg3, RegState::Kill) 8394 .addReg(NewVReg4) 8395 .addImm(0) 8396 .addMemOperand(JTMMOLd) 8397 .add(predOps(ARMCC::AL)); 8398 8399 if (IsPositionIndependent) { 8400 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8401 .addReg(NewVReg5, RegState::Kill) 8402 .addReg(NewVReg4) 8403 .addJumpTableIndex(MJTI); 8404 } else { 8405 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8406 .addReg(NewVReg5, RegState::Kill) 8407 .addJumpTableIndex(MJTI); 8408 } 8409 } 8410 8411 // Add the jump table entries as successors to the MBB. 8412 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8413 for (std::vector<MachineBasicBlock*>::iterator 8414 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8415 MachineBasicBlock *CurMBB = *I; 8416 if (SeenMBBs.insert(CurMBB).second) 8417 DispContBB->addSuccessor(CurMBB); 8418 } 8419 8420 // N.B. the order the invoke BBs are processed in doesn't matter here. 8421 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8422 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8423 for (MachineBasicBlock *BB : InvokeBBs) { 8424 8425 // Remove the landing pad successor from the invoke block and replace it 8426 // with the new dispatch block. 8427 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8428 BB->succ_end()); 8429 while (!Successors.empty()) { 8430 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8431 if (SMBB->isEHPad()) { 8432 BB->removeSuccessor(SMBB); 8433 MBBLPads.push_back(SMBB); 8434 } 8435 } 8436 8437 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8438 BB->normalizeSuccProbs(); 8439 8440 // Find the invoke call and mark all of the callee-saved registers as 8441 // 'implicit defined' so that they're spilled. This prevents code from 8442 // moving instructions to before the EH block, where they will never be 8443 // executed. 8444 for (MachineBasicBlock::reverse_iterator 8445 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8446 if (!II->isCall()) continue; 8447 8448 DenseMap<unsigned, bool> DefRegs; 8449 for (MachineInstr::mop_iterator 8450 OI = II->operands_begin(), OE = II->operands_end(); 8451 OI != OE; ++OI) { 8452 if (!OI->isReg()) continue; 8453 DefRegs[OI->getReg()] = true; 8454 } 8455 8456 MachineInstrBuilder MIB(*MF, &*II); 8457 8458 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8459 unsigned Reg = SavedRegs[i]; 8460 if (Subtarget->isThumb2() && 8461 !ARM::tGPRRegClass.contains(Reg) && 8462 !ARM::hGPRRegClass.contains(Reg)) 8463 continue; 8464 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8465 continue; 8466 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8467 continue; 8468 if (!DefRegs[Reg]) 8469 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8470 } 8471 8472 break; 8473 } 8474 } 8475 8476 // Mark all former landing pads as non-landing pads. The dispatch is the only 8477 // landing pad now. 8478 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8479 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8480 (*I)->setIsEHPad(false); 8481 8482 // The instruction is gone now. 8483 MI.eraseFromParent(); 8484 } 8485 8486 static 8487 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8488 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8489 E = MBB->succ_end(); I != E; ++I) 8490 if (*I != Succ) 8491 return *I; 8492 llvm_unreachable("Expecting a BB with two successors!"); 8493 } 8494 8495 /// Return the load opcode for a given load size. If load size >= 8, 8496 /// neon opcode will be returned. 8497 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8498 if (LdSize >= 8) 8499 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8500 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8501 if (IsThumb1) 8502 return LdSize == 4 ? ARM::tLDRi 8503 : LdSize == 2 ? ARM::tLDRHi 8504 : LdSize == 1 ? ARM::tLDRBi : 0; 8505 if (IsThumb2) 8506 return LdSize == 4 ? ARM::t2LDR_POST 8507 : LdSize == 2 ? ARM::t2LDRH_POST 8508 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8509 return LdSize == 4 ? ARM::LDR_POST_IMM 8510 : LdSize == 2 ? ARM::LDRH_POST 8511 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8512 } 8513 8514 /// Return the store opcode for a given store size. If store size >= 8, 8515 /// neon opcode will be returned. 8516 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8517 if (StSize >= 8) 8518 return StSize == 16 ? ARM::VST1q32wb_fixed 8519 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8520 if (IsThumb1) 8521 return StSize == 4 ? ARM::tSTRi 8522 : StSize == 2 ? ARM::tSTRHi 8523 : StSize == 1 ? ARM::tSTRBi : 0; 8524 if (IsThumb2) 8525 return StSize == 4 ? ARM::t2STR_POST 8526 : StSize == 2 ? ARM::t2STRH_POST 8527 : StSize == 1 ? ARM::t2STRB_POST : 0; 8528 return StSize == 4 ? ARM::STR_POST_IMM 8529 : StSize == 2 ? ARM::STRH_POST 8530 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8531 } 8532 8533 /// Emit a post-increment load operation with given size. The instructions 8534 /// will be added to BB at Pos. 8535 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8536 const TargetInstrInfo *TII, const DebugLoc &dl, 8537 unsigned LdSize, unsigned Data, unsigned AddrIn, 8538 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8539 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8540 assert(LdOpc != 0 && "Should have a load opcode"); 8541 if (LdSize >= 8) { 8542 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8543 .addReg(AddrOut, RegState::Define) 8544 .addReg(AddrIn) 8545 .addImm(0) 8546 .add(predOps(ARMCC::AL)); 8547 } else if (IsThumb1) { 8548 // load + update AddrIn 8549 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8550 .addReg(AddrIn) 8551 .addImm(0) 8552 .add(predOps(ARMCC::AL)); 8553 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8554 .add(t1CondCodeOp()) 8555 .addReg(AddrIn) 8556 .addImm(LdSize) 8557 .add(predOps(ARMCC::AL)); 8558 } else if (IsThumb2) { 8559 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8560 .addReg(AddrOut, RegState::Define) 8561 .addReg(AddrIn) 8562 .addImm(LdSize) 8563 .add(predOps(ARMCC::AL)); 8564 } else { // arm 8565 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8566 .addReg(AddrOut, RegState::Define) 8567 .addReg(AddrIn) 8568 .addReg(0) 8569 .addImm(LdSize) 8570 .add(predOps(ARMCC::AL)); 8571 } 8572 } 8573 8574 /// Emit a post-increment store operation with given size. The instructions 8575 /// will be added to BB at Pos. 8576 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8577 const TargetInstrInfo *TII, const DebugLoc &dl, 8578 unsigned StSize, unsigned Data, unsigned AddrIn, 8579 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8580 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8581 assert(StOpc != 0 && "Should have a store opcode"); 8582 if (StSize >= 8) { 8583 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8584 .addReg(AddrIn) 8585 .addImm(0) 8586 .addReg(Data) 8587 .add(predOps(ARMCC::AL)); 8588 } else if (IsThumb1) { 8589 // store + update AddrIn 8590 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8591 .addReg(Data) 8592 .addReg(AddrIn) 8593 .addImm(0) 8594 .add(predOps(ARMCC::AL)); 8595 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8596 .add(t1CondCodeOp()) 8597 .addReg(AddrIn) 8598 .addImm(StSize) 8599 .add(predOps(ARMCC::AL)); 8600 } else if (IsThumb2) { 8601 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8602 .addReg(Data) 8603 .addReg(AddrIn) 8604 .addImm(StSize) 8605 .add(predOps(ARMCC::AL)); 8606 } else { // arm 8607 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8608 .addReg(Data) 8609 .addReg(AddrIn) 8610 .addReg(0) 8611 .addImm(StSize) 8612 .add(predOps(ARMCC::AL)); 8613 } 8614 } 8615 8616 MachineBasicBlock * 8617 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8618 MachineBasicBlock *BB) const { 8619 // This pseudo instruction has 3 operands: dst, src, size 8620 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8621 // Otherwise, we will generate unrolled scalar copies. 8622 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8623 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8624 MachineFunction::iterator It = ++BB->getIterator(); 8625 8626 unsigned dest = MI.getOperand(0).getReg(); 8627 unsigned src = MI.getOperand(1).getReg(); 8628 unsigned SizeVal = MI.getOperand(2).getImm(); 8629 unsigned Align = MI.getOperand(3).getImm(); 8630 DebugLoc dl = MI.getDebugLoc(); 8631 8632 MachineFunction *MF = BB->getParent(); 8633 MachineRegisterInfo &MRI = MF->getRegInfo(); 8634 unsigned UnitSize = 0; 8635 const TargetRegisterClass *TRC = nullptr; 8636 const TargetRegisterClass *VecTRC = nullptr; 8637 8638 bool IsThumb1 = Subtarget->isThumb1Only(); 8639 bool IsThumb2 = Subtarget->isThumb2(); 8640 bool IsThumb = Subtarget->isThumb(); 8641 8642 if (Align & 1) { 8643 UnitSize = 1; 8644 } else if (Align & 2) { 8645 UnitSize = 2; 8646 } else { 8647 // Check whether we can use NEON instructions. 8648 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 8649 Subtarget->hasNEON()) { 8650 if ((Align % 16 == 0) && SizeVal >= 16) 8651 UnitSize = 16; 8652 else if ((Align % 8 == 0) && SizeVal >= 8) 8653 UnitSize = 8; 8654 } 8655 // Can't use NEON instructions. 8656 if (UnitSize == 0) 8657 UnitSize = 4; 8658 } 8659 8660 // Select the correct opcode and register class for unit size load/store 8661 bool IsNeon = UnitSize >= 8; 8662 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8663 if (IsNeon) 8664 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8665 : UnitSize == 8 ? &ARM::DPRRegClass 8666 : nullptr; 8667 8668 unsigned BytesLeft = SizeVal % UnitSize; 8669 unsigned LoopSize = SizeVal - BytesLeft; 8670 8671 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8672 // Use LDR and STR to copy. 8673 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8674 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8675 unsigned srcIn = src; 8676 unsigned destIn = dest; 8677 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8678 unsigned srcOut = MRI.createVirtualRegister(TRC); 8679 unsigned destOut = MRI.createVirtualRegister(TRC); 8680 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8681 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8682 IsThumb1, IsThumb2); 8683 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8684 IsThumb1, IsThumb2); 8685 srcIn = srcOut; 8686 destIn = destOut; 8687 } 8688 8689 // Handle the leftover bytes with LDRB and STRB. 8690 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8691 // [destOut] = STRB_POST(scratch, destIn, 1) 8692 for (unsigned i = 0; i < BytesLeft; i++) { 8693 unsigned srcOut = MRI.createVirtualRegister(TRC); 8694 unsigned destOut = MRI.createVirtualRegister(TRC); 8695 unsigned scratch = MRI.createVirtualRegister(TRC); 8696 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8697 IsThumb1, IsThumb2); 8698 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8699 IsThumb1, IsThumb2); 8700 srcIn = srcOut; 8701 destIn = destOut; 8702 } 8703 MI.eraseFromParent(); // The instruction is gone now. 8704 return BB; 8705 } 8706 8707 // Expand the pseudo op to a loop. 8708 // thisMBB: 8709 // ... 8710 // movw varEnd, # --> with thumb2 8711 // movt varEnd, # 8712 // ldrcp varEnd, idx --> without thumb2 8713 // fallthrough --> loopMBB 8714 // loopMBB: 8715 // PHI varPhi, varEnd, varLoop 8716 // PHI srcPhi, src, srcLoop 8717 // PHI destPhi, dst, destLoop 8718 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8719 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8720 // subs varLoop, varPhi, #UnitSize 8721 // bne loopMBB 8722 // fallthrough --> exitMBB 8723 // exitMBB: 8724 // epilogue to handle left-over bytes 8725 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8726 // [destOut] = STRB_POST(scratch, destLoop, 1) 8727 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8728 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8729 MF->insert(It, loopMBB); 8730 MF->insert(It, exitMBB); 8731 8732 // Transfer the remainder of BB and its successor edges to exitMBB. 8733 exitMBB->splice(exitMBB->begin(), BB, 8734 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8735 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8736 8737 // Load an immediate to varEnd. 8738 unsigned varEnd = MRI.createVirtualRegister(TRC); 8739 if (Subtarget->useMovt(*MF)) { 8740 unsigned Vtmp = varEnd; 8741 if ((LoopSize & 0xFFFF0000) != 0) 8742 Vtmp = MRI.createVirtualRegister(TRC); 8743 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 8744 .addImm(LoopSize & 0xFFFF) 8745 .add(predOps(ARMCC::AL)); 8746 8747 if ((LoopSize & 0xFFFF0000) != 0) 8748 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 8749 .addReg(Vtmp) 8750 .addImm(LoopSize >> 16) 8751 .add(predOps(ARMCC::AL)); 8752 } else { 8753 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8754 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8755 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 8756 8757 // MachineConstantPool wants an explicit alignment. 8758 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8759 if (Align == 0) 8760 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8761 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8762 8763 if (IsThumb) 8764 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 8765 .addReg(varEnd, RegState::Define) 8766 .addConstantPoolIndex(Idx) 8767 .add(predOps(ARMCC::AL)); 8768 else 8769 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 8770 .addReg(varEnd, RegState::Define) 8771 .addConstantPoolIndex(Idx) 8772 .addImm(0) 8773 .add(predOps(ARMCC::AL)); 8774 } 8775 BB->addSuccessor(loopMBB); 8776 8777 // Generate the loop body: 8778 // varPhi = PHI(varLoop, varEnd) 8779 // srcPhi = PHI(srcLoop, src) 8780 // destPhi = PHI(destLoop, dst) 8781 MachineBasicBlock *entryBB = BB; 8782 BB = loopMBB; 8783 unsigned varLoop = MRI.createVirtualRegister(TRC); 8784 unsigned varPhi = MRI.createVirtualRegister(TRC); 8785 unsigned srcLoop = MRI.createVirtualRegister(TRC); 8786 unsigned srcPhi = MRI.createVirtualRegister(TRC); 8787 unsigned destLoop = MRI.createVirtualRegister(TRC); 8788 unsigned destPhi = MRI.createVirtualRegister(TRC); 8789 8790 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 8791 .addReg(varLoop).addMBB(loopMBB) 8792 .addReg(varEnd).addMBB(entryBB); 8793 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 8794 .addReg(srcLoop).addMBB(loopMBB) 8795 .addReg(src).addMBB(entryBB); 8796 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 8797 .addReg(destLoop).addMBB(loopMBB) 8798 .addReg(dest).addMBB(entryBB); 8799 8800 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8801 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 8802 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8803 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 8804 IsThumb1, IsThumb2); 8805 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 8806 IsThumb1, IsThumb2); 8807 8808 // Decrement loop variable by UnitSize. 8809 if (IsThumb1) { 8810 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 8811 .add(t1CondCodeOp()) 8812 .addReg(varPhi) 8813 .addImm(UnitSize) 8814 .add(predOps(ARMCC::AL)); 8815 } else { 8816 MachineInstrBuilder MIB = 8817 BuildMI(*BB, BB->end(), dl, 8818 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 8819 MIB.addReg(varPhi) 8820 .addImm(UnitSize) 8821 .add(predOps(ARMCC::AL)) 8822 .add(condCodeOp()); 8823 MIB->getOperand(5).setReg(ARM::CPSR); 8824 MIB->getOperand(5).setIsDef(true); 8825 } 8826 BuildMI(*BB, BB->end(), dl, 8827 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 8828 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 8829 8830 // loopMBB can loop back to loopMBB or fall through to exitMBB. 8831 BB->addSuccessor(loopMBB); 8832 BB->addSuccessor(exitMBB); 8833 8834 // Add epilogue to handle BytesLeft. 8835 BB = exitMBB; 8836 auto StartOfExit = exitMBB->begin(); 8837 8838 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8839 // [destOut] = STRB_POST(scratch, destLoop, 1) 8840 unsigned srcIn = srcLoop; 8841 unsigned destIn = destLoop; 8842 for (unsigned i = 0; i < BytesLeft; i++) { 8843 unsigned srcOut = MRI.createVirtualRegister(TRC); 8844 unsigned destOut = MRI.createVirtualRegister(TRC); 8845 unsigned scratch = MRI.createVirtualRegister(TRC); 8846 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 8847 IsThumb1, IsThumb2); 8848 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 8849 IsThumb1, IsThumb2); 8850 srcIn = srcOut; 8851 destIn = destOut; 8852 } 8853 8854 MI.eraseFromParent(); // The instruction is gone now. 8855 return BB; 8856 } 8857 8858 MachineBasicBlock * 8859 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 8860 MachineBasicBlock *MBB) const { 8861 const TargetMachine &TM = getTargetMachine(); 8862 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 8863 DebugLoc DL = MI.getDebugLoc(); 8864 8865 assert(Subtarget->isTargetWindows() && 8866 "__chkstk is only supported on Windows"); 8867 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 8868 8869 // __chkstk takes the number of words to allocate on the stack in R4, and 8870 // returns the stack adjustment in number of bytes in R4. This will not 8871 // clober any other registers (other than the obvious lr). 8872 // 8873 // Although, technically, IP should be considered a register which may be 8874 // clobbered, the call itself will not touch it. Windows on ARM is a pure 8875 // thumb-2 environment, so there is no interworking required. As a result, we 8876 // do not expect a veneer to be emitted by the linker, clobbering IP. 8877 // 8878 // Each module receives its own copy of __chkstk, so no import thunk is 8879 // required, again, ensuring that IP is not clobbered. 8880 // 8881 // Finally, although some linkers may theoretically provide a trampoline for 8882 // out of range calls (which is quite common due to a 32M range limitation of 8883 // branches for Thumb), we can generate the long-call version via 8884 // -mcmodel=large, alleviating the need for the trampoline which may clobber 8885 // IP. 8886 8887 switch (TM.getCodeModel()) { 8888 case CodeModel::Small: 8889 case CodeModel::Medium: 8890 case CodeModel::Kernel: 8891 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 8892 .add(predOps(ARMCC::AL)) 8893 .addExternalSymbol("__chkstk") 8894 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8895 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8896 .addReg(ARM::R12, 8897 RegState::Implicit | RegState::Define | RegState::Dead) 8898 .addReg(ARM::CPSR, 8899 RegState::Implicit | RegState::Define | RegState::Dead); 8900 break; 8901 case CodeModel::Large: { 8902 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 8903 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 8904 8905 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 8906 .addExternalSymbol("__chkstk"); 8907 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 8908 .add(predOps(ARMCC::AL)) 8909 .addReg(Reg, RegState::Kill) 8910 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 8911 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 8912 .addReg(ARM::R12, 8913 RegState::Implicit | RegState::Define | RegState::Dead) 8914 .addReg(ARM::CPSR, 8915 RegState::Implicit | RegState::Define | RegState::Dead); 8916 break; 8917 } 8918 } 8919 8920 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 8921 .addReg(ARM::SP, RegState::Kill) 8922 .addReg(ARM::R4, RegState::Kill) 8923 .setMIFlags(MachineInstr::FrameSetup) 8924 .add(predOps(ARMCC::AL)) 8925 .add(condCodeOp()); 8926 8927 MI.eraseFromParent(); 8928 return MBB; 8929 } 8930 8931 MachineBasicBlock * 8932 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 8933 MachineBasicBlock *MBB) const { 8934 DebugLoc DL = MI.getDebugLoc(); 8935 MachineFunction *MF = MBB->getParent(); 8936 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8937 8938 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 8939 MF->insert(++MBB->getIterator(), ContBB); 8940 ContBB->splice(ContBB->begin(), MBB, 8941 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 8942 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 8943 MBB->addSuccessor(ContBB); 8944 8945 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8946 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 8947 MF->push_back(TrapBB); 8948 MBB->addSuccessor(TrapBB); 8949 8950 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 8951 .addReg(MI.getOperand(0).getReg()) 8952 .addImm(0) 8953 .add(predOps(ARMCC::AL)); 8954 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 8955 .addMBB(TrapBB) 8956 .addImm(ARMCC::EQ) 8957 .addReg(ARM::CPSR); 8958 8959 MI.eraseFromParent(); 8960 return ContBB; 8961 } 8962 8963 MachineBasicBlock * 8964 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 8965 MachineBasicBlock *BB) const { 8966 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8967 DebugLoc dl = MI.getDebugLoc(); 8968 bool isThumb2 = Subtarget->isThumb2(); 8969 switch (MI.getOpcode()) { 8970 default: { 8971 MI.print(errs()); 8972 llvm_unreachable("Unexpected instr type to insert"); 8973 } 8974 8975 // Thumb1 post-indexed loads are really just single-register LDMs. 8976 case ARM::tLDR_postidx: { 8977 MachineOperand Def(MI.getOperand(1)); 8978 if (TargetRegisterInfo::isPhysicalRegister(Def.getReg())) 8979 Def.setIsRenamable(false); 8980 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 8981 .add(Def) // Rn_wb 8982 .add(MI.getOperand(2)) // Rn 8983 .add(MI.getOperand(3)) // PredImm 8984 .add(MI.getOperand(4)) // PredReg 8985 .add(MI.getOperand(0)); // Rt 8986 MI.eraseFromParent(); 8987 return BB; 8988 } 8989 8990 // The Thumb2 pre-indexed stores have the same MI operands, they just 8991 // define them differently in the .td files from the isel patterns, so 8992 // they need pseudos. 8993 case ARM::t2STR_preidx: 8994 MI.setDesc(TII->get(ARM::t2STR_PRE)); 8995 return BB; 8996 case ARM::t2STRB_preidx: 8997 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 8998 return BB; 8999 case ARM::t2STRH_preidx: 9000 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9001 return BB; 9002 9003 case ARM::STRi_preidx: 9004 case ARM::STRBi_preidx: { 9005 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9006 : ARM::STRB_PRE_IMM; 9007 // Decode the offset. 9008 unsigned Offset = MI.getOperand(4).getImm(); 9009 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9010 Offset = ARM_AM::getAM2Offset(Offset); 9011 if (isSub) 9012 Offset = -Offset; 9013 9014 MachineMemOperand *MMO = *MI.memoperands_begin(); 9015 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9016 .add(MI.getOperand(0)) // Rn_wb 9017 .add(MI.getOperand(1)) // Rt 9018 .add(MI.getOperand(2)) // Rn 9019 .addImm(Offset) // offset (skip GPR==zero_reg) 9020 .add(MI.getOperand(5)) // pred 9021 .add(MI.getOperand(6)) 9022 .addMemOperand(MMO); 9023 MI.eraseFromParent(); 9024 return BB; 9025 } 9026 case ARM::STRr_preidx: 9027 case ARM::STRBr_preidx: 9028 case ARM::STRH_preidx: { 9029 unsigned NewOpc; 9030 switch (MI.getOpcode()) { 9031 default: llvm_unreachable("unexpected opcode!"); 9032 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9033 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9034 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9035 } 9036 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9037 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9038 MIB.add(MI.getOperand(i)); 9039 MI.eraseFromParent(); 9040 return BB; 9041 } 9042 9043 case ARM::tMOVCCr_pseudo: { 9044 // To "insert" a SELECT_CC instruction, we actually have to insert the 9045 // diamond control-flow pattern. The incoming instruction knows the 9046 // destination vreg to set, the condition code register to branch on, the 9047 // true/false values to select between, and a branch opcode to use. 9048 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9049 MachineFunction::iterator It = ++BB->getIterator(); 9050 9051 // thisMBB: 9052 // ... 9053 // TrueVal = ... 9054 // cmpTY ccX, r1, r2 9055 // bCC copy1MBB 9056 // fallthrough --> copy0MBB 9057 MachineBasicBlock *thisMBB = BB; 9058 MachineFunction *F = BB->getParent(); 9059 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9060 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9061 F->insert(It, copy0MBB); 9062 F->insert(It, sinkMBB); 9063 9064 // Transfer the remainder of BB and its successor edges to sinkMBB. 9065 sinkMBB->splice(sinkMBB->begin(), BB, 9066 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9067 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9068 9069 BB->addSuccessor(copy0MBB); 9070 BB->addSuccessor(sinkMBB); 9071 9072 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9073 .addMBB(sinkMBB) 9074 .addImm(MI.getOperand(3).getImm()) 9075 .addReg(MI.getOperand(4).getReg()); 9076 9077 // copy0MBB: 9078 // %FalseValue = ... 9079 // # fallthrough to sinkMBB 9080 BB = copy0MBB; 9081 9082 // Update machine-CFG edges 9083 BB->addSuccessor(sinkMBB); 9084 9085 // sinkMBB: 9086 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9087 // ... 9088 BB = sinkMBB; 9089 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9090 .addReg(MI.getOperand(1).getReg()) 9091 .addMBB(copy0MBB) 9092 .addReg(MI.getOperand(2).getReg()) 9093 .addMBB(thisMBB); 9094 9095 MI.eraseFromParent(); // The pseudo instruction is gone now. 9096 return BB; 9097 } 9098 9099 case ARM::BCCi64: 9100 case ARM::BCCZi64: { 9101 // If there is an unconditional branch to the other successor, remove it. 9102 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9103 9104 // Compare both parts that make up the double comparison separately for 9105 // equality. 9106 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9107 9108 unsigned LHS1 = MI.getOperand(1).getReg(); 9109 unsigned LHS2 = MI.getOperand(2).getReg(); 9110 if (RHSisZero) { 9111 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9112 .addReg(LHS1) 9113 .addImm(0) 9114 .add(predOps(ARMCC::AL)); 9115 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9116 .addReg(LHS2).addImm(0) 9117 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9118 } else { 9119 unsigned RHS1 = MI.getOperand(3).getReg(); 9120 unsigned RHS2 = MI.getOperand(4).getReg(); 9121 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9122 .addReg(LHS1) 9123 .addReg(RHS1) 9124 .add(predOps(ARMCC::AL)); 9125 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9126 .addReg(LHS2).addReg(RHS2) 9127 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9128 } 9129 9130 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9131 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9132 if (MI.getOperand(0).getImm() == ARMCC::NE) 9133 std::swap(destMBB, exitMBB); 9134 9135 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9136 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9137 if (isThumb2) 9138 BuildMI(BB, dl, TII->get(ARM::t2B)) 9139 .addMBB(exitMBB) 9140 .add(predOps(ARMCC::AL)); 9141 else 9142 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9143 9144 MI.eraseFromParent(); // The pseudo instruction is gone now. 9145 return BB; 9146 } 9147 9148 case ARM::Int_eh_sjlj_setjmp: 9149 case ARM::Int_eh_sjlj_setjmp_nofp: 9150 case ARM::tInt_eh_sjlj_setjmp: 9151 case ARM::t2Int_eh_sjlj_setjmp: 9152 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9153 return BB; 9154 9155 case ARM::Int_eh_sjlj_setup_dispatch: 9156 EmitSjLjDispatchBlock(MI, BB); 9157 return BB; 9158 9159 case ARM::ABS: 9160 case ARM::t2ABS: { 9161 // To insert an ABS instruction, we have to insert the 9162 // diamond control-flow pattern. The incoming instruction knows the 9163 // source vreg to test against 0, the destination vreg to set, 9164 // the condition code register to branch on, the 9165 // true/false values to select between, and a branch opcode to use. 9166 // It transforms 9167 // V1 = ABS V0 9168 // into 9169 // V2 = MOVS V0 9170 // BCC (branch to SinkBB if V0 >= 0) 9171 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9172 // SinkBB: V1 = PHI(V2, V3) 9173 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9174 MachineFunction::iterator BBI = ++BB->getIterator(); 9175 MachineFunction *Fn = BB->getParent(); 9176 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9177 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9178 Fn->insert(BBI, RSBBB); 9179 Fn->insert(BBI, SinkBB); 9180 9181 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9182 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9183 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9184 bool isThumb2 = Subtarget->isThumb2(); 9185 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9186 // In Thumb mode S must not be specified if source register is the SP or 9187 // PC and if destination register is the SP, so restrict register class 9188 unsigned NewRsbDstReg = 9189 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9190 9191 // Transfer the remainder of BB and its successor edges to sinkMBB. 9192 SinkBB->splice(SinkBB->begin(), BB, 9193 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9194 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9195 9196 BB->addSuccessor(RSBBB); 9197 BB->addSuccessor(SinkBB); 9198 9199 // fall through to SinkMBB 9200 RSBBB->addSuccessor(SinkBB); 9201 9202 // insert a cmp at the end of BB 9203 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9204 .addReg(ABSSrcReg) 9205 .addImm(0) 9206 .add(predOps(ARMCC::AL)); 9207 9208 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9209 BuildMI(BB, dl, 9210 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9211 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9212 9213 // insert rsbri in RSBBB 9214 // Note: BCC and rsbri will be converted into predicated rsbmi 9215 // by if-conversion pass 9216 BuildMI(*RSBBB, RSBBB->begin(), dl, 9217 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9218 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9219 .addImm(0) 9220 .add(predOps(ARMCC::AL)) 9221 .add(condCodeOp()); 9222 9223 // insert PHI in SinkBB, 9224 // reuse ABSDstReg to not change uses of ABS instruction 9225 BuildMI(*SinkBB, SinkBB->begin(), dl, 9226 TII->get(ARM::PHI), ABSDstReg) 9227 .addReg(NewRsbDstReg).addMBB(RSBBB) 9228 .addReg(ABSSrcReg).addMBB(BB); 9229 9230 // remove ABS instruction 9231 MI.eraseFromParent(); 9232 9233 // return last added BB 9234 return SinkBB; 9235 } 9236 case ARM::COPY_STRUCT_BYVAL_I32: 9237 ++NumLoopByVals; 9238 return EmitStructByval(MI, BB); 9239 case ARM::WIN__CHKSTK: 9240 return EmitLowered__chkstk(MI, BB); 9241 case ARM::WIN__DBZCHK: 9242 return EmitLowered__dbzchk(MI, BB); 9243 } 9244 } 9245 9246 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 9247 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9248 /// instead of as a custom inserter because we need the use list from the SDNode. 9249 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9250 MachineInstr &MI, const SDNode *Node) { 9251 bool isThumb1 = Subtarget->isThumb1Only(); 9252 9253 DebugLoc DL = MI.getDebugLoc(); 9254 MachineFunction *MF = MI.getParent()->getParent(); 9255 MachineRegisterInfo &MRI = MF->getRegInfo(); 9256 MachineInstrBuilder MIB(*MF, MI); 9257 9258 // If the new dst/src is unused mark it as dead. 9259 if (!Node->hasAnyUseOfValue(0)) { 9260 MI.getOperand(0).setIsDead(true); 9261 } 9262 if (!Node->hasAnyUseOfValue(1)) { 9263 MI.getOperand(1).setIsDead(true); 9264 } 9265 9266 // The MEMCPY both defines and kills the scratch registers. 9267 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9268 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9269 : &ARM::GPRRegClass); 9270 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9271 } 9272 } 9273 9274 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9275 SDNode *Node) const { 9276 if (MI.getOpcode() == ARM::MEMCPY) { 9277 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9278 return; 9279 } 9280 9281 const MCInstrDesc *MCID = &MI.getDesc(); 9282 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9283 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9284 // operand is still set to noreg. If needed, set the optional operand's 9285 // register to CPSR, and remove the redundant implicit def. 9286 // 9287 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 9288 9289 // Rename pseudo opcodes. 9290 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9291 unsigned ccOutIdx; 9292 if (NewOpc) { 9293 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9294 MCID = &TII->get(NewOpc); 9295 9296 assert(MCID->getNumOperands() == 9297 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9298 && "converted opcode should be the same except for cc_out" 9299 " (and, on Thumb1, pred)"); 9300 9301 MI.setDesc(*MCID); 9302 9303 // Add the optional cc_out operand 9304 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9305 9306 // On Thumb1, move all input operands to the end, then add the predicate 9307 if (Subtarget->isThumb1Only()) { 9308 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9309 MI.addOperand(MI.getOperand(1)); 9310 MI.RemoveOperand(1); 9311 } 9312 9313 // Restore the ties 9314 for (unsigned i = MI.getNumOperands(); i--;) { 9315 const MachineOperand& op = MI.getOperand(i); 9316 if (op.isReg() && op.isUse()) { 9317 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9318 if (DefIdx != -1) 9319 MI.tieOperands(DefIdx, i); 9320 } 9321 } 9322 9323 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9324 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9325 ccOutIdx = 1; 9326 } else 9327 ccOutIdx = MCID->getNumOperands() - 1; 9328 } else 9329 ccOutIdx = MCID->getNumOperands() - 1; 9330 9331 // Any ARM instruction that sets the 's' bit should specify an optional 9332 // "cc_out" operand in the last operand position. 9333 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9334 assert(!NewOpc && "Optional cc_out operand required"); 9335 return; 9336 } 9337 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9338 // since we already have an optional CPSR def. 9339 bool definesCPSR = false; 9340 bool deadCPSR = false; 9341 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9342 ++i) { 9343 const MachineOperand &MO = MI.getOperand(i); 9344 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9345 definesCPSR = true; 9346 if (MO.isDead()) 9347 deadCPSR = true; 9348 MI.RemoveOperand(i); 9349 break; 9350 } 9351 } 9352 if (!definesCPSR) { 9353 assert(!NewOpc && "Optional cc_out operand required"); 9354 return; 9355 } 9356 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9357 if (deadCPSR) { 9358 assert(!MI.getOperand(ccOutIdx).getReg() && 9359 "expect uninitialized optional cc_out operand"); 9360 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9361 if (!Subtarget->isThumb1Only()) 9362 return; 9363 } 9364 9365 // If this instruction was defined with an optional CPSR def and its dag node 9366 // had a live implicit CPSR def, then activate the optional CPSR def. 9367 MachineOperand &MO = MI.getOperand(ccOutIdx); 9368 MO.setReg(ARM::CPSR); 9369 MO.setIsDef(true); 9370 } 9371 9372 //===----------------------------------------------------------------------===// 9373 // ARM Optimization Hooks 9374 //===----------------------------------------------------------------------===// 9375 9376 // Helper function that checks if N is a null or all ones constant. 9377 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9378 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9379 } 9380 9381 // Return true if N is conditionally 0 or all ones. 9382 // Detects these expressions where cc is an i1 value: 9383 // 9384 // (select cc 0, y) [AllOnes=0] 9385 // (select cc y, 0) [AllOnes=0] 9386 // (zext cc) [AllOnes=0] 9387 // (sext cc) [AllOnes=0/1] 9388 // (select cc -1, y) [AllOnes=1] 9389 // (select cc y, -1) [AllOnes=1] 9390 // 9391 // Invert is set when N is the null/all ones constant when CC is false. 9392 // OtherOp is set to the alternative value of N. 9393 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9394 SDValue &CC, bool &Invert, 9395 SDValue &OtherOp, 9396 SelectionDAG &DAG) { 9397 switch (N->getOpcode()) { 9398 default: return false; 9399 case ISD::SELECT: { 9400 CC = N->getOperand(0); 9401 SDValue N1 = N->getOperand(1); 9402 SDValue N2 = N->getOperand(2); 9403 if (isZeroOrAllOnes(N1, AllOnes)) { 9404 Invert = false; 9405 OtherOp = N2; 9406 return true; 9407 } 9408 if (isZeroOrAllOnes(N2, AllOnes)) { 9409 Invert = true; 9410 OtherOp = N1; 9411 return true; 9412 } 9413 return false; 9414 } 9415 case ISD::ZERO_EXTEND: 9416 // (zext cc) can never be the all ones value. 9417 if (AllOnes) 9418 return false; 9419 LLVM_FALLTHROUGH; 9420 case ISD::SIGN_EXTEND: { 9421 SDLoc dl(N); 9422 EVT VT = N->getValueType(0); 9423 CC = N->getOperand(0); 9424 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9425 return false; 9426 Invert = !AllOnes; 9427 if (AllOnes) 9428 // When looking for an AllOnes constant, N is an sext, and the 'other' 9429 // value is 0. 9430 OtherOp = DAG.getConstant(0, dl, VT); 9431 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9432 // When looking for a 0 constant, N can be zext or sext. 9433 OtherOp = DAG.getConstant(1, dl, VT); 9434 else 9435 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9436 VT); 9437 return true; 9438 } 9439 } 9440 } 9441 9442 // Combine a constant select operand into its use: 9443 // 9444 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9445 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9446 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9447 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9448 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9449 // 9450 // The transform is rejected if the select doesn't have a constant operand that 9451 // is null, or all ones when AllOnes is set. 9452 // 9453 // Also recognize sext/zext from i1: 9454 // 9455 // (add (zext cc), x) -> (select cc (add x, 1), x) 9456 // (add (sext cc), x) -> (select cc (add x, -1), x) 9457 // 9458 // These transformations eventually create predicated instructions. 9459 // 9460 // @param N The node to transform. 9461 // @param Slct The N operand that is a select. 9462 // @param OtherOp The other N operand (x above). 9463 // @param DCI Context. 9464 // @param AllOnes Require the select constant to be all ones instead of null. 9465 // @returns The new node, or SDValue() on failure. 9466 static 9467 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9468 TargetLowering::DAGCombinerInfo &DCI, 9469 bool AllOnes = false) { 9470 SelectionDAG &DAG = DCI.DAG; 9471 EVT VT = N->getValueType(0); 9472 SDValue NonConstantVal; 9473 SDValue CCOp; 9474 bool SwapSelectOps; 9475 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9476 NonConstantVal, DAG)) 9477 return SDValue(); 9478 9479 // Slct is now know to be the desired identity constant when CC is true. 9480 SDValue TrueVal = OtherOp; 9481 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9482 OtherOp, NonConstantVal); 9483 // Unless SwapSelectOps says CC should be false. 9484 if (SwapSelectOps) 9485 std::swap(TrueVal, FalseVal); 9486 9487 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9488 CCOp, TrueVal, FalseVal); 9489 } 9490 9491 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9492 static 9493 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9494 TargetLowering::DAGCombinerInfo &DCI) { 9495 SDValue N0 = N->getOperand(0); 9496 SDValue N1 = N->getOperand(1); 9497 if (N0.getNode()->hasOneUse()) 9498 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9499 return Result; 9500 if (N1.getNode()->hasOneUse()) 9501 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9502 return Result; 9503 return SDValue(); 9504 } 9505 9506 static bool IsVUZPShuffleNode(SDNode *N) { 9507 // VUZP shuffle node. 9508 if (N->getOpcode() == ARMISD::VUZP) 9509 return true; 9510 9511 // "VUZP" on i32 is an alias for VTRN. 9512 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9513 return true; 9514 9515 return false; 9516 } 9517 9518 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9519 TargetLowering::DAGCombinerInfo &DCI, 9520 const ARMSubtarget *Subtarget) { 9521 // Look for ADD(VUZP.0, VUZP.1). 9522 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9523 N0 == N1) 9524 return SDValue(); 9525 9526 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9527 if (!N->getValueType(0).is64BitVector()) 9528 return SDValue(); 9529 9530 // Generate vpadd. 9531 SelectionDAG &DAG = DCI.DAG; 9532 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9533 SDLoc dl(N); 9534 SDNode *Unzip = N0.getNode(); 9535 EVT VT = N->getValueType(0); 9536 9537 SmallVector<SDValue, 8> Ops; 9538 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9539 TLI.getPointerTy(DAG.getDataLayout()))); 9540 Ops.push_back(Unzip->getOperand(0)); 9541 Ops.push_back(Unzip->getOperand(1)); 9542 9543 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9544 } 9545 9546 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9547 TargetLowering::DAGCombinerInfo &DCI, 9548 const ARMSubtarget *Subtarget) { 9549 // Check for two extended operands. 9550 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9551 N1.getOpcode() == ISD::SIGN_EXTEND) && 9552 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9553 N1.getOpcode() == ISD::ZERO_EXTEND)) 9554 return SDValue(); 9555 9556 SDValue N00 = N0.getOperand(0); 9557 SDValue N10 = N1.getOperand(0); 9558 9559 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9560 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9561 N00 == N10) 9562 return SDValue(); 9563 9564 // We only recognize Q register paddl here; this can't be reached until 9565 // after type legalization. 9566 if (!N00.getValueType().is64BitVector() || 9567 !N0.getValueType().is128BitVector()) 9568 return SDValue(); 9569 9570 // Generate vpaddl. 9571 SelectionDAG &DAG = DCI.DAG; 9572 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9573 SDLoc dl(N); 9574 EVT VT = N->getValueType(0); 9575 9576 SmallVector<SDValue, 8> Ops; 9577 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9578 unsigned Opcode; 9579 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9580 Opcode = Intrinsic::arm_neon_vpaddls; 9581 else 9582 Opcode = Intrinsic::arm_neon_vpaddlu; 9583 Ops.push_back(DAG.getConstant(Opcode, dl, 9584 TLI.getPointerTy(DAG.getDataLayout()))); 9585 EVT ElemTy = N00.getValueType().getVectorElementType(); 9586 unsigned NumElts = VT.getVectorNumElements(); 9587 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9588 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9589 N00.getOperand(0), N00.getOperand(1)); 9590 Ops.push_back(Concat); 9591 9592 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9593 } 9594 9595 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9596 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9597 // much easier to match. 9598 static SDValue 9599 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9600 TargetLowering::DAGCombinerInfo &DCI, 9601 const ARMSubtarget *Subtarget) { 9602 // Only perform optimization if after legalize, and if NEON is available. We 9603 // also expected both operands to be BUILD_VECTORs. 9604 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9605 || N0.getOpcode() != ISD::BUILD_VECTOR 9606 || N1.getOpcode() != ISD::BUILD_VECTOR) 9607 return SDValue(); 9608 9609 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9610 EVT VT = N->getValueType(0); 9611 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9612 return SDValue(); 9613 9614 // Check that the vector operands are of the right form. 9615 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9616 // operands, where N is the size of the formed vector. 9617 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9618 // index such that we have a pair wise add pattern. 9619 9620 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9621 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9622 return SDValue(); 9623 SDValue Vec = N0->getOperand(0)->getOperand(0); 9624 SDNode *V = Vec.getNode(); 9625 unsigned nextIndex = 0; 9626 9627 // For each operands to the ADD which are BUILD_VECTORs, 9628 // check to see if each of their operands are an EXTRACT_VECTOR with 9629 // the same vector and appropriate index. 9630 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9631 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9632 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9633 9634 SDValue ExtVec0 = N0->getOperand(i); 9635 SDValue ExtVec1 = N1->getOperand(i); 9636 9637 // First operand is the vector, verify its the same. 9638 if (V != ExtVec0->getOperand(0).getNode() || 9639 V != ExtVec1->getOperand(0).getNode()) 9640 return SDValue(); 9641 9642 // Second is the constant, verify its correct. 9643 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9644 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9645 9646 // For the constant, we want to see all the even or all the odd. 9647 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9648 || C1->getZExtValue() != nextIndex+1) 9649 return SDValue(); 9650 9651 // Increment index. 9652 nextIndex+=2; 9653 } else 9654 return SDValue(); 9655 } 9656 9657 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 9658 // we're using the entire input vector, otherwise there's a size/legality 9659 // mismatch somewhere. 9660 if (nextIndex != Vec.getValueType().getVectorNumElements() || 9661 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9662 return SDValue(); 9663 9664 // Create VPADDL node. 9665 SelectionDAG &DAG = DCI.DAG; 9666 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9667 9668 SDLoc dl(N); 9669 9670 // Build operand list. 9671 SmallVector<SDValue, 8> Ops; 9672 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9673 TLI.getPointerTy(DAG.getDataLayout()))); 9674 9675 // Input is the vector. 9676 Ops.push_back(Vec); 9677 9678 // Get widened type and narrowed type. 9679 MVT widenType; 9680 unsigned numElem = VT.getVectorNumElements(); 9681 9682 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9683 switch (inputLaneType.getSimpleVT().SimpleTy) { 9684 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9685 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9686 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9687 default: 9688 llvm_unreachable("Invalid vector element type for padd optimization."); 9689 } 9690 9691 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9692 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9693 return DAG.getNode(ExtOp, dl, VT, tmp); 9694 } 9695 9696 static SDValue findMUL_LOHI(SDValue V) { 9697 if (V->getOpcode() == ISD::UMUL_LOHI || 9698 V->getOpcode() == ISD::SMUL_LOHI) 9699 return V; 9700 return SDValue(); 9701 } 9702 9703 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 9704 TargetLowering::DAGCombinerInfo &DCI, 9705 const ARMSubtarget *Subtarget) { 9706 if (Subtarget->isThumb()) { 9707 if (!Subtarget->hasDSP()) 9708 return SDValue(); 9709 } else if (!Subtarget->hasV5TEOps()) 9710 return SDValue(); 9711 9712 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 9713 // accumulates the product into a 64-bit value. The 16-bit values will 9714 // be sign extended somehow or SRA'd into 32-bit values 9715 // (addc (adde (mul 16bit, 16bit), lo), hi) 9716 SDValue Mul = AddcNode->getOperand(0); 9717 SDValue Lo = AddcNode->getOperand(1); 9718 if (Mul.getOpcode() != ISD::MUL) { 9719 Lo = AddcNode->getOperand(0); 9720 Mul = AddcNode->getOperand(1); 9721 if (Mul.getOpcode() != ISD::MUL) 9722 return SDValue(); 9723 } 9724 9725 SDValue SRA = AddeNode->getOperand(0); 9726 SDValue Hi = AddeNode->getOperand(1); 9727 if (SRA.getOpcode() != ISD::SRA) { 9728 SRA = AddeNode->getOperand(1); 9729 Hi = AddeNode->getOperand(0); 9730 if (SRA.getOpcode() != ISD::SRA) 9731 return SDValue(); 9732 } 9733 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 9734 if (Const->getZExtValue() != 31) 9735 return SDValue(); 9736 } else 9737 return SDValue(); 9738 9739 if (SRA.getOperand(0) != Mul) 9740 return SDValue(); 9741 9742 SelectionDAG &DAG = DCI.DAG; 9743 SDLoc dl(AddcNode); 9744 unsigned Opcode = 0; 9745 SDValue Op0; 9746 SDValue Op1; 9747 9748 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 9749 Opcode = ARMISD::SMLALBB; 9750 Op0 = Mul.getOperand(0); 9751 Op1 = Mul.getOperand(1); 9752 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 9753 Opcode = ARMISD::SMLALBT; 9754 Op0 = Mul.getOperand(0); 9755 Op1 = Mul.getOperand(1).getOperand(0); 9756 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 9757 Opcode = ARMISD::SMLALTB; 9758 Op0 = Mul.getOperand(0).getOperand(0); 9759 Op1 = Mul.getOperand(1); 9760 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 9761 Opcode = ARMISD::SMLALTT; 9762 Op0 = Mul->getOperand(0).getOperand(0); 9763 Op1 = Mul->getOperand(1).getOperand(0); 9764 } 9765 9766 if (!Op0 || !Op1) 9767 return SDValue(); 9768 9769 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 9770 Op0, Op1, Lo, Hi); 9771 // Replace the ADDs' nodes uses by the MLA node's values. 9772 SDValue HiMLALResult(SMLAL.getNode(), 1); 9773 SDValue LoMLALResult(SMLAL.getNode(), 0); 9774 9775 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9776 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9777 9778 // Return original node to notify the driver to stop replacing. 9779 SDValue resNode(AddcNode, 0); 9780 return resNode; 9781 } 9782 9783 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode, 9784 TargetLowering::DAGCombinerInfo &DCI, 9785 const ARMSubtarget *Subtarget) { 9786 // Look for multiply add opportunities. 9787 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 9788 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 9789 // a glue link from the first add to the second add. 9790 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 9791 // a S/UMLAL instruction. 9792 // UMUL_LOHI 9793 // / :lo \ :hi 9794 // V \ [no multiline comment] 9795 // loAdd -> ADDC | 9796 // \ :carry / 9797 // V V 9798 // ADDE <- hiAdd 9799 // 9800 assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE"); 9801 9802 assert(AddeNode->getNumOperands() == 3 && 9803 AddeNode->getOperand(2).getValueType() == MVT::i32 && 9804 "ADDE node has the wrong inputs"); 9805 9806 // Check that we are chained to the right ADDC node. 9807 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 9808 if (AddcNode->getOpcode() != ARMISD::ADDC) 9809 return SDValue(); 9810 9811 SDValue AddcOp0 = AddcNode->getOperand(0); 9812 SDValue AddcOp1 = AddcNode->getOperand(1); 9813 9814 // Check if the two operands are from the same mul_lohi node. 9815 if (AddcOp0.getNode() == AddcOp1.getNode()) 9816 return SDValue(); 9817 9818 assert(AddcNode->getNumValues() == 2 && 9819 AddcNode->getValueType(0) == MVT::i32 && 9820 "Expect ADDC with two result values. First: i32"); 9821 9822 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 9823 // maybe a SMLAL which multiplies two 16-bit values. 9824 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 9825 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 9826 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 9827 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 9828 return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget); 9829 9830 // Check for the triangle shape. 9831 SDValue AddeOp0 = AddeNode->getOperand(0); 9832 SDValue AddeOp1 = AddeNode->getOperand(1); 9833 9834 // Make sure that the ADDE operands are not coming from the same node. 9835 if (AddeOp0.getNode() == AddeOp1.getNode()) 9836 return SDValue(); 9837 9838 // Find the MUL_LOHI node walking up ADDE's operands. 9839 bool IsLeftOperandMUL = false; 9840 SDValue MULOp = findMUL_LOHI(AddeOp0); 9841 if (MULOp == SDValue()) 9842 MULOp = findMUL_LOHI(AddeOp1); 9843 else 9844 IsLeftOperandMUL = true; 9845 if (MULOp == SDValue()) 9846 return SDValue(); 9847 9848 // Figure out the right opcode. 9849 unsigned Opc = MULOp->getOpcode(); 9850 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 9851 9852 // Figure out the high and low input values to the MLAL node. 9853 SDValue* HiAdd = nullptr; 9854 SDValue* LoMul = nullptr; 9855 SDValue* LowAdd = nullptr; 9856 9857 // Ensure that ADDE is from high result of ISD::xMUL_LOHI. 9858 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1))) 9859 return SDValue(); 9860 9861 if (IsLeftOperandMUL) 9862 HiAdd = &AddeOp1; 9863 else 9864 HiAdd = &AddeOp0; 9865 9866 9867 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node 9868 // whose low result is fed to the ADDC we are checking. 9869 9870 if (AddcOp0 == MULOp.getValue(0)) { 9871 LoMul = &AddcOp0; 9872 LowAdd = &AddcOp1; 9873 } 9874 if (AddcOp1 == MULOp.getValue(0)) { 9875 LoMul = &AddcOp1; 9876 LowAdd = &AddcOp0; 9877 } 9878 9879 if (!LoMul) 9880 return SDValue(); 9881 9882 // If HiAdd is the same node as ADDC or is a predecessor of ADDC the 9883 // replacement below will create a cycle. 9884 if (AddcNode == HiAdd->getNode() || 9885 AddcNode->isPredecessorOf(HiAdd->getNode())) 9886 return SDValue(); 9887 9888 // Create the merged node. 9889 SelectionDAG &DAG = DCI.DAG; 9890 9891 // Build operand list. 9892 SmallVector<SDValue, 8> Ops; 9893 Ops.push_back(LoMul->getOperand(0)); 9894 Ops.push_back(LoMul->getOperand(1)); 9895 Ops.push_back(*LowAdd); 9896 Ops.push_back(*HiAdd); 9897 9898 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 9899 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9900 9901 // Replace the ADDs' nodes uses by the MLA node's values. 9902 SDValue HiMLALResult(MLALNode.getNode(), 1); 9903 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 9904 9905 SDValue LoMLALResult(MLALNode.getNode(), 0); 9906 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 9907 9908 // Return original node to notify the driver to stop replacing. 9909 return SDValue(AddeNode, 0); 9910 } 9911 9912 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 9913 TargetLowering::DAGCombinerInfo &DCI, 9914 const ARMSubtarget *Subtarget) { 9915 // UMAAL is similar to UMLAL except that it adds two unsigned values. 9916 // While trying to combine for the other MLAL nodes, first search for the 9917 // chance to use UMAAL. Check if Addc uses a node which has already 9918 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 9919 // as the addend, and it's handled in PerformUMLALCombine. 9920 9921 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 9922 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 9923 9924 // Check that we have a glued ADDC node. 9925 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 9926 if (AddcNode->getOpcode() != ARMISD::ADDC) 9927 return SDValue(); 9928 9929 // Find the converted UMAAL or quit if it doesn't exist. 9930 SDNode *UmlalNode = nullptr; 9931 SDValue AddHi; 9932 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 9933 UmlalNode = AddcNode->getOperand(0).getNode(); 9934 AddHi = AddcNode->getOperand(1); 9935 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 9936 UmlalNode = AddcNode->getOperand(1).getNode(); 9937 AddHi = AddcNode->getOperand(0); 9938 } else { 9939 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 9940 } 9941 9942 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 9943 // the ADDC as well as Zero. 9944 if (!isNullConstant(UmlalNode->getOperand(3))) 9945 return SDValue(); 9946 9947 if ((isNullConstant(AddeNode->getOperand(0)) && 9948 AddeNode->getOperand(1).getNode() == UmlalNode) || 9949 (AddeNode->getOperand(0).getNode() == UmlalNode && 9950 isNullConstant(AddeNode->getOperand(1)))) { 9951 SelectionDAG &DAG = DCI.DAG; 9952 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 9953 UmlalNode->getOperand(2), AddHi }; 9954 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 9955 DAG.getVTList(MVT::i32, MVT::i32), Ops); 9956 9957 // Replace the ADDs' nodes uses by the UMAAL node's values. 9958 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 9959 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 9960 9961 // Return original node to notify the driver to stop replacing. 9962 return SDValue(AddeNode, 0); 9963 } 9964 return SDValue(); 9965 } 9966 9967 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 9968 const ARMSubtarget *Subtarget) { 9969 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 9970 return SDValue(); 9971 9972 // Check that we have a pair of ADDC and ADDE as operands. 9973 // Both addends of the ADDE must be zero. 9974 SDNode* AddcNode = N->getOperand(2).getNode(); 9975 SDNode* AddeNode = N->getOperand(3).getNode(); 9976 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 9977 (AddeNode->getOpcode() == ARMISD::ADDE) && 9978 isNullConstant(AddeNode->getOperand(0)) && 9979 isNullConstant(AddeNode->getOperand(1)) && 9980 (AddeNode->getOperand(2).getNode() == AddcNode)) 9981 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 9982 DAG.getVTList(MVT::i32, MVT::i32), 9983 {N->getOperand(0), N->getOperand(1), 9984 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 9985 else 9986 return SDValue(); 9987 } 9988 9989 static SDValue PerformAddcSubcCombine(SDNode *N, 9990 TargetLowering::DAGCombinerInfo &DCI, 9991 const ARMSubtarget *Subtarget) { 9992 SelectionDAG &DAG(DCI.DAG); 9993 9994 if (N->getOpcode() == ARMISD::ADDC) { 9995 // (ADDC (ADDE 0, 0, C), -1) -> C 9996 SDValue LHS = N->getOperand(0); 9997 SDValue RHS = N->getOperand(1); 9998 if (LHS->getOpcode() == ARMISD::ADDE && 9999 isNullConstant(LHS->getOperand(0)) && 10000 isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) { 10001 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10002 } 10003 } 10004 10005 if (Subtarget->isThumb1Only()) { 10006 SDValue RHS = N->getOperand(1); 10007 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10008 int32_t imm = C->getSExtValue(); 10009 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10010 SDLoc DL(N); 10011 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10012 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10013 : ARMISD::ADDC; 10014 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10015 } 10016 } 10017 } 10018 return SDValue(); 10019 } 10020 10021 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG, 10022 const ARMSubtarget *Subtarget) { 10023 if (Subtarget->isThumb1Only()) { 10024 SDValue RHS = N->getOperand(1); 10025 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10026 int64_t imm = C->getSExtValue(); 10027 if (imm < 0) { 10028 SDLoc DL(N); 10029 10030 // The with-carry-in form matches bitwise not instead of the negation. 10031 // Effectively, the inverse interpretation of the carry flag already 10032 // accounts for part of the negation. 10033 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10034 10035 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10036 : ARMISD::ADDE; 10037 return DAG.getNode(Opcode, DL, N->getVTList(), 10038 N->getOperand(0), RHS, N->getOperand(2)); 10039 } 10040 } 10041 } 10042 return SDValue(); 10043 } 10044 10045 /// PerformADDECombine - Target-specific dag combine transform from 10046 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10047 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10048 static SDValue PerformADDECombine(SDNode *N, 10049 TargetLowering::DAGCombinerInfo &DCI, 10050 const ARMSubtarget *Subtarget) { 10051 // Only ARM and Thumb2 support UMLAL/SMLAL. 10052 if (Subtarget->isThumb1Only()) 10053 return PerformAddeSubeCombine(N, DCI.DAG, Subtarget); 10054 10055 // Only perform the checks after legalize when the pattern is available. 10056 if (DCI.isBeforeLegalize()) return SDValue(); 10057 10058 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10059 } 10060 10061 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10062 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10063 /// called with the default operands, and if that fails, with commuted 10064 /// operands. 10065 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10066 TargetLowering::DAGCombinerInfo &DCI, 10067 const ARMSubtarget *Subtarget){ 10068 // Attempt to create vpadd for this add. 10069 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10070 return Result; 10071 10072 // Attempt to create vpaddl for this add. 10073 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10074 return Result; 10075 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10076 Subtarget)) 10077 return Result; 10078 10079 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10080 if (N0.getNode()->hasOneUse()) 10081 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10082 return Result; 10083 return SDValue(); 10084 } 10085 10086 static SDValue PerformSHLSimplify(SDNode *N, 10087 TargetLowering::DAGCombinerInfo &DCI, 10088 const ARMSubtarget *ST) { 10089 // Allow the generic combiner to identify potential bswaps. 10090 if (DCI.isBeforeLegalize()) 10091 return SDValue(); 10092 10093 // DAG combiner will fold: 10094 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10095 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 10096 // Other code patterns that can be also be modified have the following form: 10097 // b + ((a << 1) | 510) 10098 // b + ((a << 1) & 510) 10099 // b + ((a << 1) ^ 510) 10100 // b + ((a << 1) + 510) 10101 10102 // Many instructions can perform the shift for free, but it requires both 10103 // the operands to be registers. If c1 << c2 is too large, a mov immediate 10104 // instruction will needed. So, unfold back to the original pattern if: 10105 // - if c1 and c2 are small enough that they don't require mov imms. 10106 // - the user(s) of the node can perform an shl 10107 10108 // No shifted operands for 16-bit instructions. 10109 if (ST->isThumb() && ST->isThumb1Only()) 10110 return SDValue(); 10111 10112 // Check that all the users could perform the shl themselves. 10113 for (auto U : N->uses()) { 10114 switch(U->getOpcode()) { 10115 default: 10116 return SDValue(); 10117 case ISD::SUB: 10118 case ISD::ADD: 10119 case ISD::AND: 10120 case ISD::OR: 10121 case ISD::XOR: 10122 case ISD::SETCC: 10123 case ARMISD::CMP: 10124 // Check that its not already using a shl. 10125 if (U->getOperand(0).getOpcode() == ISD::SHL || 10126 U->getOperand(1).getOpcode() == ISD::SHL) 10127 return SDValue(); 10128 break; 10129 } 10130 } 10131 10132 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 10133 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 10134 return SDValue(); 10135 10136 if (N->getOperand(0).getOpcode() != ISD::SHL) 10137 return SDValue(); 10138 10139 SDValue SHL = N->getOperand(0); 10140 10141 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10142 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 10143 if (!C1ShlC2 || !C2) 10144 return SDValue(); 10145 10146 DEBUG(dbgs() << "Trying to simplify shl: "; N->dump()); 10147 10148 APInt C2Int = C2->getAPIntValue(); 10149 APInt C1Int = C1ShlC2->getAPIntValue(); 10150 10151 // Check that performing a lshr will not lose any information. 10152 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 10153 C2Int.getBitWidth() - C2->getZExtValue()); 10154 if ((C1Int & Mask) != C1Int) 10155 return SDValue(); 10156 10157 // Shift the first constant. 10158 C1Int.lshrInPlace(C2Int); 10159 10160 // The immediates are encoded as an 8-bit value that can be rotated. 10161 unsigned Zeros = C1Int.countLeadingZeros() + C1Int.countTrailingZeros(); 10162 if (C1Int.getBitWidth() - Zeros > 8) 10163 return SDValue(); 10164 10165 Zeros = C2Int.countLeadingZeros() + C2Int.countTrailingZeros(); 10166 if (C2Int.getBitWidth() - Zeros > 8) 10167 return SDValue(); 10168 10169 SelectionDAG &DAG = DCI.DAG; 10170 SDLoc dl(N); 10171 SDValue X = SHL.getOperand(0); 10172 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 10173 DAG.getConstant(C1Int, dl, MVT::i32)); 10174 // Shift left to compensate for the lshr of C1Int. 10175 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 10176 10177 DAG.ReplaceAllUsesWith(SDValue(N, 0), Res); 10178 return SDValue(N, 0); 10179 } 10180 10181 10182 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10183 /// 10184 static SDValue PerformADDCombine(SDNode *N, 10185 TargetLowering::DAGCombinerInfo &DCI, 10186 const ARMSubtarget *Subtarget) { 10187 SDValue N0 = N->getOperand(0); 10188 SDValue N1 = N->getOperand(1); 10189 10190 // Only works one way, because it needs an immediate operand. 10191 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10192 return Result; 10193 10194 // First try with the default operand order. 10195 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10196 return Result; 10197 10198 // If that didn't work, try again with the operands commuted. 10199 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10200 } 10201 10202 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 10203 /// 10204 static SDValue PerformSUBCombine(SDNode *N, 10205 TargetLowering::DAGCombinerInfo &DCI) { 10206 SDValue N0 = N->getOperand(0); 10207 SDValue N1 = N->getOperand(1); 10208 10209 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10210 if (N1.getNode()->hasOneUse()) 10211 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 10212 return Result; 10213 10214 return SDValue(); 10215 } 10216 10217 /// PerformVMULCombine 10218 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 10219 /// special multiplier accumulator forwarding. 10220 /// vmul d3, d0, d2 10221 /// vmla d3, d1, d2 10222 /// is faster than 10223 /// vadd d3, d0, d1 10224 /// vmul d3, d3, d2 10225 // However, for (A + B) * (A + B), 10226 // vadd d2, d0, d1 10227 // vmul d3, d0, d2 10228 // vmla d3, d1, d2 10229 // is slower than 10230 // vadd d2, d0, d1 10231 // vmul d3, d2, d2 10232 static SDValue PerformVMULCombine(SDNode *N, 10233 TargetLowering::DAGCombinerInfo &DCI, 10234 const ARMSubtarget *Subtarget) { 10235 if (!Subtarget->hasVMLxForwarding()) 10236 return SDValue(); 10237 10238 SelectionDAG &DAG = DCI.DAG; 10239 SDValue N0 = N->getOperand(0); 10240 SDValue N1 = N->getOperand(1); 10241 unsigned Opcode = N0.getOpcode(); 10242 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10243 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10244 Opcode = N1.getOpcode(); 10245 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10246 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10247 return SDValue(); 10248 std::swap(N0, N1); 10249 } 10250 10251 if (N0 == N1) 10252 return SDValue(); 10253 10254 EVT VT = N->getValueType(0); 10255 SDLoc DL(N); 10256 SDValue N00 = N0->getOperand(0); 10257 SDValue N01 = N0->getOperand(1); 10258 return DAG.getNode(Opcode, DL, VT, 10259 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10260 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10261 } 10262 10263 static SDValue PerformMULCombine(SDNode *N, 10264 TargetLowering::DAGCombinerInfo &DCI, 10265 const ARMSubtarget *Subtarget) { 10266 SelectionDAG &DAG = DCI.DAG; 10267 10268 if (Subtarget->isThumb1Only()) 10269 return SDValue(); 10270 10271 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10272 return SDValue(); 10273 10274 EVT VT = N->getValueType(0); 10275 if (VT.is64BitVector() || VT.is128BitVector()) 10276 return PerformVMULCombine(N, DCI, Subtarget); 10277 if (VT != MVT::i32) 10278 return SDValue(); 10279 10280 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10281 if (!C) 10282 return SDValue(); 10283 10284 int64_t MulAmt = C->getSExtValue(); 10285 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10286 10287 ShiftAmt = ShiftAmt & (32 - 1); 10288 SDValue V = N->getOperand(0); 10289 SDLoc DL(N); 10290 10291 SDValue Res; 10292 MulAmt >>= ShiftAmt; 10293 10294 if (MulAmt >= 0) { 10295 if (isPowerOf2_32(MulAmt - 1)) { 10296 // (mul x, 2^N + 1) => (add (shl x, N), x) 10297 Res = DAG.getNode(ISD::ADD, DL, VT, 10298 V, 10299 DAG.getNode(ISD::SHL, DL, VT, 10300 V, 10301 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10302 MVT::i32))); 10303 } else if (isPowerOf2_32(MulAmt + 1)) { 10304 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10305 Res = DAG.getNode(ISD::SUB, DL, VT, 10306 DAG.getNode(ISD::SHL, DL, VT, 10307 V, 10308 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10309 MVT::i32)), 10310 V); 10311 } else 10312 return SDValue(); 10313 } else { 10314 uint64_t MulAmtAbs = -MulAmt; 10315 if (isPowerOf2_32(MulAmtAbs + 1)) { 10316 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10317 Res = DAG.getNode(ISD::SUB, DL, VT, 10318 V, 10319 DAG.getNode(ISD::SHL, DL, VT, 10320 V, 10321 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10322 MVT::i32))); 10323 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10324 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10325 Res = DAG.getNode(ISD::ADD, DL, VT, 10326 V, 10327 DAG.getNode(ISD::SHL, DL, VT, 10328 V, 10329 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10330 MVT::i32))); 10331 Res = DAG.getNode(ISD::SUB, DL, VT, 10332 DAG.getConstant(0, DL, MVT::i32), Res); 10333 } else 10334 return SDValue(); 10335 } 10336 10337 if (ShiftAmt != 0) 10338 Res = DAG.getNode(ISD::SHL, DL, VT, 10339 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10340 10341 // Do not add new nodes to DAG combiner worklist. 10342 DCI.CombineTo(N, Res, false); 10343 return SDValue(); 10344 } 10345 10346 static SDValue PerformANDCombine(SDNode *N, 10347 TargetLowering::DAGCombinerInfo &DCI, 10348 const ARMSubtarget *Subtarget) { 10349 // Attempt to use immediate-form VBIC 10350 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10351 SDLoc dl(N); 10352 EVT VT = N->getValueType(0); 10353 SelectionDAG &DAG = DCI.DAG; 10354 10355 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10356 return SDValue(); 10357 10358 APInt SplatBits, SplatUndef; 10359 unsigned SplatBitSize; 10360 bool HasAnyUndefs; 10361 if (BVN && 10362 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10363 if (SplatBitSize <= 64) { 10364 EVT VbicVT; 10365 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10366 SplatUndef.getZExtValue(), SplatBitSize, 10367 DAG, dl, VbicVT, VT.is128BitVector(), 10368 OtherModImm); 10369 if (Val.getNode()) { 10370 SDValue Input = 10371 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10372 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10373 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10374 } 10375 } 10376 } 10377 10378 if (!Subtarget->isThumb1Only()) { 10379 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10380 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10381 return Result; 10382 10383 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10384 return Result; 10385 } 10386 10387 return SDValue(); 10388 } 10389 10390 // Try combining OR nodes to SMULWB, SMULWT. 10391 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10392 TargetLowering::DAGCombinerInfo &DCI, 10393 const ARMSubtarget *Subtarget) { 10394 if (!Subtarget->hasV6Ops() || 10395 (Subtarget->isThumb() && 10396 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10397 return SDValue(); 10398 10399 SDValue SRL = OR->getOperand(0); 10400 SDValue SHL = OR->getOperand(1); 10401 10402 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10403 SRL = OR->getOperand(1); 10404 SHL = OR->getOperand(0); 10405 } 10406 if (!isSRL16(SRL) || !isSHL16(SHL)) 10407 return SDValue(); 10408 10409 // The first operands to the shifts need to be the two results from the 10410 // same smul_lohi node. 10411 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10412 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10413 return SDValue(); 10414 10415 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10416 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10417 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10418 return SDValue(); 10419 10420 // Now we have: 10421 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10422 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10423 // For SMUWB the 16-bit value will signed extended somehow. 10424 // For SMULWT only the SRA is required. 10425 // Check both sides of SMUL_LOHI 10426 SDValue OpS16 = SMULLOHI->getOperand(0); 10427 SDValue OpS32 = SMULLOHI->getOperand(1); 10428 10429 SelectionDAG &DAG = DCI.DAG; 10430 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10431 OpS16 = OpS32; 10432 OpS32 = SMULLOHI->getOperand(0); 10433 } 10434 10435 SDLoc dl(OR); 10436 unsigned Opcode = 0; 10437 if (isS16(OpS16, DAG)) 10438 Opcode = ARMISD::SMULWB; 10439 else if (isSRA16(OpS16)) { 10440 Opcode = ARMISD::SMULWT; 10441 OpS16 = OpS16->getOperand(0); 10442 } 10443 else 10444 return SDValue(); 10445 10446 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10447 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10448 return SDValue(OR, 0); 10449 } 10450 10451 static SDValue PerformORCombineToBFI(SDNode *N, 10452 TargetLowering::DAGCombinerInfo &DCI, 10453 const ARMSubtarget *Subtarget) { 10454 // BFI is only available on V6T2+ 10455 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10456 return SDValue(); 10457 10458 EVT VT = N->getValueType(0); 10459 SDValue N0 = N->getOperand(0); 10460 SDValue N1 = N->getOperand(1); 10461 SelectionDAG &DAG = DCI.DAG; 10462 SDLoc DL(N); 10463 // 1) or (and A, mask), val => ARMbfi A, val, mask 10464 // iff (val & mask) == val 10465 // 10466 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10467 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10468 // && mask == ~mask2 10469 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10470 // && ~mask == mask2 10471 // (i.e., copy a bitfield value into another bitfield of the same width) 10472 10473 if (VT != MVT::i32) 10474 return SDValue(); 10475 10476 SDValue N00 = N0.getOperand(0); 10477 10478 // The value and the mask need to be constants so we can verify this is 10479 // actually a bitfield set. If the mask is 0xffff, we can do better 10480 // via a movt instruction, so don't use BFI in that case. 10481 SDValue MaskOp = N0.getOperand(1); 10482 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10483 if (!MaskC) 10484 return SDValue(); 10485 unsigned Mask = MaskC->getZExtValue(); 10486 if (Mask == 0xffff) 10487 return SDValue(); 10488 SDValue Res; 10489 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10490 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10491 if (N1C) { 10492 unsigned Val = N1C->getZExtValue(); 10493 if ((Val & ~Mask) != Val) 10494 return SDValue(); 10495 10496 if (ARM::isBitFieldInvertedMask(Mask)) { 10497 Val >>= countTrailingZeros(~Mask); 10498 10499 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10500 DAG.getConstant(Val, DL, MVT::i32), 10501 DAG.getConstant(Mask, DL, MVT::i32)); 10502 10503 DCI.CombineTo(N, Res, false); 10504 // Return value from the original node to inform the combiner than N is 10505 // now dead. 10506 return SDValue(N, 0); 10507 } 10508 } else if (N1.getOpcode() == ISD::AND) { 10509 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10510 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10511 if (!N11C) 10512 return SDValue(); 10513 unsigned Mask2 = N11C->getZExtValue(); 10514 10515 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10516 // as is to match. 10517 if (ARM::isBitFieldInvertedMask(Mask) && 10518 (Mask == ~Mask2)) { 10519 // The pack halfword instruction works better for masks that fit it, 10520 // so use that when it's available. 10521 if (Subtarget->hasDSP() && 10522 (Mask == 0xffff || Mask == 0xffff0000)) 10523 return SDValue(); 10524 // 2a 10525 unsigned amt = countTrailingZeros(Mask2); 10526 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10527 DAG.getConstant(amt, DL, MVT::i32)); 10528 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10529 DAG.getConstant(Mask, DL, MVT::i32)); 10530 DCI.CombineTo(N, Res, false); 10531 // Return value from the original node to inform the combiner than N is 10532 // now dead. 10533 return SDValue(N, 0); 10534 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10535 (~Mask == Mask2)) { 10536 // The pack halfword instruction works better for masks that fit it, 10537 // so use that when it's available. 10538 if (Subtarget->hasDSP() && 10539 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10540 return SDValue(); 10541 // 2b 10542 unsigned lsb = countTrailingZeros(Mask); 10543 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10544 DAG.getConstant(lsb, DL, MVT::i32)); 10545 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10546 DAG.getConstant(Mask2, DL, MVT::i32)); 10547 DCI.CombineTo(N, Res, false); 10548 // Return value from the original node to inform the combiner than N is 10549 // now dead. 10550 return SDValue(N, 0); 10551 } 10552 } 10553 10554 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10555 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10556 ARM::isBitFieldInvertedMask(~Mask)) { 10557 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10558 // where lsb(mask) == #shamt and masked bits of B are known zero. 10559 SDValue ShAmt = N00.getOperand(1); 10560 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10561 unsigned LSB = countTrailingZeros(Mask); 10562 if (ShAmtC != LSB) 10563 return SDValue(); 10564 10565 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10566 DAG.getConstant(~Mask, DL, MVT::i32)); 10567 10568 DCI.CombineTo(N, Res, false); 10569 // Return value from the original node to inform the combiner than N is 10570 // now dead. 10571 return SDValue(N, 0); 10572 } 10573 10574 return SDValue(); 10575 } 10576 10577 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 10578 static SDValue PerformORCombine(SDNode *N, 10579 TargetLowering::DAGCombinerInfo &DCI, 10580 const ARMSubtarget *Subtarget) { 10581 // Attempt to use immediate-form VORR 10582 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10583 SDLoc dl(N); 10584 EVT VT = N->getValueType(0); 10585 SelectionDAG &DAG = DCI.DAG; 10586 10587 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10588 return SDValue(); 10589 10590 APInt SplatBits, SplatUndef; 10591 unsigned SplatBitSize; 10592 bool HasAnyUndefs; 10593 if (BVN && Subtarget->hasNEON() && 10594 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10595 if (SplatBitSize <= 64) { 10596 EVT VorrVT; 10597 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 10598 SplatUndef.getZExtValue(), SplatBitSize, 10599 DAG, dl, VorrVT, VT.is128BitVector(), 10600 OtherModImm); 10601 if (Val.getNode()) { 10602 SDValue Input = 10603 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 10604 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 10605 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 10606 } 10607 } 10608 } 10609 10610 if (!Subtarget->isThumb1Only()) { 10611 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10612 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10613 return Result; 10614 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 10615 return Result; 10616 } 10617 10618 SDValue N0 = N->getOperand(0); 10619 SDValue N1 = N->getOperand(1); 10620 10621 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 10622 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 10623 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10624 10625 // The code below optimizes (or (and X, Y), Z). 10626 // The AND operand needs to have a single user to make these optimizations 10627 // profitable. 10628 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 10629 return SDValue(); 10630 10631 APInt SplatUndef; 10632 unsigned SplatBitSize; 10633 bool HasAnyUndefs; 10634 10635 APInt SplatBits0, SplatBits1; 10636 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 10637 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 10638 // Ensure that the second operand of both ands are constants 10639 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 10640 HasAnyUndefs) && !HasAnyUndefs) { 10641 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 10642 HasAnyUndefs) && !HasAnyUndefs) { 10643 // Ensure that the bit width of the constants are the same and that 10644 // the splat arguments are logical inverses as per the pattern we 10645 // are trying to simplify. 10646 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 10647 SplatBits0 == ~SplatBits1) { 10648 // Canonicalize the vector type to make instruction selection 10649 // simpler. 10650 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 10651 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 10652 N0->getOperand(1), 10653 N0->getOperand(0), 10654 N1->getOperand(0)); 10655 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 10656 } 10657 } 10658 } 10659 } 10660 10661 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 10662 // reasonable. 10663 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 10664 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 10665 return Res; 10666 } 10667 10668 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10669 return Result; 10670 10671 return SDValue(); 10672 } 10673 10674 static SDValue PerformXORCombine(SDNode *N, 10675 TargetLowering::DAGCombinerInfo &DCI, 10676 const ARMSubtarget *Subtarget) { 10677 EVT VT = N->getValueType(0); 10678 SelectionDAG &DAG = DCI.DAG; 10679 10680 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10681 return SDValue(); 10682 10683 if (!Subtarget->isThumb1Only()) { 10684 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10685 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10686 return Result; 10687 10688 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10689 return Result; 10690 } 10691 10692 return SDValue(); 10693 } 10694 10695 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 10696 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 10697 // their position in "to" (Rd). 10698 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 10699 assert(N->getOpcode() == ARMISD::BFI); 10700 10701 SDValue From = N->getOperand(1); 10702 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 10703 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 10704 10705 // If the Base came from a SHR #C, we can deduce that it is really testing bit 10706 // #C in the base of the SHR. 10707 if (From->getOpcode() == ISD::SRL && 10708 isa<ConstantSDNode>(From->getOperand(1))) { 10709 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 10710 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 10711 FromMask <<= Shift.getLimitedValue(31); 10712 From = From->getOperand(0); 10713 } 10714 10715 return From; 10716 } 10717 10718 // If A and B contain one contiguous set of bits, does A | B == A . B? 10719 // 10720 // Neither A nor B must be zero. 10721 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 10722 unsigned LastActiveBitInA = A.countTrailingZeros(); 10723 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 10724 return LastActiveBitInA - 1 == FirstActiveBitInB; 10725 } 10726 10727 static SDValue FindBFIToCombineWith(SDNode *N) { 10728 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 10729 // if one exists. 10730 APInt ToMask, FromMask; 10731 SDValue From = ParseBFI(N, ToMask, FromMask); 10732 SDValue To = N->getOperand(0); 10733 10734 // Now check for a compatible BFI to merge with. We can pass through BFIs that 10735 // aren't compatible, but not if they set the same bit in their destination as 10736 // we do (or that of any BFI we're going to combine with). 10737 SDValue V = To; 10738 APInt CombinedToMask = ToMask; 10739 while (V.getOpcode() == ARMISD::BFI) { 10740 APInt NewToMask, NewFromMask; 10741 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 10742 if (NewFrom != From) { 10743 // This BFI has a different base. Keep going. 10744 CombinedToMask |= NewToMask; 10745 V = V.getOperand(0); 10746 continue; 10747 } 10748 10749 // Do the written bits conflict with any we've seen so far? 10750 if ((NewToMask & CombinedToMask).getBoolValue()) 10751 // Conflicting bits - bail out because going further is unsafe. 10752 return SDValue(); 10753 10754 // Are the new bits contiguous when combined with the old bits? 10755 if (BitsProperlyConcatenate(ToMask, NewToMask) && 10756 BitsProperlyConcatenate(FromMask, NewFromMask)) 10757 return V; 10758 if (BitsProperlyConcatenate(NewToMask, ToMask) && 10759 BitsProperlyConcatenate(NewFromMask, FromMask)) 10760 return V; 10761 10762 // We've seen a write to some bits, so track it. 10763 CombinedToMask |= NewToMask; 10764 // Keep going... 10765 V = V.getOperand(0); 10766 } 10767 10768 return SDValue(); 10769 } 10770 10771 static SDValue PerformBFICombine(SDNode *N, 10772 TargetLowering::DAGCombinerInfo &DCI) { 10773 SDValue N1 = N->getOperand(1); 10774 if (N1.getOpcode() == ISD::AND) { 10775 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 10776 // the bits being cleared by the AND are not demanded by the BFI. 10777 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10778 if (!N11C) 10779 return SDValue(); 10780 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 10781 unsigned LSB = countTrailingZeros(~InvMask); 10782 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 10783 assert(Width < 10784 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 10785 "undefined behavior"); 10786 unsigned Mask = (1u << Width) - 1; 10787 unsigned Mask2 = N11C->getZExtValue(); 10788 if ((Mask & (~Mask2)) == 0) 10789 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 10790 N->getOperand(0), N1.getOperand(0), 10791 N->getOperand(2)); 10792 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 10793 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 10794 // Keep track of any consecutive bits set that all come from the same base 10795 // value. We can combine these together into a single BFI. 10796 SDValue CombineBFI = FindBFIToCombineWith(N); 10797 if (CombineBFI == SDValue()) 10798 return SDValue(); 10799 10800 // We've found a BFI. 10801 APInt ToMask1, FromMask1; 10802 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 10803 10804 APInt ToMask2, FromMask2; 10805 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 10806 assert(From1 == From2); 10807 (void)From2; 10808 10809 // First, unlink CombineBFI. 10810 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 10811 // Then create a new BFI, combining the two together. 10812 APInt NewFromMask = FromMask1 | FromMask2; 10813 APInt NewToMask = ToMask1 | ToMask2; 10814 10815 EVT VT = N->getValueType(0); 10816 SDLoc dl(N); 10817 10818 if (NewFromMask[0] == 0) 10819 From1 = DCI.DAG.getNode( 10820 ISD::SRL, dl, VT, From1, 10821 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 10822 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 10823 DCI.DAG.getConstant(~NewToMask, dl, VT)); 10824 } 10825 return SDValue(); 10826 } 10827 10828 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 10829 /// ARMISD::VMOVRRD. 10830 static SDValue PerformVMOVRRDCombine(SDNode *N, 10831 TargetLowering::DAGCombinerInfo &DCI, 10832 const ARMSubtarget *Subtarget) { 10833 // vmovrrd(vmovdrr x, y) -> x,y 10834 SDValue InDouble = N->getOperand(0); 10835 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 10836 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 10837 10838 // vmovrrd(load f64) -> (load i32), (load i32) 10839 SDNode *InNode = InDouble.getNode(); 10840 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 10841 InNode->getValueType(0) == MVT::f64 && 10842 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 10843 !cast<LoadSDNode>(InNode)->isVolatile()) { 10844 // TODO: Should this be done for non-FrameIndex operands? 10845 LoadSDNode *LD = cast<LoadSDNode>(InNode); 10846 10847 SelectionDAG &DAG = DCI.DAG; 10848 SDLoc DL(LD); 10849 SDValue BasePtr = LD->getBasePtr(); 10850 SDValue NewLD1 = 10851 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 10852 LD->getAlignment(), LD->getMemOperand()->getFlags()); 10853 10854 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 10855 DAG.getConstant(4, DL, MVT::i32)); 10856 SDValue NewLD2 = DAG.getLoad( 10857 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 10858 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 10859 10860 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 10861 if (DCI.DAG.getDataLayout().isBigEndian()) 10862 std::swap (NewLD1, NewLD2); 10863 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 10864 return Result; 10865 } 10866 10867 return SDValue(); 10868 } 10869 10870 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 10871 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 10872 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 10873 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 10874 SDValue Op0 = N->getOperand(0); 10875 SDValue Op1 = N->getOperand(1); 10876 if (Op0.getOpcode() == ISD::BITCAST) 10877 Op0 = Op0.getOperand(0); 10878 if (Op1.getOpcode() == ISD::BITCAST) 10879 Op1 = Op1.getOperand(0); 10880 if (Op0.getOpcode() == ARMISD::VMOVRRD && 10881 Op0.getNode() == Op1.getNode() && 10882 Op0.getResNo() == 0 && Op1.getResNo() == 1) 10883 return DAG.getNode(ISD::BITCAST, SDLoc(N), 10884 N->getValueType(0), Op0.getOperand(0)); 10885 return SDValue(); 10886 } 10887 10888 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 10889 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 10890 /// i64 vector to have f64 elements, since the value can then be loaded 10891 /// directly into a VFP register. 10892 static bool hasNormalLoadOperand(SDNode *N) { 10893 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 10894 for (unsigned i = 0; i < NumElts; ++i) { 10895 SDNode *Elt = N->getOperand(i).getNode(); 10896 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 10897 return true; 10898 } 10899 return false; 10900 } 10901 10902 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 10903 /// ISD::BUILD_VECTOR. 10904 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 10905 TargetLowering::DAGCombinerInfo &DCI, 10906 const ARMSubtarget *Subtarget) { 10907 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 10908 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 10909 // into a pair of GPRs, which is fine when the value is used as a scalar, 10910 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 10911 SelectionDAG &DAG = DCI.DAG; 10912 if (N->getNumOperands() == 2) 10913 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 10914 return RV; 10915 10916 // Load i64 elements as f64 values so that type legalization does not split 10917 // them up into i32 values. 10918 EVT VT = N->getValueType(0); 10919 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 10920 return SDValue(); 10921 SDLoc dl(N); 10922 SmallVector<SDValue, 8> Ops; 10923 unsigned NumElts = VT.getVectorNumElements(); 10924 for (unsigned i = 0; i < NumElts; ++i) { 10925 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 10926 Ops.push_back(V); 10927 // Make the DAGCombiner fold the bitcast. 10928 DCI.AddToWorklist(V.getNode()); 10929 } 10930 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 10931 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 10932 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 10933 } 10934 10935 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 10936 static SDValue 10937 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 10938 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 10939 // At that time, we may have inserted bitcasts from integer to float. 10940 // If these bitcasts have survived DAGCombine, change the lowering of this 10941 // BUILD_VECTOR in something more vector friendly, i.e., that does not 10942 // force to use floating point types. 10943 10944 // Make sure we can change the type of the vector. 10945 // This is possible iff: 10946 // 1. The vector is only used in a bitcast to a integer type. I.e., 10947 // 1.1. Vector is used only once. 10948 // 1.2. Use is a bit convert to an integer type. 10949 // 2. The size of its operands are 32-bits (64-bits are not legal). 10950 EVT VT = N->getValueType(0); 10951 EVT EltVT = VT.getVectorElementType(); 10952 10953 // Check 1.1. and 2. 10954 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 10955 return SDValue(); 10956 10957 // By construction, the input type must be float. 10958 assert(EltVT == MVT::f32 && "Unexpected type!"); 10959 10960 // Check 1.2. 10961 SDNode *Use = *N->use_begin(); 10962 if (Use->getOpcode() != ISD::BITCAST || 10963 Use->getValueType(0).isFloatingPoint()) 10964 return SDValue(); 10965 10966 // Check profitability. 10967 // Model is, if more than half of the relevant operands are bitcast from 10968 // i32, turn the build_vector into a sequence of insert_vector_elt. 10969 // Relevant operands are everything that is not statically 10970 // (i.e., at compile time) bitcasted. 10971 unsigned NumOfBitCastedElts = 0; 10972 unsigned NumElts = VT.getVectorNumElements(); 10973 unsigned NumOfRelevantElts = NumElts; 10974 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 10975 SDValue Elt = N->getOperand(Idx); 10976 if (Elt->getOpcode() == ISD::BITCAST) { 10977 // Assume only bit cast to i32 will go away. 10978 if (Elt->getOperand(0).getValueType() == MVT::i32) 10979 ++NumOfBitCastedElts; 10980 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 10981 // Constants are statically casted, thus do not count them as 10982 // relevant operands. 10983 --NumOfRelevantElts; 10984 } 10985 10986 // Check if more than half of the elements require a non-free bitcast. 10987 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 10988 return SDValue(); 10989 10990 SelectionDAG &DAG = DCI.DAG; 10991 // Create the new vector type. 10992 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 10993 // Check if the type is legal. 10994 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10995 if (!TLI.isTypeLegal(VecVT)) 10996 return SDValue(); 10997 10998 // Combine: 10999 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 11000 // => BITCAST INSERT_VECTOR_ELT 11001 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 11002 // (BITCAST EN), N. 11003 SDValue Vec = DAG.getUNDEF(VecVT); 11004 SDLoc dl(N); 11005 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 11006 SDValue V = N->getOperand(Idx); 11007 if (V.isUndef()) 11008 continue; 11009 if (V.getOpcode() == ISD::BITCAST && 11010 V->getOperand(0).getValueType() == MVT::i32) 11011 // Fold obvious case. 11012 V = V.getOperand(0); 11013 else { 11014 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 11015 // Make the DAGCombiner fold the bitcasts. 11016 DCI.AddToWorklist(V.getNode()); 11017 } 11018 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 11019 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 11020 } 11021 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 11022 // Make the DAGCombiner fold the bitcasts. 11023 DCI.AddToWorklist(Vec.getNode()); 11024 return Vec; 11025 } 11026 11027 /// PerformInsertEltCombine - Target-specific dag combine xforms for 11028 /// ISD::INSERT_VECTOR_ELT. 11029 static SDValue PerformInsertEltCombine(SDNode *N, 11030 TargetLowering::DAGCombinerInfo &DCI) { 11031 // Bitcast an i64 load inserted into a vector to f64. 11032 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11033 EVT VT = N->getValueType(0); 11034 SDNode *Elt = N->getOperand(1).getNode(); 11035 if (VT.getVectorElementType() != MVT::i64 || 11036 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 11037 return SDValue(); 11038 11039 SelectionDAG &DAG = DCI.DAG; 11040 SDLoc dl(N); 11041 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11042 VT.getVectorNumElements()); 11043 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 11044 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 11045 // Make the DAGCombiner fold the bitcasts. 11046 DCI.AddToWorklist(Vec.getNode()); 11047 DCI.AddToWorklist(V.getNode()); 11048 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 11049 Vec, V, N->getOperand(2)); 11050 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 11051 } 11052 11053 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 11054 /// ISD::VECTOR_SHUFFLE. 11055 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 11056 // The LLVM shufflevector instruction does not require the shuffle mask 11057 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 11058 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 11059 // operands do not match the mask length, they are extended by concatenating 11060 // them with undef vectors. That is probably the right thing for other 11061 // targets, but for NEON it is better to concatenate two double-register 11062 // size vector operands into a single quad-register size vector. Do that 11063 // transformation here: 11064 // shuffle(concat(v1, undef), concat(v2, undef)) -> 11065 // shuffle(concat(v1, v2), undef) 11066 SDValue Op0 = N->getOperand(0); 11067 SDValue Op1 = N->getOperand(1); 11068 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 11069 Op1.getOpcode() != ISD::CONCAT_VECTORS || 11070 Op0.getNumOperands() != 2 || 11071 Op1.getNumOperands() != 2) 11072 return SDValue(); 11073 SDValue Concat0Op1 = Op0.getOperand(1); 11074 SDValue Concat1Op1 = Op1.getOperand(1); 11075 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 11076 return SDValue(); 11077 // Skip the transformation if any of the types are illegal. 11078 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11079 EVT VT = N->getValueType(0); 11080 if (!TLI.isTypeLegal(VT) || 11081 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 11082 !TLI.isTypeLegal(Concat1Op1.getValueType())) 11083 return SDValue(); 11084 11085 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11086 Op0.getOperand(0), Op1.getOperand(0)); 11087 // Translate the shuffle mask. 11088 SmallVector<int, 16> NewMask; 11089 unsigned NumElts = VT.getVectorNumElements(); 11090 unsigned HalfElts = NumElts/2; 11091 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11092 for (unsigned n = 0; n < NumElts; ++n) { 11093 int MaskElt = SVN->getMaskElt(n); 11094 int NewElt = -1; 11095 if (MaskElt < (int)HalfElts) 11096 NewElt = MaskElt; 11097 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 11098 NewElt = HalfElts + MaskElt - NumElts; 11099 NewMask.push_back(NewElt); 11100 } 11101 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 11102 DAG.getUNDEF(VT), NewMask); 11103 } 11104 11105 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 11106 /// NEON load/store intrinsics, and generic vector load/stores, to merge 11107 /// base address updates. 11108 /// For generic load/stores, the memory type is assumed to be a vector. 11109 /// The caller is assumed to have checked legality. 11110 static SDValue CombineBaseUpdate(SDNode *N, 11111 TargetLowering::DAGCombinerInfo &DCI) { 11112 SelectionDAG &DAG = DCI.DAG; 11113 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 11114 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 11115 const bool isStore = N->getOpcode() == ISD::STORE; 11116 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 11117 SDValue Addr = N->getOperand(AddrOpIdx); 11118 MemSDNode *MemN = cast<MemSDNode>(N); 11119 SDLoc dl(N); 11120 11121 // Search for a use of the address operand that is an increment. 11122 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11123 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11124 SDNode *User = *UI; 11125 if (User->getOpcode() != ISD::ADD || 11126 UI.getUse().getResNo() != Addr.getResNo()) 11127 continue; 11128 11129 // Check that the add is independent of the load/store. Otherwise, folding 11130 // it would create a cycle. 11131 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 11132 continue; 11133 11134 // Find the new opcode for the updating load/store. 11135 bool isLoadOp = true; 11136 bool isLaneOp = false; 11137 unsigned NewOpc = 0; 11138 unsigned NumVecs = 0; 11139 if (isIntrinsic) { 11140 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11141 switch (IntNo) { 11142 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11143 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 11144 NumVecs = 1; break; 11145 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 11146 NumVecs = 2; break; 11147 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 11148 NumVecs = 3; break; 11149 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 11150 NumVecs = 4; break; 11151 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 11152 NumVecs = 2; isLaneOp = true; break; 11153 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 11154 NumVecs = 3; isLaneOp = true; break; 11155 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 11156 NumVecs = 4; isLaneOp = true; break; 11157 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 11158 NumVecs = 1; isLoadOp = false; break; 11159 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 11160 NumVecs = 2; isLoadOp = false; break; 11161 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 11162 NumVecs = 3; isLoadOp = false; break; 11163 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 11164 NumVecs = 4; isLoadOp = false; break; 11165 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 11166 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 11167 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 11168 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 11169 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 11170 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 11171 } 11172 } else { 11173 isLaneOp = true; 11174 switch (N->getOpcode()) { 11175 default: llvm_unreachable("unexpected opcode for Neon base update"); 11176 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 11177 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 11178 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 11179 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 11180 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 11181 NumVecs = 1; isLaneOp = false; break; 11182 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 11183 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 11184 } 11185 } 11186 11187 // Find the size of memory referenced by the load/store. 11188 EVT VecTy; 11189 if (isLoadOp) { 11190 VecTy = N->getValueType(0); 11191 } else if (isIntrinsic) { 11192 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 11193 } else { 11194 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 11195 VecTy = N->getOperand(1).getValueType(); 11196 } 11197 11198 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11199 if (isLaneOp) 11200 NumBytes /= VecTy.getVectorNumElements(); 11201 11202 // If the increment is a constant, it must match the memory ref size. 11203 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11204 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 11205 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 11206 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 11207 // separate instructions that make it harder to use a non-constant update. 11208 continue; 11209 } 11210 11211 // OK, we found an ADD we can fold into the base update. 11212 // Now, create a _UPD node, taking care of not breaking alignment. 11213 11214 EVT AlignedVecTy = VecTy; 11215 unsigned Alignment = MemN->getAlignment(); 11216 11217 // If this is a less-than-standard-aligned load/store, change the type to 11218 // match the standard alignment. 11219 // The alignment is overlooked when selecting _UPD variants; and it's 11220 // easier to introduce bitcasts here than fix that. 11221 // There are 3 ways to get to this base-update combine: 11222 // - intrinsics: they are assumed to be properly aligned (to the standard 11223 // alignment of the memory type), so we don't need to do anything. 11224 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 11225 // intrinsics, so, likewise, there's nothing to do. 11226 // - generic load/store instructions: the alignment is specified as an 11227 // explicit operand, rather than implicitly as the standard alignment 11228 // of the memory type (like the intrisics). We need to change the 11229 // memory type to match the explicit alignment. That way, we don't 11230 // generate non-standard-aligned ARMISD::VLDx nodes. 11231 if (isa<LSBaseSDNode>(N)) { 11232 if (Alignment == 0) 11233 Alignment = 1; 11234 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 11235 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 11236 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 11237 assert(!isLaneOp && "Unexpected generic load/store lane."); 11238 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 11239 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 11240 } 11241 // Don't set an explicit alignment on regular load/stores that we want 11242 // to transform to VLD/VST 1_UPD nodes. 11243 // This matches the behavior of regular load/stores, which only get an 11244 // explicit alignment if the MMO alignment is larger than the standard 11245 // alignment of the memory type. 11246 // Intrinsics, however, always get an explicit alignment, set to the 11247 // alignment of the MMO. 11248 Alignment = 1; 11249 } 11250 11251 // Create the new updating load/store node. 11252 // First, create an SDVTList for the new updating node's results. 11253 EVT Tys[6]; 11254 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 11255 unsigned n; 11256 for (n = 0; n < NumResultVecs; ++n) 11257 Tys[n] = AlignedVecTy; 11258 Tys[n++] = MVT::i32; 11259 Tys[n] = MVT::Other; 11260 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 11261 11262 // Then, gather the new node's operands. 11263 SmallVector<SDValue, 8> Ops; 11264 Ops.push_back(N->getOperand(0)); // incoming chain 11265 Ops.push_back(N->getOperand(AddrOpIdx)); 11266 Ops.push_back(Inc); 11267 11268 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 11269 // Try to match the intrinsic's signature 11270 Ops.push_back(StN->getValue()); 11271 } else { 11272 // Loads (and of course intrinsics) match the intrinsics' signature, 11273 // so just add all but the alignment operand. 11274 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 11275 Ops.push_back(N->getOperand(i)); 11276 } 11277 11278 // For all node types, the alignment operand is always the last one. 11279 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 11280 11281 // If this is a non-standard-aligned STORE, the penultimate operand is the 11282 // stored value. Bitcast it to the aligned type. 11283 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 11284 SDValue &StVal = Ops[Ops.size()-2]; 11285 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 11286 } 11287 11288 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 11289 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 11290 MemN->getMemOperand()); 11291 11292 // Update the uses. 11293 SmallVector<SDValue, 5> NewResults; 11294 for (unsigned i = 0; i < NumResultVecs; ++i) 11295 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11296 11297 // If this is an non-standard-aligned LOAD, the first result is the loaded 11298 // value. Bitcast it to the expected result type. 11299 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 11300 SDValue &LdVal = NewResults[0]; 11301 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 11302 } 11303 11304 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 11305 DCI.CombineTo(N, NewResults); 11306 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11307 11308 break; 11309 } 11310 return SDValue(); 11311 } 11312 11313 static SDValue PerformVLDCombine(SDNode *N, 11314 TargetLowering::DAGCombinerInfo &DCI) { 11315 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11316 return SDValue(); 11317 11318 return CombineBaseUpdate(N, DCI); 11319 } 11320 11321 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 11322 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 11323 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11324 /// return true. 11325 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11326 SelectionDAG &DAG = DCI.DAG; 11327 EVT VT = N->getValueType(0); 11328 // vldN-dup instructions only support 64-bit vectors for N > 1. 11329 if (!VT.is64BitVector()) 11330 return false; 11331 11332 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11333 SDNode *VLD = N->getOperand(0).getNode(); 11334 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11335 return false; 11336 unsigned NumVecs = 0; 11337 unsigned NewOpc = 0; 11338 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11339 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11340 NumVecs = 2; 11341 NewOpc = ARMISD::VLD2DUP; 11342 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11343 NumVecs = 3; 11344 NewOpc = ARMISD::VLD3DUP; 11345 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11346 NumVecs = 4; 11347 NewOpc = ARMISD::VLD4DUP; 11348 } else { 11349 return false; 11350 } 11351 11352 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11353 // numbers match the load. 11354 unsigned VLDLaneNo = 11355 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11356 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11357 UI != UE; ++UI) { 11358 // Ignore uses of the chain result. 11359 if (UI.getUse().getResNo() == NumVecs) 11360 continue; 11361 SDNode *User = *UI; 11362 if (User->getOpcode() != ARMISD::VDUPLANE || 11363 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11364 return false; 11365 } 11366 11367 // Create the vldN-dup node. 11368 EVT Tys[5]; 11369 unsigned n; 11370 for (n = 0; n < NumVecs; ++n) 11371 Tys[n] = VT; 11372 Tys[n] = MVT::Other; 11373 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11374 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11375 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11376 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11377 Ops, VLDMemInt->getMemoryVT(), 11378 VLDMemInt->getMemOperand()); 11379 11380 // Update the uses. 11381 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11382 UI != UE; ++UI) { 11383 unsigned ResNo = UI.getUse().getResNo(); 11384 // Ignore uses of the chain result. 11385 if (ResNo == NumVecs) 11386 continue; 11387 SDNode *User = *UI; 11388 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11389 } 11390 11391 // Now the vldN-lane intrinsic is dead except for its chain result. 11392 // Update uses of the chain. 11393 std::vector<SDValue> VLDDupResults; 11394 for (unsigned n = 0; n < NumVecs; ++n) 11395 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11396 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11397 DCI.CombineTo(VLD, VLDDupResults); 11398 11399 return true; 11400 } 11401 11402 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11403 /// ARMISD::VDUPLANE. 11404 static SDValue PerformVDUPLANECombine(SDNode *N, 11405 TargetLowering::DAGCombinerInfo &DCI) { 11406 SDValue Op = N->getOperand(0); 11407 11408 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11409 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11410 if (CombineVLDDUP(N, DCI)) 11411 return SDValue(N, 0); 11412 11413 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11414 // redundant. Ignore bit_converts for now; element sizes are checked below. 11415 while (Op.getOpcode() == ISD::BITCAST) 11416 Op = Op.getOperand(0); 11417 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11418 return SDValue(); 11419 11420 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11421 unsigned EltSize = Op.getScalarValueSizeInBits(); 11422 // The canonical VMOV for a zero vector uses a 32-bit element size. 11423 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11424 unsigned EltBits; 11425 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11426 EltSize = 8; 11427 EVT VT = N->getValueType(0); 11428 if (EltSize > VT.getScalarSizeInBits()) 11429 return SDValue(); 11430 11431 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11432 } 11433 11434 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11435 static SDValue PerformVDUPCombine(SDNode *N, 11436 TargetLowering::DAGCombinerInfo &DCI) { 11437 SelectionDAG &DAG = DCI.DAG; 11438 SDValue Op = N->getOperand(0); 11439 11440 // Match VDUP(LOAD) -> VLD1DUP. 11441 // We match this pattern here rather than waiting for isel because the 11442 // transform is only legal for unindexed loads. 11443 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11444 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11445 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11446 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11447 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11448 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11449 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11450 Ops, LD->getMemoryVT(), 11451 LD->getMemOperand()); 11452 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11453 return VLDDup; 11454 } 11455 11456 return SDValue(); 11457 } 11458 11459 static SDValue PerformLOADCombine(SDNode *N, 11460 TargetLowering::DAGCombinerInfo &DCI) { 11461 EVT VT = N->getValueType(0); 11462 11463 // If this is a legal vector load, try to combine it into a VLD1_UPD. 11464 if (ISD::isNormalLoad(N) && VT.isVector() && 11465 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11466 return CombineBaseUpdate(N, DCI); 11467 11468 return SDValue(); 11469 } 11470 11471 /// PerformSTORECombine - Target-specific dag combine xforms for 11472 /// ISD::STORE. 11473 static SDValue PerformSTORECombine(SDNode *N, 11474 TargetLowering::DAGCombinerInfo &DCI) { 11475 StoreSDNode *St = cast<StoreSDNode>(N); 11476 if (St->isVolatile()) 11477 return SDValue(); 11478 11479 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 11480 // pack all of the elements in one place. Next, store to memory in fewer 11481 // chunks. 11482 SDValue StVal = St->getValue(); 11483 EVT VT = StVal.getValueType(); 11484 if (St->isTruncatingStore() && VT.isVector()) { 11485 SelectionDAG &DAG = DCI.DAG; 11486 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11487 EVT StVT = St->getMemoryVT(); 11488 unsigned NumElems = VT.getVectorNumElements(); 11489 assert(StVT != VT && "Cannot truncate to the same type"); 11490 unsigned FromEltSz = VT.getScalarSizeInBits(); 11491 unsigned ToEltSz = StVT.getScalarSizeInBits(); 11492 11493 // From, To sizes and ElemCount must be pow of two 11494 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 11495 11496 // We are going to use the original vector elt for storing. 11497 // Accumulated smaller vector elements must be a multiple of the store size. 11498 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 11499 11500 unsigned SizeRatio = FromEltSz / ToEltSz; 11501 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 11502 11503 // Create a type on which we perform the shuffle. 11504 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 11505 NumElems*SizeRatio); 11506 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 11507 11508 SDLoc DL(St); 11509 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 11510 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 11511 for (unsigned i = 0; i < NumElems; ++i) 11512 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 11513 ? (i + 1) * SizeRatio - 1 11514 : i * SizeRatio; 11515 11516 // Can't shuffle using an illegal type. 11517 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 11518 11519 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 11520 DAG.getUNDEF(WideVec.getValueType()), 11521 ShuffleVec); 11522 // At this point all of the data is stored at the bottom of the 11523 // register. We now need to save it to mem. 11524 11525 // Find the largest store unit 11526 MVT StoreType = MVT::i8; 11527 for (MVT Tp : MVT::integer_valuetypes()) { 11528 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 11529 StoreType = Tp; 11530 } 11531 // Didn't find a legal store type. 11532 if (!TLI.isTypeLegal(StoreType)) 11533 return SDValue(); 11534 11535 // Bitcast the original vector into a vector of store-size units 11536 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 11537 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 11538 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 11539 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 11540 SmallVector<SDValue, 8> Chains; 11541 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 11542 TLI.getPointerTy(DAG.getDataLayout())); 11543 SDValue BasePtr = St->getBasePtr(); 11544 11545 // Perform one or more big stores into memory. 11546 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 11547 for (unsigned I = 0; I < E; I++) { 11548 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 11549 StoreType, ShuffWide, 11550 DAG.getIntPtrConstant(I, DL)); 11551 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 11552 St->getPointerInfo(), St->getAlignment(), 11553 St->getMemOperand()->getFlags()); 11554 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 11555 Increment); 11556 Chains.push_back(Ch); 11557 } 11558 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11559 } 11560 11561 if (!ISD::isNormalStore(St)) 11562 return SDValue(); 11563 11564 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 11565 // ARM stores of arguments in the same cache line. 11566 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 11567 StVal.getNode()->hasOneUse()) { 11568 SelectionDAG &DAG = DCI.DAG; 11569 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 11570 SDLoc DL(St); 11571 SDValue BasePtr = St->getBasePtr(); 11572 SDValue NewST1 = DAG.getStore( 11573 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 11574 BasePtr, St->getPointerInfo(), St->getAlignment(), 11575 St->getMemOperand()->getFlags()); 11576 11577 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11578 DAG.getConstant(4, DL, MVT::i32)); 11579 return DAG.getStore(NewST1.getValue(0), DL, 11580 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 11581 OffsetPtr, St->getPointerInfo(), 11582 std::min(4U, St->getAlignment() / 2), 11583 St->getMemOperand()->getFlags()); 11584 } 11585 11586 if (StVal.getValueType() == MVT::i64 && 11587 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11588 11589 // Bitcast an i64 store extracted from a vector to f64. 11590 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11591 SelectionDAG &DAG = DCI.DAG; 11592 SDLoc dl(StVal); 11593 SDValue IntVec = StVal.getOperand(0); 11594 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11595 IntVec.getValueType().getVectorNumElements()); 11596 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 11597 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 11598 Vec, StVal.getOperand(1)); 11599 dl = SDLoc(N); 11600 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 11601 // Make the DAGCombiner fold the bitcasts. 11602 DCI.AddToWorklist(Vec.getNode()); 11603 DCI.AddToWorklist(ExtElt.getNode()); 11604 DCI.AddToWorklist(V.getNode()); 11605 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 11606 St->getPointerInfo(), St->getAlignment(), 11607 St->getMemOperand()->getFlags(), St->getAAInfo()); 11608 } 11609 11610 // If this is a legal vector store, try to combine it into a VST1_UPD. 11611 if (ISD::isNormalStore(N) && VT.isVector() && 11612 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11613 return CombineBaseUpdate(N, DCI); 11614 11615 return SDValue(); 11616 } 11617 11618 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11619 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11620 /// when the VMUL has a constant operand that is a power of 2. 11621 /// 11622 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11623 /// vmul.f32 d16, d17, d16 11624 /// vcvt.s32.f32 d16, d16 11625 /// becomes: 11626 /// vcvt.s32.f32 d16, d16, #3 11627 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11628 const ARMSubtarget *Subtarget) { 11629 if (!Subtarget->hasNEON()) 11630 return SDValue(); 11631 11632 SDValue Op = N->getOperand(0); 11633 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 11634 Op.getOpcode() != ISD::FMUL) 11635 return SDValue(); 11636 11637 SDValue ConstVec = Op->getOperand(1); 11638 if (!isa<BuildVectorSDNode>(ConstVec)) 11639 return SDValue(); 11640 11641 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 11642 uint32_t FloatBits = FloatTy.getSizeInBits(); 11643 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 11644 uint32_t IntBits = IntTy.getSizeInBits(); 11645 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11646 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11647 // These instructions only exist converting from f32 to i32. We can handle 11648 // smaller integers by generating an extra truncate, but larger ones would 11649 // be lossy. We also can't handle more then 4 lanes, since these intructions 11650 // only support v2i32/v4i32 types. 11651 return SDValue(); 11652 } 11653 11654 BitVector UndefElements; 11655 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11656 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11657 if (C == -1 || C == 0 || C > 32) 11658 return SDValue(); 11659 11660 SDLoc dl(N); 11661 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 11662 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 11663 Intrinsic::arm_neon_vcvtfp2fxu; 11664 SDValue FixConv = DAG.getNode( 11665 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11666 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 11667 DAG.getConstant(C, dl, MVT::i32)); 11668 11669 if (IntBits < FloatBits) 11670 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 11671 11672 return FixConv; 11673 } 11674 11675 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 11676 /// can replace combinations of VCVT (integer to floating-point) and VDIV 11677 /// when the VDIV has a constant operand that is a power of 2. 11678 /// 11679 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11680 /// vcvt.f32.s32 d16, d16 11681 /// vdiv.f32 d16, d17, d16 11682 /// becomes: 11683 /// vcvt.f32.s32 d16, d16, #3 11684 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 11685 const ARMSubtarget *Subtarget) { 11686 if (!Subtarget->hasNEON()) 11687 return SDValue(); 11688 11689 SDValue Op = N->getOperand(0); 11690 unsigned OpOpcode = Op.getNode()->getOpcode(); 11691 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 11692 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 11693 return SDValue(); 11694 11695 SDValue ConstVec = N->getOperand(1); 11696 if (!isa<BuildVectorSDNode>(ConstVec)) 11697 return SDValue(); 11698 11699 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 11700 uint32_t FloatBits = FloatTy.getSizeInBits(); 11701 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 11702 uint32_t IntBits = IntTy.getSizeInBits(); 11703 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11704 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11705 // These instructions only exist converting from i32 to f32. We can handle 11706 // smaller integers by generating an extra extend, but larger ones would 11707 // be lossy. We also can't handle more then 4 lanes, since these intructions 11708 // only support v2i32/v4i32 types. 11709 return SDValue(); 11710 } 11711 11712 BitVector UndefElements; 11713 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11714 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11715 if (C == -1 || C == 0 || C > 32) 11716 return SDValue(); 11717 11718 SDLoc dl(N); 11719 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 11720 SDValue ConvInput = Op.getOperand(0); 11721 if (IntBits < FloatBits) 11722 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 11723 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11724 ConvInput); 11725 11726 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 11727 Intrinsic::arm_neon_vcvtfxu2fp; 11728 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 11729 Op.getValueType(), 11730 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 11731 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 11732 } 11733 11734 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 11735 /// operand of a vector shift operation, where all the elements of the 11736 /// build_vector must have the same constant integer value. 11737 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 11738 // Ignore bit_converts. 11739 while (Op.getOpcode() == ISD::BITCAST) 11740 Op = Op.getOperand(0); 11741 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 11742 APInt SplatBits, SplatUndef; 11743 unsigned SplatBitSize; 11744 bool HasAnyUndefs; 11745 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 11746 HasAnyUndefs, ElementBits) || 11747 SplatBitSize > ElementBits) 11748 return false; 11749 Cnt = SplatBits.getSExtValue(); 11750 return true; 11751 } 11752 11753 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 11754 /// operand of a vector shift left operation. That value must be in the range: 11755 /// 0 <= Value < ElementBits for a left shift; or 11756 /// 0 <= Value <= ElementBits for a long left shift. 11757 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 11758 assert(VT.isVector() && "vector shift count is not a vector type"); 11759 int64_t ElementBits = VT.getScalarSizeInBits(); 11760 if (! getVShiftImm(Op, ElementBits, Cnt)) 11761 return false; 11762 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 11763 } 11764 11765 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 11766 /// operand of a vector shift right operation. For a shift opcode, the value 11767 /// is positive, but for an intrinsic the value count must be negative. The 11768 /// absolute value must be in the range: 11769 /// 1 <= |Value| <= ElementBits for a right shift; or 11770 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 11771 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 11772 int64_t &Cnt) { 11773 assert(VT.isVector() && "vector shift count is not a vector type"); 11774 int64_t ElementBits = VT.getScalarSizeInBits(); 11775 if (! getVShiftImm(Op, ElementBits, Cnt)) 11776 return false; 11777 if (!isIntrinsic) 11778 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 11779 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 11780 Cnt = -Cnt; 11781 return true; 11782 } 11783 return false; 11784 } 11785 11786 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 11787 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 11788 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 11789 switch (IntNo) { 11790 default: 11791 // Don't do anything for most intrinsics. 11792 break; 11793 11794 // Vector shifts: check for immediate versions and lower them. 11795 // Note: This is done during DAG combining instead of DAG legalizing because 11796 // the build_vectors for 64-bit vector element shift counts are generally 11797 // not legal, and it is hard to see their values after they get legalized to 11798 // loads from a constant pool. 11799 case Intrinsic::arm_neon_vshifts: 11800 case Intrinsic::arm_neon_vshiftu: 11801 case Intrinsic::arm_neon_vrshifts: 11802 case Intrinsic::arm_neon_vrshiftu: 11803 case Intrinsic::arm_neon_vrshiftn: 11804 case Intrinsic::arm_neon_vqshifts: 11805 case Intrinsic::arm_neon_vqshiftu: 11806 case Intrinsic::arm_neon_vqshiftsu: 11807 case Intrinsic::arm_neon_vqshiftns: 11808 case Intrinsic::arm_neon_vqshiftnu: 11809 case Intrinsic::arm_neon_vqshiftnsu: 11810 case Intrinsic::arm_neon_vqrshiftns: 11811 case Intrinsic::arm_neon_vqrshiftnu: 11812 case Intrinsic::arm_neon_vqrshiftnsu: { 11813 EVT VT = N->getOperand(1).getValueType(); 11814 int64_t Cnt; 11815 unsigned VShiftOpc = 0; 11816 11817 switch (IntNo) { 11818 case Intrinsic::arm_neon_vshifts: 11819 case Intrinsic::arm_neon_vshiftu: 11820 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 11821 VShiftOpc = ARMISD::VSHL; 11822 break; 11823 } 11824 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 11825 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 11826 ARMISD::VSHRs : ARMISD::VSHRu); 11827 break; 11828 } 11829 return SDValue(); 11830 11831 case Intrinsic::arm_neon_vrshifts: 11832 case Intrinsic::arm_neon_vrshiftu: 11833 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 11834 break; 11835 return SDValue(); 11836 11837 case Intrinsic::arm_neon_vqshifts: 11838 case Intrinsic::arm_neon_vqshiftu: 11839 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11840 break; 11841 return SDValue(); 11842 11843 case Intrinsic::arm_neon_vqshiftsu: 11844 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 11845 break; 11846 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 11847 11848 case Intrinsic::arm_neon_vrshiftn: 11849 case Intrinsic::arm_neon_vqshiftns: 11850 case Intrinsic::arm_neon_vqshiftnu: 11851 case Intrinsic::arm_neon_vqshiftnsu: 11852 case Intrinsic::arm_neon_vqrshiftns: 11853 case Intrinsic::arm_neon_vqrshiftnu: 11854 case Intrinsic::arm_neon_vqrshiftnsu: 11855 // Narrowing shifts require an immediate right shift. 11856 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 11857 break; 11858 llvm_unreachable("invalid shift count for narrowing vector shift " 11859 "intrinsic"); 11860 11861 default: 11862 llvm_unreachable("unhandled vector shift"); 11863 } 11864 11865 switch (IntNo) { 11866 case Intrinsic::arm_neon_vshifts: 11867 case Intrinsic::arm_neon_vshiftu: 11868 // Opcode already set above. 11869 break; 11870 case Intrinsic::arm_neon_vrshifts: 11871 VShiftOpc = ARMISD::VRSHRs; break; 11872 case Intrinsic::arm_neon_vrshiftu: 11873 VShiftOpc = ARMISD::VRSHRu; break; 11874 case Intrinsic::arm_neon_vrshiftn: 11875 VShiftOpc = ARMISD::VRSHRN; break; 11876 case Intrinsic::arm_neon_vqshifts: 11877 VShiftOpc = ARMISD::VQSHLs; break; 11878 case Intrinsic::arm_neon_vqshiftu: 11879 VShiftOpc = ARMISD::VQSHLu; break; 11880 case Intrinsic::arm_neon_vqshiftsu: 11881 VShiftOpc = ARMISD::VQSHLsu; break; 11882 case Intrinsic::arm_neon_vqshiftns: 11883 VShiftOpc = ARMISD::VQSHRNs; break; 11884 case Intrinsic::arm_neon_vqshiftnu: 11885 VShiftOpc = ARMISD::VQSHRNu; break; 11886 case Intrinsic::arm_neon_vqshiftnsu: 11887 VShiftOpc = ARMISD::VQSHRNsu; break; 11888 case Intrinsic::arm_neon_vqrshiftns: 11889 VShiftOpc = ARMISD::VQRSHRNs; break; 11890 case Intrinsic::arm_neon_vqrshiftnu: 11891 VShiftOpc = ARMISD::VQRSHRNu; break; 11892 case Intrinsic::arm_neon_vqrshiftnsu: 11893 VShiftOpc = ARMISD::VQRSHRNsu; break; 11894 } 11895 11896 SDLoc dl(N); 11897 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11898 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 11899 } 11900 11901 case Intrinsic::arm_neon_vshiftins: { 11902 EVT VT = N->getOperand(1).getValueType(); 11903 int64_t Cnt; 11904 unsigned VShiftOpc = 0; 11905 11906 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 11907 VShiftOpc = ARMISD::VSLI; 11908 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 11909 VShiftOpc = ARMISD::VSRI; 11910 else { 11911 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 11912 } 11913 11914 SDLoc dl(N); 11915 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 11916 N->getOperand(1), N->getOperand(2), 11917 DAG.getConstant(Cnt, dl, MVT::i32)); 11918 } 11919 11920 case Intrinsic::arm_neon_vqrshifts: 11921 case Intrinsic::arm_neon_vqrshiftu: 11922 // No immediate versions of these to check for. 11923 break; 11924 } 11925 11926 return SDValue(); 11927 } 11928 11929 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 11930 /// lowers them. As with the vector shift intrinsics, this is done during DAG 11931 /// combining instead of DAG legalizing because the build_vectors for 64-bit 11932 /// vector element shift counts are generally not legal, and it is hard to see 11933 /// their values after they get legalized to loads from a constant pool. 11934 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 11935 const ARMSubtarget *ST) { 11936 EVT VT = N->getValueType(0); 11937 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 11938 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 11939 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 11940 SDValue N1 = N->getOperand(1); 11941 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 11942 SDValue N0 = N->getOperand(0); 11943 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 11944 DAG.MaskedValueIsZero(N0.getOperand(0), 11945 APInt::getHighBitsSet(32, 16))) 11946 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 11947 } 11948 } 11949 11950 // Nothing to be done for scalar shifts. 11951 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11952 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 11953 return SDValue(); 11954 11955 assert(ST->hasNEON() && "unexpected vector shift"); 11956 int64_t Cnt; 11957 11958 switch (N->getOpcode()) { 11959 default: llvm_unreachable("unexpected shift opcode"); 11960 11961 case ISD::SHL: 11962 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 11963 SDLoc dl(N); 11964 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 11965 DAG.getConstant(Cnt, dl, MVT::i32)); 11966 } 11967 break; 11968 11969 case ISD::SRA: 11970 case ISD::SRL: 11971 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 11972 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 11973 ARMISD::VSHRs : ARMISD::VSHRu); 11974 SDLoc dl(N); 11975 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 11976 DAG.getConstant(Cnt, dl, MVT::i32)); 11977 } 11978 } 11979 return SDValue(); 11980 } 11981 11982 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 11983 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 11984 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 11985 const ARMSubtarget *ST) { 11986 SDValue N0 = N->getOperand(0); 11987 11988 // Check for sign- and zero-extensions of vector extract operations of 8- 11989 // and 16-bit vector elements. NEON supports these directly. They are 11990 // handled during DAG combining because type legalization will promote them 11991 // to 32-bit types and it is messy to recognize the operations after that. 11992 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11993 SDValue Vec = N0.getOperand(0); 11994 SDValue Lane = N0.getOperand(1); 11995 EVT VT = N->getValueType(0); 11996 EVT EltVT = N0.getValueType(); 11997 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11998 11999 if (VT == MVT::i32 && 12000 (EltVT == MVT::i8 || EltVT == MVT::i16) && 12001 TLI.isTypeLegal(Vec.getValueType()) && 12002 isa<ConstantSDNode>(Lane)) { 12003 12004 unsigned Opc = 0; 12005 switch (N->getOpcode()) { 12006 default: llvm_unreachable("unexpected opcode"); 12007 case ISD::SIGN_EXTEND: 12008 Opc = ARMISD::VGETLANEs; 12009 break; 12010 case ISD::ZERO_EXTEND: 12011 case ISD::ANY_EXTEND: 12012 Opc = ARMISD::VGETLANEu; 12013 break; 12014 } 12015 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 12016 } 12017 } 12018 12019 return SDValue(); 12020 } 12021 12022 static const APInt *isPowerOf2Constant(SDValue V) { 12023 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 12024 if (!C) 12025 return nullptr; 12026 const APInt *CV = &C->getAPIntValue(); 12027 return CV->isPowerOf2() ? CV : nullptr; 12028 } 12029 12030 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 12031 // If we have a CMOV, OR and AND combination such as: 12032 // if (x & CN) 12033 // y |= CM; 12034 // 12035 // And: 12036 // * CN is a single bit; 12037 // * All bits covered by CM are known zero in y 12038 // 12039 // Then we can convert this into a sequence of BFI instructions. This will 12040 // always be a win if CM is a single bit, will always be no worse than the 12041 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 12042 // three bits (due to the extra IT instruction). 12043 12044 SDValue Op0 = CMOV->getOperand(0); 12045 SDValue Op1 = CMOV->getOperand(1); 12046 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 12047 auto CC = CCNode->getAPIntValue().getLimitedValue(); 12048 SDValue CmpZ = CMOV->getOperand(4); 12049 12050 // The compare must be against zero. 12051 if (!isNullConstant(CmpZ->getOperand(1))) 12052 return SDValue(); 12053 12054 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 12055 SDValue And = CmpZ->getOperand(0); 12056 if (And->getOpcode() != ISD::AND) 12057 return SDValue(); 12058 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 12059 if (!AndC) 12060 return SDValue(); 12061 SDValue X = And->getOperand(0); 12062 12063 if (CC == ARMCC::EQ) { 12064 // We're performing an "equal to zero" compare. Swap the operands so we 12065 // canonicalize on a "not equal to zero" compare. 12066 std::swap(Op0, Op1); 12067 } else { 12068 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 12069 } 12070 12071 if (Op1->getOpcode() != ISD::OR) 12072 return SDValue(); 12073 12074 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 12075 if (!OrC) 12076 return SDValue(); 12077 SDValue Y = Op1->getOperand(0); 12078 12079 if (Op0 != Y) 12080 return SDValue(); 12081 12082 // Now, is it profitable to continue? 12083 APInt OrCI = OrC->getAPIntValue(); 12084 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 12085 if (OrCI.countPopulation() > Heuristic) 12086 return SDValue(); 12087 12088 // Lastly, can we determine that the bits defined by OrCI 12089 // are zero in Y? 12090 KnownBits Known; 12091 DAG.computeKnownBits(Y, Known); 12092 if ((OrCI & Known.Zero) != OrCI) 12093 return SDValue(); 12094 12095 // OK, we can do the combine. 12096 SDValue V = Y; 12097 SDLoc dl(X); 12098 EVT VT = X.getValueType(); 12099 unsigned BitInX = AndC->logBase2(); 12100 12101 if (BitInX != 0) { 12102 // We must shift X first. 12103 X = DAG.getNode(ISD::SRL, dl, VT, X, 12104 DAG.getConstant(BitInX, dl, VT)); 12105 } 12106 12107 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 12108 BitInY < NumActiveBits; ++BitInY) { 12109 if (OrCI[BitInY] == 0) 12110 continue; 12111 APInt Mask(VT.getSizeInBits(), 0); 12112 Mask.setBit(BitInY); 12113 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 12114 // Confusingly, the operand is an *inverted* mask. 12115 DAG.getConstant(~Mask, dl, VT)); 12116 } 12117 12118 return V; 12119 } 12120 12121 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 12122 SDValue 12123 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 12124 SDValue Cmp = N->getOperand(4); 12125 if (Cmp.getOpcode() != ARMISD::CMPZ) 12126 // Only looking at NE cases. 12127 return SDValue(); 12128 12129 EVT VT = N->getValueType(0); 12130 SDLoc dl(N); 12131 SDValue LHS = Cmp.getOperand(0); 12132 SDValue RHS = Cmp.getOperand(1); 12133 SDValue Chain = N->getOperand(0); 12134 SDValue BB = N->getOperand(1); 12135 SDValue ARMcc = N->getOperand(2); 12136 ARMCC::CondCodes CC = 12137 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12138 12139 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 12140 // -> (brcond Chain BB CC CPSR Cmp) 12141 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 12142 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 12143 LHS->getOperand(0)->hasOneUse()) { 12144 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 12145 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 12146 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12147 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12148 if ((LHS00C && LHS00C->getZExtValue() == 0) && 12149 (LHS01C && LHS01C->getZExtValue() == 1) && 12150 (LHS1C && LHS1C->getZExtValue() == 1) && 12151 (RHSC && RHSC->getZExtValue() == 0)) { 12152 return DAG.getNode( 12153 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 12154 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 12155 } 12156 } 12157 12158 return SDValue(); 12159 } 12160 12161 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 12162 SDValue 12163 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 12164 SDValue Cmp = N->getOperand(4); 12165 if (Cmp.getOpcode() != ARMISD::CMPZ) 12166 // Only looking at EQ and NE cases. 12167 return SDValue(); 12168 12169 EVT VT = N->getValueType(0); 12170 SDLoc dl(N); 12171 SDValue LHS = Cmp.getOperand(0); 12172 SDValue RHS = Cmp.getOperand(1); 12173 SDValue FalseVal = N->getOperand(0); 12174 SDValue TrueVal = N->getOperand(1); 12175 SDValue ARMcc = N->getOperand(2); 12176 ARMCC::CondCodes CC = 12177 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12178 12179 // BFI is only available on V6T2+. 12180 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 12181 SDValue R = PerformCMOVToBFICombine(N, DAG); 12182 if (R) 12183 return R; 12184 } 12185 12186 // Simplify 12187 // mov r1, r0 12188 // cmp r1, x 12189 // mov r0, y 12190 // moveq r0, x 12191 // to 12192 // cmp r0, x 12193 // movne r0, y 12194 // 12195 // mov r1, r0 12196 // cmp r1, x 12197 // mov r0, x 12198 // movne r0, y 12199 // to 12200 // cmp r0, x 12201 // movne r0, y 12202 /// FIXME: Turn this into a target neutral optimization? 12203 SDValue Res; 12204 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 12205 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 12206 N->getOperand(3), Cmp); 12207 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 12208 SDValue ARMcc; 12209 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 12210 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 12211 N->getOperand(3), NewCmp); 12212 } 12213 12214 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 12215 // -> (cmov F T CC CPSR Cmp) 12216 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 12217 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 12218 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12219 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12220 if ((LHS0C && LHS0C->getZExtValue() == 0) && 12221 (LHS1C && LHS1C->getZExtValue() == 1) && 12222 (RHSC && RHSC->getZExtValue() == 0)) { 12223 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 12224 LHS->getOperand(2), LHS->getOperand(3), 12225 LHS->getOperand(4)); 12226 } 12227 } 12228 12229 if (Res.getNode()) { 12230 KnownBits Known; 12231 DAG.computeKnownBits(SDValue(N,0), Known); 12232 // Capture demanded bits information that would be otherwise lost. 12233 if (Known.Zero == 0xfffffffe) 12234 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12235 DAG.getValueType(MVT::i1)); 12236 else if (Known.Zero == 0xffffff00) 12237 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12238 DAG.getValueType(MVT::i8)); 12239 else if (Known.Zero == 0xffff0000) 12240 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12241 DAG.getValueType(MVT::i16)); 12242 } 12243 12244 return Res; 12245 } 12246 12247 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 12248 DAGCombinerInfo &DCI) const { 12249 switch (N->getOpcode()) { 12250 default: break; 12251 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 12252 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 12253 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 12254 case ISD::SUB: return PerformSUBCombine(N, DCI); 12255 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 12256 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 12257 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 12258 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 12259 case ARMISD::ADDC: 12260 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 12261 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI.DAG, Subtarget); 12262 case ARMISD::BFI: return PerformBFICombine(N, DCI); 12263 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 12264 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 12265 case ISD::STORE: return PerformSTORECombine(N, DCI); 12266 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 12267 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 12268 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 12269 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 12270 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 12271 case ISD::FP_TO_SINT: 12272 case ISD::FP_TO_UINT: 12273 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 12274 case ISD::FDIV: 12275 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 12276 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 12277 case ISD::SHL: 12278 case ISD::SRA: 12279 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 12280 case ISD::SIGN_EXTEND: 12281 case ISD::ZERO_EXTEND: 12282 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 12283 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 12284 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 12285 case ISD::LOAD: return PerformLOADCombine(N, DCI); 12286 case ARMISD::VLD1DUP: 12287 case ARMISD::VLD2DUP: 12288 case ARMISD::VLD3DUP: 12289 case ARMISD::VLD4DUP: 12290 return PerformVLDCombine(N, DCI); 12291 case ARMISD::BUILD_VECTOR: 12292 return PerformARMBUILD_VECTORCombine(N, DCI); 12293 case ARMISD::SMULWB: { 12294 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12295 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12296 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12297 return SDValue(); 12298 break; 12299 } 12300 case ARMISD::SMULWT: { 12301 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12302 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12303 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12304 return SDValue(); 12305 break; 12306 } 12307 case ARMISD::SMLALBB: { 12308 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12309 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12310 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12311 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12312 return SDValue(); 12313 break; 12314 } 12315 case ARMISD::SMLALBT: { 12316 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 12317 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12318 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 12319 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12320 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 12321 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12322 return SDValue(); 12323 break; 12324 } 12325 case ARMISD::SMLALTB: { 12326 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12327 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12328 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12329 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12330 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12331 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12332 return SDValue(); 12333 break; 12334 } 12335 case ARMISD::SMLALTT: { 12336 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12337 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12338 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12339 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12340 return SDValue(); 12341 break; 12342 } 12343 case ISD::INTRINSIC_VOID: 12344 case ISD::INTRINSIC_W_CHAIN: 12345 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12346 case Intrinsic::arm_neon_vld1: 12347 case Intrinsic::arm_neon_vld2: 12348 case Intrinsic::arm_neon_vld3: 12349 case Intrinsic::arm_neon_vld4: 12350 case Intrinsic::arm_neon_vld2lane: 12351 case Intrinsic::arm_neon_vld3lane: 12352 case Intrinsic::arm_neon_vld4lane: 12353 case Intrinsic::arm_neon_vst1: 12354 case Intrinsic::arm_neon_vst2: 12355 case Intrinsic::arm_neon_vst3: 12356 case Intrinsic::arm_neon_vst4: 12357 case Intrinsic::arm_neon_vst2lane: 12358 case Intrinsic::arm_neon_vst3lane: 12359 case Intrinsic::arm_neon_vst4lane: 12360 return PerformVLDCombine(N, DCI); 12361 default: break; 12362 } 12363 break; 12364 } 12365 return SDValue(); 12366 } 12367 12368 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 12369 EVT VT) const { 12370 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 12371 } 12372 12373 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12374 unsigned, 12375 unsigned, 12376 bool *Fast) const { 12377 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 12378 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 12379 12380 switch (VT.getSimpleVT().SimpleTy) { 12381 default: 12382 return false; 12383 case MVT::i8: 12384 case MVT::i16: 12385 case MVT::i32: { 12386 // Unaligned access can use (for example) LRDB, LRDH, LDR 12387 if (AllowsUnaligned) { 12388 if (Fast) 12389 *Fast = Subtarget->hasV7Ops(); 12390 return true; 12391 } 12392 return false; 12393 } 12394 case MVT::f64: 12395 case MVT::v2f64: { 12396 // For any little-endian targets with neon, we can support unaligned ld/st 12397 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 12398 // A big-endian target may also explicitly support unaligned accesses 12399 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 12400 if (Fast) 12401 *Fast = true; 12402 return true; 12403 } 12404 return false; 12405 } 12406 } 12407 } 12408 12409 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 12410 unsigned AlignCheck) { 12411 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 12412 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 12413 } 12414 12415 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 12416 unsigned DstAlign, unsigned SrcAlign, 12417 bool IsMemset, bool ZeroMemset, 12418 bool MemcpyStrSrc, 12419 MachineFunction &MF) const { 12420 const Function &F = MF.getFunction(); 12421 12422 // See if we can use NEON instructions for this... 12423 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 12424 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 12425 bool Fast; 12426 if (Size >= 16 && 12427 (memOpAlign(SrcAlign, DstAlign, 16) || 12428 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 12429 return MVT::v2f64; 12430 } else if (Size >= 8 && 12431 (memOpAlign(SrcAlign, DstAlign, 8) || 12432 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 12433 Fast))) { 12434 return MVT::f64; 12435 } 12436 } 12437 12438 // Let the target-independent logic figure it out. 12439 return MVT::Other; 12440 } 12441 12442 // 64-bit integers are split into their high and low parts and held in two 12443 // different registers, so the trunc is free since the low register can just 12444 // be used. 12445 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 12446 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 12447 return false; 12448 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 12449 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 12450 return (SrcBits == 64 && DestBits == 32); 12451 } 12452 12453 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 12454 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 12455 !DstVT.isInteger()) 12456 return false; 12457 unsigned SrcBits = SrcVT.getSizeInBits(); 12458 unsigned DestBits = DstVT.getSizeInBits(); 12459 return (SrcBits == 64 && DestBits == 32); 12460 } 12461 12462 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12463 if (Val.getOpcode() != ISD::LOAD) 12464 return false; 12465 12466 EVT VT1 = Val.getValueType(); 12467 if (!VT1.isSimple() || !VT1.isInteger() || 12468 !VT2.isSimple() || !VT2.isInteger()) 12469 return false; 12470 12471 switch (VT1.getSimpleVT().SimpleTy) { 12472 default: break; 12473 case MVT::i1: 12474 case MVT::i8: 12475 case MVT::i16: 12476 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 12477 return true; 12478 } 12479 12480 return false; 12481 } 12482 12483 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 12484 EVT VT = ExtVal.getValueType(); 12485 12486 if (!isTypeLegal(VT)) 12487 return false; 12488 12489 // Don't create a loadext if we can fold the extension into a wide/long 12490 // instruction. 12491 // If there's more than one user instruction, the loadext is desirable no 12492 // matter what. There can be two uses by the same instruction. 12493 if (ExtVal->use_empty() || 12494 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 12495 return true; 12496 12497 SDNode *U = *ExtVal->use_begin(); 12498 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 12499 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 12500 return false; 12501 12502 return true; 12503 } 12504 12505 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 12506 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12507 return false; 12508 12509 if (!isTypeLegal(EVT::getEVT(Ty1))) 12510 return false; 12511 12512 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 12513 12514 // Assuming the caller doesn't have a zeroext or signext return parameter, 12515 // truncation all the way down to i1 is valid. 12516 return true; 12517 } 12518 12519 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 12520 const AddrMode &AM, Type *Ty, 12521 unsigned AS) const { 12522 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 12523 if (Subtarget->hasFPAO()) 12524 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 12525 return 0; 12526 } 12527 return -1; 12528 } 12529 12530 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 12531 if (V < 0) 12532 return false; 12533 12534 unsigned Scale = 1; 12535 switch (VT.getSimpleVT().SimpleTy) { 12536 default: return false; 12537 case MVT::i1: 12538 case MVT::i8: 12539 // Scale == 1; 12540 break; 12541 case MVT::i16: 12542 // Scale == 2; 12543 Scale = 2; 12544 break; 12545 case MVT::i32: 12546 // Scale == 4; 12547 Scale = 4; 12548 break; 12549 } 12550 12551 if ((V & (Scale - 1)) != 0) 12552 return false; 12553 V /= Scale; 12554 return V == (V & ((1LL << 5) - 1)); 12555 } 12556 12557 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 12558 const ARMSubtarget *Subtarget) { 12559 bool isNeg = false; 12560 if (V < 0) { 12561 isNeg = true; 12562 V = - V; 12563 } 12564 12565 switch (VT.getSimpleVT().SimpleTy) { 12566 default: return false; 12567 case MVT::i1: 12568 case MVT::i8: 12569 case MVT::i16: 12570 case MVT::i32: 12571 // + imm12 or - imm8 12572 if (isNeg) 12573 return V == (V & ((1LL << 8) - 1)); 12574 return V == (V & ((1LL << 12) - 1)); 12575 case MVT::f32: 12576 case MVT::f64: 12577 // Same as ARM mode. FIXME: NEON? 12578 if (!Subtarget->hasVFP2()) 12579 return false; 12580 if ((V & 3) != 0) 12581 return false; 12582 V >>= 2; 12583 return V == (V & ((1LL << 8) - 1)); 12584 } 12585 } 12586 12587 /// isLegalAddressImmediate - Return true if the integer value can be used 12588 /// as the offset of the target addressing mode for load / store of the 12589 /// given type. 12590 static bool isLegalAddressImmediate(int64_t V, EVT VT, 12591 const ARMSubtarget *Subtarget) { 12592 if (V == 0) 12593 return true; 12594 12595 if (!VT.isSimple()) 12596 return false; 12597 12598 if (Subtarget->isThumb1Only()) 12599 return isLegalT1AddressImmediate(V, VT); 12600 else if (Subtarget->isThumb2()) 12601 return isLegalT2AddressImmediate(V, VT, Subtarget); 12602 12603 // ARM mode. 12604 if (V < 0) 12605 V = - V; 12606 switch (VT.getSimpleVT().SimpleTy) { 12607 default: return false; 12608 case MVT::i1: 12609 case MVT::i8: 12610 case MVT::i32: 12611 // +- imm12 12612 return V == (V & ((1LL << 12) - 1)); 12613 case MVT::i16: 12614 // +- imm8 12615 return V == (V & ((1LL << 8) - 1)); 12616 case MVT::f32: 12617 case MVT::f64: 12618 if (!Subtarget->hasVFP2()) // FIXME: NEON? 12619 return false; 12620 if ((V & 3) != 0) 12621 return false; 12622 V >>= 2; 12623 return V == (V & ((1LL << 8) - 1)); 12624 } 12625 } 12626 12627 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 12628 EVT VT) const { 12629 int Scale = AM.Scale; 12630 if (Scale < 0) 12631 return false; 12632 12633 switch (VT.getSimpleVT().SimpleTy) { 12634 default: return false; 12635 case MVT::i1: 12636 case MVT::i8: 12637 case MVT::i16: 12638 case MVT::i32: 12639 if (Scale == 1) 12640 return true; 12641 // r + r << imm 12642 Scale = Scale & ~1; 12643 return Scale == 2 || Scale == 4 || Scale == 8; 12644 case MVT::i64: 12645 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 12646 // version in Thumb mode. 12647 // r + r 12648 if (Scale == 1) 12649 return true; 12650 // r * 2 (this can be lowered to r + r). 12651 if (!AM.HasBaseReg && Scale == 2) 12652 return true; 12653 return false; 12654 case MVT::isVoid: 12655 // Note, we allow "void" uses (basically, uses that aren't loads or 12656 // stores), because arm allows folding a scale into many arithmetic 12657 // operations. This should be made more precise and revisited later. 12658 12659 // Allow r << imm, but the imm has to be a multiple of two. 12660 if (Scale & 1) return false; 12661 return isPowerOf2_32(Scale); 12662 } 12663 } 12664 12665 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 12666 EVT VT) const { 12667 const int Scale = AM.Scale; 12668 12669 // Negative scales are not supported in Thumb1. 12670 if (Scale < 0) 12671 return false; 12672 12673 // Thumb1 addressing modes do not support register scaling excepting the 12674 // following cases: 12675 // 1. Scale == 1 means no scaling. 12676 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 12677 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 12678 } 12679 12680 /// isLegalAddressingMode - Return true if the addressing mode represented 12681 /// by AM is legal for this target, for a load/store of the specified type. 12682 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 12683 const AddrMode &AM, Type *Ty, 12684 unsigned AS, Instruction *I) const { 12685 EVT VT = getValueType(DL, Ty, true); 12686 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 12687 return false; 12688 12689 // Can never fold addr of global into load/store. 12690 if (AM.BaseGV) 12691 return false; 12692 12693 switch (AM.Scale) { 12694 case 0: // no scale reg, must be "r+i" or "r", or "i". 12695 break; 12696 default: 12697 // ARM doesn't support any R+R*scale+imm addr modes. 12698 if (AM.BaseOffs) 12699 return false; 12700 12701 if (!VT.isSimple()) 12702 return false; 12703 12704 if (Subtarget->isThumb1Only()) 12705 return isLegalT1ScaledAddressingMode(AM, VT); 12706 12707 if (Subtarget->isThumb2()) 12708 return isLegalT2ScaledAddressingMode(AM, VT); 12709 12710 int Scale = AM.Scale; 12711 switch (VT.getSimpleVT().SimpleTy) { 12712 default: return false; 12713 case MVT::i1: 12714 case MVT::i8: 12715 case MVT::i32: 12716 if (Scale < 0) Scale = -Scale; 12717 if (Scale == 1) 12718 return true; 12719 // r + r << imm 12720 return isPowerOf2_32(Scale & ~1); 12721 case MVT::i16: 12722 case MVT::i64: 12723 // r +/- r 12724 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 12725 return true; 12726 // r * 2 (this can be lowered to r + r). 12727 if (!AM.HasBaseReg && Scale == 2) 12728 return true; 12729 return false; 12730 12731 case MVT::isVoid: 12732 // Note, we allow "void" uses (basically, uses that aren't loads or 12733 // stores), because arm allows folding a scale into many arithmetic 12734 // operations. This should be made more precise and revisited later. 12735 12736 // Allow r << imm, but the imm has to be a multiple of two. 12737 if (Scale & 1) return false; 12738 return isPowerOf2_32(Scale); 12739 } 12740 } 12741 return true; 12742 } 12743 12744 /// isLegalICmpImmediate - Return true if the specified immediate is legal 12745 /// icmp immediate, that is the target has icmp instructions which can compare 12746 /// a register against the immediate without having to materialize the 12747 /// immediate into a register. 12748 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 12749 // Thumb2 and ARM modes can use cmn for negative immediates. 12750 if (!Subtarget->isThumb()) 12751 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 12752 if (Subtarget->isThumb2()) 12753 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 12754 // Thumb1 doesn't have cmn, and only 8-bit immediates. 12755 return Imm >= 0 && Imm <= 255; 12756 } 12757 12758 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 12759 /// *or sub* immediate, that is the target has add or sub instructions which can 12760 /// add a register with the immediate without having to materialize the 12761 /// immediate into a register. 12762 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 12763 // Same encoding for add/sub, just flip the sign. 12764 int64_t AbsImm = std::abs(Imm); 12765 if (!Subtarget->isThumb()) 12766 return ARM_AM::getSOImmVal(AbsImm) != -1; 12767 if (Subtarget->isThumb2()) 12768 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 12769 // Thumb1 only has 8-bit unsigned immediate. 12770 return AbsImm >= 0 && AbsImm <= 255; 12771 } 12772 12773 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 12774 bool isSEXTLoad, SDValue &Base, 12775 SDValue &Offset, bool &isInc, 12776 SelectionDAG &DAG) { 12777 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12778 return false; 12779 12780 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 12781 // AddressingMode 3 12782 Base = Ptr->getOperand(0); 12783 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12784 int RHSC = (int)RHS->getZExtValue(); 12785 if (RHSC < 0 && RHSC > -256) { 12786 assert(Ptr->getOpcode() == ISD::ADD); 12787 isInc = false; 12788 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12789 return true; 12790 } 12791 } 12792 isInc = (Ptr->getOpcode() == ISD::ADD); 12793 Offset = Ptr->getOperand(1); 12794 return true; 12795 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 12796 // AddressingMode 2 12797 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12798 int RHSC = (int)RHS->getZExtValue(); 12799 if (RHSC < 0 && RHSC > -0x1000) { 12800 assert(Ptr->getOpcode() == ISD::ADD); 12801 isInc = false; 12802 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12803 Base = Ptr->getOperand(0); 12804 return true; 12805 } 12806 } 12807 12808 if (Ptr->getOpcode() == ISD::ADD) { 12809 isInc = true; 12810 ARM_AM::ShiftOpc ShOpcVal= 12811 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 12812 if (ShOpcVal != ARM_AM::no_shift) { 12813 Base = Ptr->getOperand(1); 12814 Offset = Ptr->getOperand(0); 12815 } else { 12816 Base = Ptr->getOperand(0); 12817 Offset = Ptr->getOperand(1); 12818 } 12819 return true; 12820 } 12821 12822 isInc = (Ptr->getOpcode() == ISD::ADD); 12823 Base = Ptr->getOperand(0); 12824 Offset = Ptr->getOperand(1); 12825 return true; 12826 } 12827 12828 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 12829 return false; 12830 } 12831 12832 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 12833 bool isSEXTLoad, SDValue &Base, 12834 SDValue &Offset, bool &isInc, 12835 SelectionDAG &DAG) { 12836 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 12837 return false; 12838 12839 Base = Ptr->getOperand(0); 12840 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 12841 int RHSC = (int)RHS->getZExtValue(); 12842 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 12843 assert(Ptr->getOpcode() == ISD::ADD); 12844 isInc = false; 12845 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12846 return true; 12847 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 12848 isInc = Ptr->getOpcode() == ISD::ADD; 12849 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 12850 return true; 12851 } 12852 } 12853 12854 return false; 12855 } 12856 12857 /// getPreIndexedAddressParts - returns true by value, base pointer and 12858 /// offset pointer and addressing mode by reference if the node's address 12859 /// can be legally represented as pre-indexed load / store address. 12860 bool 12861 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 12862 SDValue &Offset, 12863 ISD::MemIndexedMode &AM, 12864 SelectionDAG &DAG) const { 12865 if (Subtarget->isThumb1Only()) 12866 return false; 12867 12868 EVT VT; 12869 SDValue Ptr; 12870 bool isSEXTLoad = false; 12871 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12872 Ptr = LD->getBasePtr(); 12873 VT = LD->getMemoryVT(); 12874 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12875 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12876 Ptr = ST->getBasePtr(); 12877 VT = ST->getMemoryVT(); 12878 } else 12879 return false; 12880 12881 bool isInc; 12882 bool isLegal = false; 12883 if (Subtarget->isThumb2()) 12884 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12885 Offset, isInc, DAG); 12886 else 12887 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 12888 Offset, isInc, DAG); 12889 if (!isLegal) 12890 return false; 12891 12892 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 12893 return true; 12894 } 12895 12896 /// getPostIndexedAddressParts - returns true by value, base pointer and 12897 /// offset pointer and addressing mode by reference if this node can be 12898 /// combined with a load / store to form a post-indexed load / store. 12899 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 12900 SDValue &Base, 12901 SDValue &Offset, 12902 ISD::MemIndexedMode &AM, 12903 SelectionDAG &DAG) const { 12904 EVT VT; 12905 SDValue Ptr; 12906 bool isSEXTLoad = false, isNonExt; 12907 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12908 VT = LD->getMemoryVT(); 12909 Ptr = LD->getBasePtr(); 12910 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 12911 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 12912 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12913 VT = ST->getMemoryVT(); 12914 Ptr = ST->getBasePtr(); 12915 isNonExt = !ST->isTruncatingStore(); 12916 } else 12917 return false; 12918 12919 if (Subtarget->isThumb1Only()) { 12920 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 12921 // must be non-extending/truncating, i32, with an offset of 4. 12922 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 12923 if (Op->getOpcode() != ISD::ADD || !isNonExt) 12924 return false; 12925 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 12926 if (!RHS || RHS->getZExtValue() != 4) 12927 return false; 12928 12929 Offset = Op->getOperand(1); 12930 Base = Op->getOperand(0); 12931 AM = ISD::POST_INC; 12932 return true; 12933 } 12934 12935 bool isInc; 12936 bool isLegal = false; 12937 if (Subtarget->isThumb2()) 12938 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12939 isInc, DAG); 12940 else 12941 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 12942 isInc, DAG); 12943 if (!isLegal) 12944 return false; 12945 12946 if (Ptr != Base) { 12947 // Swap base ptr and offset to catch more post-index load / store when 12948 // it's legal. In Thumb2 mode, offset must be an immediate. 12949 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 12950 !Subtarget->isThumb2()) 12951 std::swap(Base, Offset); 12952 12953 // Post-indexed load / store update the base pointer. 12954 if (Ptr != Base) 12955 return false; 12956 } 12957 12958 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 12959 return true; 12960 } 12961 12962 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12963 KnownBits &Known, 12964 const APInt &DemandedElts, 12965 const SelectionDAG &DAG, 12966 unsigned Depth) const { 12967 unsigned BitWidth = Known.getBitWidth(); 12968 Known.resetAll(); 12969 switch (Op.getOpcode()) { 12970 default: break; 12971 case ARMISD::ADDC: 12972 case ARMISD::ADDE: 12973 case ARMISD::SUBC: 12974 case ARMISD::SUBE: 12975 // Special cases when we convert a carry to a boolean. 12976 if (Op.getResNo() == 0) { 12977 SDValue LHS = Op.getOperand(0); 12978 SDValue RHS = Op.getOperand(1); 12979 // (ADDE 0, 0, C) will give us a single bit. 12980 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 12981 isNullConstant(RHS)) { 12982 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 12983 return; 12984 } 12985 } 12986 break; 12987 case ARMISD::CMOV: { 12988 // Bits are known zero/one if known on the LHS and RHS. 12989 DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1); 12990 if (Known.isUnknown()) 12991 return; 12992 12993 KnownBits KnownRHS; 12994 DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1); 12995 Known.Zero &= KnownRHS.Zero; 12996 Known.One &= KnownRHS.One; 12997 return; 12998 } 12999 case ISD::INTRINSIC_W_CHAIN: { 13000 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 13001 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 13002 switch (IntID) { 13003 default: return; 13004 case Intrinsic::arm_ldaex: 13005 case Intrinsic::arm_ldrex: { 13006 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 13007 unsigned MemBits = VT.getScalarSizeInBits(); 13008 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 13009 return; 13010 } 13011 } 13012 } 13013 case ARMISD::BFI: { 13014 // Conservatively, we can recurse down the first operand 13015 // and just mask out all affected bits. 13016 DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1); 13017 13018 // The operand to BFI is already a mask suitable for removing the bits it 13019 // sets. 13020 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 13021 const APInt &Mask = CI->getAPIntValue(); 13022 Known.Zero &= Mask; 13023 Known.One &= Mask; 13024 return; 13025 } 13026 } 13027 } 13028 13029 //===----------------------------------------------------------------------===// 13030 // ARM Inline Assembly Support 13031 //===----------------------------------------------------------------------===// 13032 13033 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 13034 // Looking for "rev" which is V6+. 13035 if (!Subtarget->hasV6Ops()) 13036 return false; 13037 13038 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 13039 std::string AsmStr = IA->getAsmString(); 13040 SmallVector<StringRef, 4> AsmPieces; 13041 SplitString(AsmStr, AsmPieces, ";\n"); 13042 13043 switch (AsmPieces.size()) { 13044 default: return false; 13045 case 1: 13046 AsmStr = AsmPieces[0]; 13047 AsmPieces.clear(); 13048 SplitString(AsmStr, AsmPieces, " \t,"); 13049 13050 // rev $0, $1 13051 if (AsmPieces.size() == 3 && 13052 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 13053 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 13054 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 13055 if (Ty && Ty->getBitWidth() == 32) 13056 return IntrinsicLowering::LowerToByteSwap(CI); 13057 } 13058 break; 13059 } 13060 13061 return false; 13062 } 13063 13064 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 13065 // At this point, we have to lower this constraint to something else, so we 13066 // lower it to an "r" or "w". However, by doing this we will force the result 13067 // to be in register, while the X constraint is much more permissive. 13068 // 13069 // Although we are correct (we are free to emit anything, without 13070 // constraints), we might break use cases that would expect us to be more 13071 // efficient and emit something else. 13072 if (!Subtarget->hasVFP2()) 13073 return "r"; 13074 if (ConstraintVT.isFloatingPoint()) 13075 return "w"; 13076 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 13077 (ConstraintVT.getSizeInBits() == 64 || 13078 ConstraintVT.getSizeInBits() == 128)) 13079 return "w"; 13080 13081 return "r"; 13082 } 13083 13084 /// getConstraintType - Given a constraint letter, return the type of 13085 /// constraint it is for this target. 13086 ARMTargetLowering::ConstraintType 13087 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 13088 if (Constraint.size() == 1) { 13089 switch (Constraint[0]) { 13090 default: break; 13091 case 'l': return C_RegisterClass; 13092 case 'w': return C_RegisterClass; 13093 case 'h': return C_RegisterClass; 13094 case 'x': return C_RegisterClass; 13095 case 't': return C_RegisterClass; 13096 case 'j': return C_Other; // Constant for movw. 13097 // An address with a single base register. Due to the way we 13098 // currently handle addresses it is the same as an 'r' memory constraint. 13099 case 'Q': return C_Memory; 13100 } 13101 } else if (Constraint.size() == 2) { 13102 switch (Constraint[0]) { 13103 default: break; 13104 // All 'U+' constraints are addresses. 13105 case 'U': return C_Memory; 13106 } 13107 } 13108 return TargetLowering::getConstraintType(Constraint); 13109 } 13110 13111 /// Examine constraint type and operand type and determine a weight value. 13112 /// This object must already have been set up with the operand type 13113 /// and the current alternative constraint selected. 13114 TargetLowering::ConstraintWeight 13115 ARMTargetLowering::getSingleConstraintMatchWeight( 13116 AsmOperandInfo &info, const char *constraint) const { 13117 ConstraintWeight weight = CW_Invalid; 13118 Value *CallOperandVal = info.CallOperandVal; 13119 // If we don't have a value, we can't do a match, 13120 // but allow it at the lowest weight. 13121 if (!CallOperandVal) 13122 return CW_Default; 13123 Type *type = CallOperandVal->getType(); 13124 // Look at the constraint type. 13125 switch (*constraint) { 13126 default: 13127 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13128 break; 13129 case 'l': 13130 if (type->isIntegerTy()) { 13131 if (Subtarget->isThumb()) 13132 weight = CW_SpecificReg; 13133 else 13134 weight = CW_Register; 13135 } 13136 break; 13137 case 'w': 13138 if (type->isFloatingPointTy()) 13139 weight = CW_Register; 13140 break; 13141 } 13142 return weight; 13143 } 13144 13145 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 13146 13147 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 13148 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 13149 if (Constraint.size() == 1) { 13150 // GCC ARM Constraint Letters 13151 switch (Constraint[0]) { 13152 case 'l': // Low regs or general regs. 13153 if (Subtarget->isThumb()) 13154 return RCPair(0U, &ARM::tGPRRegClass); 13155 return RCPair(0U, &ARM::GPRRegClass); 13156 case 'h': // High regs or no regs. 13157 if (Subtarget->isThumb()) 13158 return RCPair(0U, &ARM::hGPRRegClass); 13159 break; 13160 case 'r': 13161 if (Subtarget->isThumb1Only()) 13162 return RCPair(0U, &ARM::tGPRRegClass); 13163 return RCPair(0U, &ARM::GPRRegClass); 13164 case 'w': 13165 if (VT == MVT::Other) 13166 break; 13167 if (VT == MVT::f32) 13168 return RCPair(0U, &ARM::SPRRegClass); 13169 if (VT.getSizeInBits() == 64) 13170 return RCPair(0U, &ARM::DPRRegClass); 13171 if (VT.getSizeInBits() == 128) 13172 return RCPair(0U, &ARM::QPRRegClass); 13173 break; 13174 case 'x': 13175 if (VT == MVT::Other) 13176 break; 13177 if (VT == MVT::f32) 13178 return RCPair(0U, &ARM::SPR_8RegClass); 13179 if (VT.getSizeInBits() == 64) 13180 return RCPair(0U, &ARM::DPR_8RegClass); 13181 if (VT.getSizeInBits() == 128) 13182 return RCPair(0U, &ARM::QPR_8RegClass); 13183 break; 13184 case 't': 13185 if (VT == MVT::f32 || VT == MVT::i32) 13186 return RCPair(0U, &ARM::SPRRegClass); 13187 break; 13188 } 13189 } 13190 if (StringRef("{cc}").equals_lower(Constraint)) 13191 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 13192 13193 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13194 } 13195 13196 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13197 /// vector. If it is invalid, don't add anything to Ops. 13198 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13199 std::string &Constraint, 13200 std::vector<SDValue>&Ops, 13201 SelectionDAG &DAG) const { 13202 SDValue Result; 13203 13204 // Currently only support length 1 constraints. 13205 if (Constraint.length() != 1) return; 13206 13207 char ConstraintLetter = Constraint[0]; 13208 switch (ConstraintLetter) { 13209 default: break; 13210 case 'j': 13211 case 'I': case 'J': case 'K': case 'L': 13212 case 'M': case 'N': case 'O': 13213 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 13214 if (!C) 13215 return; 13216 13217 int64_t CVal64 = C->getSExtValue(); 13218 int CVal = (int) CVal64; 13219 // None of these constraints allow values larger than 32 bits. Check 13220 // that the value fits in an int. 13221 if (CVal != CVal64) 13222 return; 13223 13224 switch (ConstraintLetter) { 13225 case 'j': 13226 // Constant suitable for movw, must be between 0 and 13227 // 65535. 13228 if (Subtarget->hasV6T2Ops()) 13229 if (CVal >= 0 && CVal <= 65535) 13230 break; 13231 return; 13232 case 'I': 13233 if (Subtarget->isThumb1Only()) { 13234 // This must be a constant between 0 and 255, for ADD 13235 // immediates. 13236 if (CVal >= 0 && CVal <= 255) 13237 break; 13238 } else if (Subtarget->isThumb2()) { 13239 // A constant that can be used as an immediate value in a 13240 // data-processing instruction. 13241 if (ARM_AM::getT2SOImmVal(CVal) != -1) 13242 break; 13243 } else { 13244 // A constant that can be used as an immediate value in a 13245 // data-processing instruction. 13246 if (ARM_AM::getSOImmVal(CVal) != -1) 13247 break; 13248 } 13249 return; 13250 13251 case 'J': 13252 if (Subtarget->isThumb1Only()) { 13253 // This must be a constant between -255 and -1, for negated ADD 13254 // immediates. This can be used in GCC with an "n" modifier that 13255 // prints the negated value, for use with SUB instructions. It is 13256 // not useful otherwise but is implemented for compatibility. 13257 if (CVal >= -255 && CVal <= -1) 13258 break; 13259 } else { 13260 // This must be a constant between -4095 and 4095. It is not clear 13261 // what this constraint is intended for. Implemented for 13262 // compatibility with GCC. 13263 if (CVal >= -4095 && CVal <= 4095) 13264 break; 13265 } 13266 return; 13267 13268 case 'K': 13269 if (Subtarget->isThumb1Only()) { 13270 // A 32-bit value where only one byte has a nonzero value. Exclude 13271 // zero to match GCC. This constraint is used by GCC internally for 13272 // constants that can be loaded with a move/shift combination. 13273 // It is not useful otherwise but is implemented for compatibility. 13274 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 13275 break; 13276 } else if (Subtarget->isThumb2()) { 13277 // A constant whose bitwise inverse can be used as an immediate 13278 // value in a data-processing instruction. This can be used in GCC 13279 // with a "B" modifier that prints the inverted value, for use with 13280 // BIC and MVN instructions. It is not useful otherwise but is 13281 // implemented for compatibility. 13282 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 13283 break; 13284 } else { 13285 // A constant whose bitwise inverse can be used as an immediate 13286 // value in a data-processing instruction. This can be used in GCC 13287 // with a "B" modifier that prints the inverted value, for use with 13288 // BIC and MVN instructions. It is not useful otherwise but is 13289 // implemented for compatibility. 13290 if (ARM_AM::getSOImmVal(~CVal) != -1) 13291 break; 13292 } 13293 return; 13294 13295 case 'L': 13296 if (Subtarget->isThumb1Only()) { 13297 // This must be a constant between -7 and 7, 13298 // for 3-operand ADD/SUB immediate instructions. 13299 if (CVal >= -7 && CVal < 7) 13300 break; 13301 } else if (Subtarget->isThumb2()) { 13302 // A constant whose negation can be used as an immediate value in a 13303 // data-processing instruction. This can be used in GCC with an "n" 13304 // modifier that prints the negated value, for use with SUB 13305 // instructions. It is not useful otherwise but is implemented for 13306 // compatibility. 13307 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 13308 break; 13309 } else { 13310 // A constant whose negation can be used as an immediate value in a 13311 // data-processing instruction. This can be used in GCC with an "n" 13312 // modifier that prints the negated value, for use with SUB 13313 // instructions. It is not useful otherwise but is implemented for 13314 // compatibility. 13315 if (ARM_AM::getSOImmVal(-CVal) != -1) 13316 break; 13317 } 13318 return; 13319 13320 case 'M': 13321 if (Subtarget->isThumb1Only()) { 13322 // This must be a multiple of 4 between 0 and 1020, for 13323 // ADD sp + immediate. 13324 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 13325 break; 13326 } else { 13327 // A power of two or a constant between 0 and 32. This is used in 13328 // GCC for the shift amount on shifted register operands, but it is 13329 // useful in general for any shift amounts. 13330 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 13331 break; 13332 } 13333 return; 13334 13335 case 'N': 13336 if (Subtarget->isThumb()) { // FIXME thumb2 13337 // This must be a constant between 0 and 31, for shift amounts. 13338 if (CVal >= 0 && CVal <= 31) 13339 break; 13340 } 13341 return; 13342 13343 case 'O': 13344 if (Subtarget->isThumb()) { // FIXME thumb2 13345 // This must be a multiple of 4 between -508 and 508, for 13346 // ADD/SUB sp = sp + immediate. 13347 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 13348 break; 13349 } 13350 return; 13351 } 13352 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 13353 break; 13354 } 13355 13356 if (Result.getNode()) { 13357 Ops.push_back(Result); 13358 return; 13359 } 13360 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13361 } 13362 13363 static RTLIB::Libcall getDivRemLibcall( 13364 const SDNode *N, MVT::SimpleValueType SVT) { 13365 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13366 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13367 "Unhandled Opcode in getDivRemLibcall"); 13368 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13369 N->getOpcode() == ISD::SREM; 13370 RTLIB::Libcall LC; 13371 switch (SVT) { 13372 default: llvm_unreachable("Unexpected request for libcall!"); 13373 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 13374 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 13375 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 13376 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 13377 } 13378 return LC; 13379 } 13380 13381 static TargetLowering::ArgListTy getDivRemArgList( 13382 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 13383 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13384 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13385 "Unhandled Opcode in getDivRemArgList"); 13386 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13387 N->getOpcode() == ISD::SREM; 13388 TargetLowering::ArgListTy Args; 13389 TargetLowering::ArgListEntry Entry; 13390 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13391 EVT ArgVT = N->getOperand(i).getValueType(); 13392 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 13393 Entry.Node = N->getOperand(i); 13394 Entry.Ty = ArgTy; 13395 Entry.IsSExt = isSigned; 13396 Entry.IsZExt = !isSigned; 13397 Args.push_back(Entry); 13398 } 13399 if (Subtarget->isTargetWindows() && Args.size() >= 2) 13400 std::swap(Args[0], Args[1]); 13401 return Args; 13402 } 13403 13404 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 13405 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 13406 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 13407 Subtarget->isTargetWindows()) && 13408 "Register-based DivRem lowering only"); 13409 unsigned Opcode = Op->getOpcode(); 13410 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 13411 "Invalid opcode for Div/Rem lowering"); 13412 bool isSigned = (Opcode == ISD::SDIVREM); 13413 EVT VT = Op->getValueType(0); 13414 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 13415 SDLoc dl(Op); 13416 13417 // If the target has hardware divide, use divide + multiply + subtract: 13418 // div = a / b 13419 // rem = a - b * div 13420 // return {div, rem} 13421 // This should be lowered into UDIV/SDIV + MLS later on. 13422 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 13423 : Subtarget->hasDivideInARMMode(); 13424 if (hasDivide && Op->getValueType(0).isSimple() && 13425 Op->getSimpleValueType(0) == MVT::i32) { 13426 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 13427 const SDValue Dividend = Op->getOperand(0); 13428 const SDValue Divisor = Op->getOperand(1); 13429 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 13430 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 13431 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 13432 13433 SDValue Values[2] = {Div, Rem}; 13434 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 13435 } 13436 13437 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 13438 VT.getSimpleVT().SimpleTy); 13439 SDValue InChain = DAG.getEntryNode(); 13440 13441 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 13442 DAG.getContext(), 13443 Subtarget); 13444 13445 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13446 getPointerTy(DAG.getDataLayout())); 13447 13448 Type *RetTy = StructType::get(Ty, Ty); 13449 13450 if (Subtarget->isTargetWindows()) 13451 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 13452 13453 TargetLowering::CallLoweringInfo CLI(DAG); 13454 CLI.setDebugLoc(dl).setChain(InChain) 13455 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 13456 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 13457 13458 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 13459 return CallInfo.first; 13460 } 13461 13462 // Lowers REM using divmod helpers 13463 // see RTABI section 4.2/4.3 13464 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 13465 // Build return types (div and rem) 13466 std::vector<Type*> RetTyParams; 13467 Type *RetTyElement; 13468 13469 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 13470 default: llvm_unreachable("Unexpected request for libcall!"); 13471 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 13472 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 13473 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 13474 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 13475 } 13476 13477 RetTyParams.push_back(RetTyElement); 13478 RetTyParams.push_back(RetTyElement); 13479 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 13480 Type *RetTy = StructType::get(*DAG.getContext(), ret); 13481 13482 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 13483 SimpleTy); 13484 SDValue InChain = DAG.getEntryNode(); 13485 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 13486 Subtarget); 13487 bool isSigned = N->getOpcode() == ISD::SREM; 13488 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13489 getPointerTy(DAG.getDataLayout())); 13490 13491 if (Subtarget->isTargetWindows()) 13492 InChain = WinDBZCheckDenominator(DAG, N, InChain); 13493 13494 // Lower call 13495 CallLoweringInfo CLI(DAG); 13496 CLI.setChain(InChain) 13497 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 13498 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 13499 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 13500 13501 // Return second (rem) result operand (first contains div) 13502 SDNode *ResNode = CallResult.first.getNode(); 13503 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 13504 return ResNode->getOperand(1); 13505 } 13506 13507 SDValue 13508 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 13509 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 13510 SDLoc DL(Op); 13511 13512 // Get the inputs. 13513 SDValue Chain = Op.getOperand(0); 13514 SDValue Size = Op.getOperand(1); 13515 13516 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 13517 DAG.getConstant(2, DL, MVT::i32)); 13518 13519 SDValue Flag; 13520 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 13521 Flag = Chain.getValue(1); 13522 13523 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 13524 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 13525 13526 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 13527 Chain = NewSP.getValue(1); 13528 13529 SDValue Ops[2] = { NewSP, Chain }; 13530 return DAG.getMergeValues(Ops, DL); 13531 } 13532 13533 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 13534 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 13535 "Unexpected type for custom-lowering FP_EXTEND"); 13536 13537 RTLIB::Libcall LC; 13538 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 13539 13540 SDValue SrcVal = Op.getOperand(0); 13541 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13542 SDLoc(Op)).first; 13543 } 13544 13545 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 13546 assert(Op.getOperand(0).getValueType() == MVT::f64 && 13547 Subtarget->isFPOnlySP() && 13548 "Unexpected type for custom-lowering FP_ROUND"); 13549 13550 RTLIB::Libcall LC; 13551 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 13552 13553 SDValue SrcVal = Op.getOperand(0); 13554 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13555 SDLoc(Op)).first; 13556 } 13557 13558 bool 13559 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13560 // The ARM target isn't yet aware of offsets. 13561 return false; 13562 } 13563 13564 bool ARM::isBitFieldInvertedMask(unsigned v) { 13565 if (v == 0xffffffff) 13566 return false; 13567 13568 // there can be 1's on either or both "outsides", all the "inside" 13569 // bits must be 0's 13570 return isShiftedMask_32(~v); 13571 } 13572 13573 /// isFPImmLegal - Returns true if the target can instruction select the 13574 /// specified FP immediate natively. If false, the legalizer will 13575 /// materialize the FP immediate as a load from a constant pool. 13576 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13577 if (!Subtarget->hasVFP3()) 13578 return false; 13579 if (VT == MVT::f32) 13580 return ARM_AM::getFP32Imm(Imm) != -1; 13581 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 13582 return ARM_AM::getFP64Imm(Imm) != -1; 13583 return false; 13584 } 13585 13586 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 13587 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 13588 /// specified in the intrinsic calls. 13589 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13590 const CallInst &I, 13591 MachineFunction &MF, 13592 unsigned Intrinsic) const { 13593 switch (Intrinsic) { 13594 case Intrinsic::arm_neon_vld1: 13595 case Intrinsic::arm_neon_vld2: 13596 case Intrinsic::arm_neon_vld3: 13597 case Intrinsic::arm_neon_vld4: 13598 case Intrinsic::arm_neon_vld2lane: 13599 case Intrinsic::arm_neon_vld3lane: 13600 case Intrinsic::arm_neon_vld4lane: { 13601 Info.opc = ISD::INTRINSIC_W_CHAIN; 13602 // Conservatively set memVT to the entire set of vectors loaded. 13603 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13604 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 13605 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13606 Info.ptrVal = I.getArgOperand(0); 13607 Info.offset = 0; 13608 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13609 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13610 // volatile loads with NEON intrinsics not supported 13611 Info.flags = MachineMemOperand::MOLoad; 13612 return true; 13613 } 13614 case Intrinsic::arm_neon_vst1: 13615 case Intrinsic::arm_neon_vst2: 13616 case Intrinsic::arm_neon_vst3: 13617 case Intrinsic::arm_neon_vst4: 13618 case Intrinsic::arm_neon_vst2lane: 13619 case Intrinsic::arm_neon_vst3lane: 13620 case Intrinsic::arm_neon_vst4lane: { 13621 Info.opc = ISD::INTRINSIC_VOID; 13622 // Conservatively set memVT to the entire set of vectors stored. 13623 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13624 unsigned NumElts = 0; 13625 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 13626 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 13627 if (!ArgTy->isVectorTy()) 13628 break; 13629 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 13630 } 13631 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13632 Info.ptrVal = I.getArgOperand(0); 13633 Info.offset = 0; 13634 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13635 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13636 // volatile stores with NEON intrinsics not supported 13637 Info.flags = MachineMemOperand::MOStore; 13638 return true; 13639 } 13640 case Intrinsic::arm_ldaex: 13641 case Intrinsic::arm_ldrex: { 13642 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13643 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 13644 Info.opc = ISD::INTRINSIC_W_CHAIN; 13645 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13646 Info.ptrVal = I.getArgOperand(0); 13647 Info.offset = 0; 13648 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13649 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 13650 return true; 13651 } 13652 case Intrinsic::arm_stlex: 13653 case Intrinsic::arm_strex: { 13654 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13655 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 13656 Info.opc = ISD::INTRINSIC_W_CHAIN; 13657 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13658 Info.ptrVal = I.getArgOperand(1); 13659 Info.offset = 0; 13660 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13661 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 13662 return true; 13663 } 13664 case Intrinsic::arm_stlexd: 13665 case Intrinsic::arm_strexd: 13666 Info.opc = ISD::INTRINSIC_W_CHAIN; 13667 Info.memVT = MVT::i64; 13668 Info.ptrVal = I.getArgOperand(2); 13669 Info.offset = 0; 13670 Info.align = 8; 13671 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 13672 return true; 13673 13674 case Intrinsic::arm_ldaexd: 13675 case Intrinsic::arm_ldrexd: 13676 Info.opc = ISD::INTRINSIC_W_CHAIN; 13677 Info.memVT = MVT::i64; 13678 Info.ptrVal = I.getArgOperand(0); 13679 Info.offset = 0; 13680 Info.align = 8; 13681 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 13682 return true; 13683 13684 default: 13685 break; 13686 } 13687 13688 return false; 13689 } 13690 13691 /// \brief Returns true if it is beneficial to convert a load of a constant 13692 /// to just the constant itself. 13693 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13694 Type *Ty) const { 13695 assert(Ty->isIntegerTy()); 13696 13697 unsigned Bits = Ty->getPrimitiveSizeInBits(); 13698 if (Bits == 0 || Bits > 32) 13699 return false; 13700 return true; 13701 } 13702 13703 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 13704 unsigned Index) const { 13705 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 13706 return false; 13707 13708 return (Index == 0 || Index == ResVT.getVectorNumElements()); 13709 } 13710 13711 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 13712 ARM_MB::MemBOpt Domain) const { 13713 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13714 13715 // First, if the target has no DMB, see what fallback we can use. 13716 if (!Subtarget->hasDataBarrier()) { 13717 // Some ARMv6 cpus can support data barriers with an mcr instruction. 13718 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 13719 // here. 13720 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 13721 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 13722 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 13723 Builder.getInt32(0), Builder.getInt32(7), 13724 Builder.getInt32(10), Builder.getInt32(5)}; 13725 return Builder.CreateCall(MCR, args); 13726 } else { 13727 // Instead of using barriers, atomic accesses on these subtargets use 13728 // libcalls. 13729 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 13730 } 13731 } else { 13732 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 13733 // Only a full system barrier exists in the M-class architectures. 13734 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 13735 Constant *CDomain = Builder.getInt32(Domain); 13736 return Builder.CreateCall(DMB, CDomain); 13737 } 13738 } 13739 13740 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 13741 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 13742 Instruction *Inst, 13743 AtomicOrdering Ord) const { 13744 switch (Ord) { 13745 case AtomicOrdering::NotAtomic: 13746 case AtomicOrdering::Unordered: 13747 llvm_unreachable("Invalid fence: unordered/non-atomic"); 13748 case AtomicOrdering::Monotonic: 13749 case AtomicOrdering::Acquire: 13750 return nullptr; // Nothing to do 13751 case AtomicOrdering::SequentiallyConsistent: 13752 if (!Inst->hasAtomicStore()) 13753 return nullptr; // Nothing to do 13754 /*FALLTHROUGH*/ 13755 case AtomicOrdering::Release: 13756 case AtomicOrdering::AcquireRelease: 13757 if (Subtarget->preferISHSTBarriers()) 13758 return makeDMB(Builder, ARM_MB::ISHST); 13759 // FIXME: add a comment with a link to documentation justifying this. 13760 else 13761 return makeDMB(Builder, ARM_MB::ISH); 13762 } 13763 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 13764 } 13765 13766 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 13767 Instruction *Inst, 13768 AtomicOrdering Ord) const { 13769 switch (Ord) { 13770 case AtomicOrdering::NotAtomic: 13771 case AtomicOrdering::Unordered: 13772 llvm_unreachable("Invalid fence: unordered/not-atomic"); 13773 case AtomicOrdering::Monotonic: 13774 case AtomicOrdering::Release: 13775 return nullptr; // Nothing to do 13776 case AtomicOrdering::Acquire: 13777 case AtomicOrdering::AcquireRelease: 13778 case AtomicOrdering::SequentiallyConsistent: 13779 return makeDMB(Builder, ARM_MB::ISH); 13780 } 13781 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 13782 } 13783 13784 // Loads and stores less than 64-bits are already atomic; ones above that 13785 // are doomed anyway, so defer to the default libcall and blame the OS when 13786 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13787 // anything for those. 13788 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 13789 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 13790 return (Size == 64) && !Subtarget->isMClass(); 13791 } 13792 13793 // Loads and stores less than 64-bits are already atomic; ones above that 13794 // are doomed anyway, so defer to the default libcall and blame the OS when 13795 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 13796 // anything for those. 13797 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 13798 // guarantee, see DDI0406C ARM architecture reference manual, 13799 // sections A8.8.72-74 LDRD) 13800 TargetLowering::AtomicExpansionKind 13801 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 13802 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 13803 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 13804 : AtomicExpansionKind::None; 13805 } 13806 13807 // For the real atomic operations, we have ldrex/strex up to 32 bits, 13808 // and up to 64 bits on the non-M profiles 13809 TargetLowering::AtomicExpansionKind 13810 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 13811 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 13812 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13813 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 13814 ? AtomicExpansionKind::LLSC 13815 : AtomicExpansionKind::None; 13816 } 13817 13818 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 13819 AtomicCmpXchgInst *AI) const { 13820 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 13821 // implement cmpxchg without spilling. If the address being exchanged is also 13822 // on the stack and close enough to the spill slot, this can lead to a 13823 // situation where the monitor always gets cleared and the atomic operation 13824 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 13825 bool hasAtomicCmpXchg = 13826 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 13827 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 13828 } 13829 13830 bool ARMTargetLowering::shouldInsertFencesForAtomic( 13831 const Instruction *I) const { 13832 return InsertFencesForAtomic; 13833 } 13834 13835 // This has so far only been implemented for MachO. 13836 bool ARMTargetLowering::useLoadStackGuardNode() const { 13837 return Subtarget->isTargetMachO(); 13838 } 13839 13840 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 13841 unsigned &Cost) const { 13842 // If we do not have NEON, vector types are not natively supported. 13843 if (!Subtarget->hasNEON()) 13844 return false; 13845 13846 // Floating point values and vector values map to the same register file. 13847 // Therefore, although we could do a store extract of a vector type, this is 13848 // better to leave at float as we have more freedom in the addressing mode for 13849 // those. 13850 if (VectorTy->isFPOrFPVectorTy()) 13851 return false; 13852 13853 // If the index is unknown at compile time, this is very expensive to lower 13854 // and it is not possible to combine the store with the extract. 13855 if (!isa<ConstantInt>(Idx)) 13856 return false; 13857 13858 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 13859 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 13860 // We can do a store + vector extract on any vector that fits perfectly in a D 13861 // or Q register. 13862 if (BitWidth == 64 || BitWidth == 128) { 13863 Cost = 0; 13864 return true; 13865 } 13866 return false; 13867 } 13868 13869 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 13870 return Subtarget->hasV6T2Ops(); 13871 } 13872 13873 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 13874 return Subtarget->hasV6T2Ops(); 13875 } 13876 13877 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 13878 AtomicOrdering Ord) const { 13879 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13880 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 13881 bool IsAcquire = isAcquireOrStronger(Ord); 13882 13883 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 13884 // intrinsic must return {i32, i32} and we have to recombine them into a 13885 // single i64 here. 13886 if (ValTy->getPrimitiveSizeInBits() == 64) { 13887 Intrinsic::ID Int = 13888 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 13889 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 13890 13891 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13892 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 13893 13894 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 13895 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 13896 if (!Subtarget->isLittle()) 13897 std::swap (Lo, Hi); 13898 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 13899 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 13900 return Builder.CreateOr( 13901 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 13902 } 13903 13904 Type *Tys[] = { Addr->getType() }; 13905 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 13906 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 13907 13908 return Builder.CreateTruncOrBitCast( 13909 Builder.CreateCall(Ldrex, Addr), 13910 cast<PointerType>(Addr->getType())->getElementType()); 13911 } 13912 13913 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 13914 IRBuilder<> &Builder) const { 13915 if (!Subtarget->hasV7Ops()) 13916 return; 13917 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13918 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 13919 } 13920 13921 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 13922 Value *Addr, 13923 AtomicOrdering Ord) const { 13924 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13925 bool IsRelease = isReleaseOrStronger(Ord); 13926 13927 // Since the intrinsics must have legal type, the i64 intrinsics take two 13928 // parameters: "i32, i32". We must marshal Val into the appropriate form 13929 // before the call. 13930 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 13931 Intrinsic::ID Int = 13932 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 13933 Function *Strex = Intrinsic::getDeclaration(M, Int); 13934 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 13935 13936 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 13937 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 13938 if (!Subtarget->isLittle()) 13939 std::swap(Lo, Hi); 13940 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13941 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 13942 } 13943 13944 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 13945 Type *Tys[] = { Addr->getType() }; 13946 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 13947 13948 return Builder.CreateCall( 13949 Strex, {Builder.CreateZExtOrBitCast( 13950 Val, Strex->getFunctionType()->getParamType(0)), 13951 Addr}); 13952 } 13953 13954 /// A helper function for determining the number of interleaved accesses we 13955 /// will generate when lowering accesses of the given type. 13956 unsigned 13957 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 13958 const DataLayout &DL) const { 13959 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 13960 } 13961 13962 bool ARMTargetLowering::isLegalInterleavedAccessType( 13963 VectorType *VecTy, const DataLayout &DL) const { 13964 13965 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 13966 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 13967 13968 // Ensure the vector doesn't have f16 elements. Even though we could do an 13969 // i16 vldN, we can't hold the f16 vectors and will end up converting via 13970 // f32. 13971 if (VecTy->getElementType()->isHalfTy()) 13972 return false; 13973 13974 // Ensure the number of vector elements is greater than 1. 13975 if (VecTy->getNumElements() < 2) 13976 return false; 13977 13978 // Ensure the element type is legal. 13979 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 13980 return false; 13981 13982 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 13983 // 128 will be split into multiple interleaved accesses. 13984 return VecSize == 64 || VecSize % 128 == 0; 13985 } 13986 13987 /// \brief Lower an interleaved load into a vldN intrinsic. 13988 /// 13989 /// E.g. Lower an interleaved load (Factor = 2): 13990 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 13991 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 13992 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 13993 /// 13994 /// Into: 13995 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 13996 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 13997 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 13998 bool ARMTargetLowering::lowerInterleavedLoad( 13999 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 14000 ArrayRef<unsigned> Indices, unsigned Factor) const { 14001 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14002 "Invalid interleave factor"); 14003 assert(!Shuffles.empty() && "Empty shufflevector input"); 14004 assert(Shuffles.size() == Indices.size() && 14005 "Unmatched number of shufflevectors and indices"); 14006 14007 VectorType *VecTy = Shuffles[0]->getType(); 14008 Type *EltTy = VecTy->getVectorElementType(); 14009 14010 const DataLayout &DL = LI->getModule()->getDataLayout(); 14011 14012 // Skip if we do not have NEON and skip illegal vector types. We can 14013 // "legalize" wide vector types into multiple interleaved accesses as long as 14014 // the vector types are divisible by 128. 14015 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 14016 return false; 14017 14018 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 14019 14020 // A pointer vector can not be the return type of the ldN intrinsics. Need to 14021 // load integer vectors first and then convert to pointer vectors. 14022 if (EltTy->isPointerTy()) 14023 VecTy = 14024 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 14025 14026 IRBuilder<> Builder(LI); 14027 14028 // The base address of the load. 14029 Value *BaseAddr = LI->getPointerOperand(); 14030 14031 if (NumLoads > 1) { 14032 // If we're going to generate more than one load, reset the sub-vector type 14033 // to something legal. 14034 VecTy = VectorType::get(VecTy->getVectorElementType(), 14035 VecTy->getVectorNumElements() / NumLoads); 14036 14037 // We will compute the pointer operand of each load from the original base 14038 // address using GEPs. Cast the base address to a pointer to the scalar 14039 // element type. 14040 BaseAddr = Builder.CreateBitCast( 14041 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 14042 LI->getPointerAddressSpace())); 14043 } 14044 14045 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 14046 14047 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 14048 Type *Tys[] = {VecTy, Int8Ptr}; 14049 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 14050 Intrinsic::arm_neon_vld3, 14051 Intrinsic::arm_neon_vld4}; 14052 Function *VldnFunc = 14053 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 14054 14055 // Holds sub-vectors extracted from the load intrinsic return values. The 14056 // sub-vectors are associated with the shufflevector instructions they will 14057 // replace. 14058 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 14059 14060 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 14061 // If we're generating more than one load, compute the base address of 14062 // subsequent loads as an offset from the previous. 14063 if (LoadCount > 0) 14064 BaseAddr = Builder.CreateConstGEP1_32( 14065 BaseAddr, VecTy->getVectorNumElements() * Factor); 14066 14067 SmallVector<Value *, 2> Ops; 14068 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14069 Ops.push_back(Builder.getInt32(LI->getAlignment())); 14070 14071 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 14072 14073 // Replace uses of each shufflevector with the corresponding vector loaded 14074 // by ldN. 14075 for (unsigned i = 0; i < Shuffles.size(); i++) { 14076 ShuffleVectorInst *SV = Shuffles[i]; 14077 unsigned Index = Indices[i]; 14078 14079 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 14080 14081 // Convert the integer vector to pointer vector if the element is pointer. 14082 if (EltTy->isPointerTy()) 14083 SubVec = Builder.CreateIntToPtr( 14084 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 14085 VecTy->getVectorNumElements())); 14086 14087 SubVecs[SV].push_back(SubVec); 14088 } 14089 } 14090 14091 // Replace uses of the shufflevector instructions with the sub-vectors 14092 // returned by the load intrinsic. If a shufflevector instruction is 14093 // associated with more than one sub-vector, those sub-vectors will be 14094 // concatenated into a single wide vector. 14095 for (ShuffleVectorInst *SVI : Shuffles) { 14096 auto &SubVec = SubVecs[SVI]; 14097 auto *WideVec = 14098 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 14099 SVI->replaceAllUsesWith(WideVec); 14100 } 14101 14102 return true; 14103 } 14104 14105 /// \brief Lower an interleaved store into a vstN intrinsic. 14106 /// 14107 /// E.g. Lower an interleaved store (Factor = 3): 14108 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 14109 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 14110 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 14111 /// 14112 /// Into: 14113 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 14114 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 14115 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 14116 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14117 /// 14118 /// Note that the new shufflevectors will be removed and we'll only generate one 14119 /// vst3 instruction in CodeGen. 14120 /// 14121 /// Example for a more general valid mask (Factor 3). Lower: 14122 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 14123 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 14124 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 14125 /// 14126 /// Into: 14127 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 14128 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 14129 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 14130 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14131 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 14132 ShuffleVectorInst *SVI, 14133 unsigned Factor) const { 14134 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14135 "Invalid interleave factor"); 14136 14137 VectorType *VecTy = SVI->getType(); 14138 assert(VecTy->getVectorNumElements() % Factor == 0 && 14139 "Invalid interleaved store"); 14140 14141 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 14142 Type *EltTy = VecTy->getVectorElementType(); 14143 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 14144 14145 const DataLayout &DL = SI->getModule()->getDataLayout(); 14146 14147 // Skip if we do not have NEON and skip illegal vector types. We can 14148 // "legalize" wide vector types into multiple interleaved accesses as long as 14149 // the vector types are divisible by 128. 14150 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 14151 return false; 14152 14153 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 14154 14155 Value *Op0 = SVI->getOperand(0); 14156 Value *Op1 = SVI->getOperand(1); 14157 IRBuilder<> Builder(SI); 14158 14159 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 14160 // vectors to integer vectors. 14161 if (EltTy->isPointerTy()) { 14162 Type *IntTy = DL.getIntPtrType(EltTy); 14163 14164 // Convert to the corresponding integer vector. 14165 Type *IntVecTy = 14166 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 14167 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 14168 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 14169 14170 SubVecTy = VectorType::get(IntTy, LaneLen); 14171 } 14172 14173 // The base address of the store. 14174 Value *BaseAddr = SI->getPointerOperand(); 14175 14176 if (NumStores > 1) { 14177 // If we're going to generate more than one store, reset the lane length 14178 // and sub-vector type to something legal. 14179 LaneLen /= NumStores; 14180 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 14181 14182 // We will compute the pointer operand of each store from the original base 14183 // address using GEPs. Cast the base address to a pointer to the scalar 14184 // element type. 14185 BaseAddr = Builder.CreateBitCast( 14186 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 14187 SI->getPointerAddressSpace())); 14188 } 14189 14190 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 14191 14192 auto Mask = SVI->getShuffleMask(); 14193 14194 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 14195 Type *Tys[] = {Int8Ptr, SubVecTy}; 14196 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 14197 Intrinsic::arm_neon_vst3, 14198 Intrinsic::arm_neon_vst4}; 14199 14200 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 14201 // If we generating more than one store, we compute the base address of 14202 // subsequent stores as an offset from the previous. 14203 if (StoreCount > 0) 14204 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 14205 14206 SmallVector<Value *, 6> Ops; 14207 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14208 14209 Function *VstNFunc = 14210 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 14211 14212 // Split the shufflevector operands into sub vectors for the new vstN call. 14213 for (unsigned i = 0; i < Factor; i++) { 14214 unsigned IdxI = StoreCount * LaneLen * Factor + i; 14215 if (Mask[IdxI] >= 0) { 14216 Ops.push_back(Builder.CreateShuffleVector( 14217 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 14218 } else { 14219 unsigned StartMask = 0; 14220 for (unsigned j = 1; j < LaneLen; j++) { 14221 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 14222 if (Mask[IdxJ * Factor + IdxI] >= 0) { 14223 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 14224 break; 14225 } 14226 } 14227 // Note: If all elements in a chunk are undefs, StartMask=0! 14228 // Note: Filling undef gaps with random elements is ok, since 14229 // those elements were being written anyway (with undefs). 14230 // In the case of all undefs we're defaulting to using elems from 0 14231 // Note: StartMask cannot be negative, it's checked in 14232 // isReInterleaveMask 14233 Ops.push_back(Builder.CreateShuffleVector( 14234 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 14235 } 14236 } 14237 14238 Ops.push_back(Builder.getInt32(SI->getAlignment())); 14239 Builder.CreateCall(VstNFunc, Ops); 14240 } 14241 return true; 14242 } 14243 14244 enum HABaseType { 14245 HA_UNKNOWN = 0, 14246 HA_FLOAT, 14247 HA_DOUBLE, 14248 HA_VECT64, 14249 HA_VECT128 14250 }; 14251 14252 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 14253 uint64_t &Members) { 14254 if (auto *ST = dyn_cast<StructType>(Ty)) { 14255 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 14256 uint64_t SubMembers = 0; 14257 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 14258 return false; 14259 Members += SubMembers; 14260 } 14261 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 14262 uint64_t SubMembers = 0; 14263 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 14264 return false; 14265 Members += SubMembers * AT->getNumElements(); 14266 } else if (Ty->isFloatTy()) { 14267 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 14268 return false; 14269 Members = 1; 14270 Base = HA_FLOAT; 14271 } else if (Ty->isDoubleTy()) { 14272 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 14273 return false; 14274 Members = 1; 14275 Base = HA_DOUBLE; 14276 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 14277 Members = 1; 14278 switch (Base) { 14279 case HA_FLOAT: 14280 case HA_DOUBLE: 14281 return false; 14282 case HA_VECT64: 14283 return VT->getBitWidth() == 64; 14284 case HA_VECT128: 14285 return VT->getBitWidth() == 128; 14286 case HA_UNKNOWN: 14287 switch (VT->getBitWidth()) { 14288 case 64: 14289 Base = HA_VECT64; 14290 return true; 14291 case 128: 14292 Base = HA_VECT128; 14293 return true; 14294 default: 14295 return false; 14296 } 14297 } 14298 } 14299 14300 return (Members > 0 && Members <= 4); 14301 } 14302 14303 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 14304 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 14305 /// passing according to AAPCS rules. 14306 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 14307 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 14308 if (getEffectiveCallingConv(CallConv, isVarArg) != 14309 CallingConv::ARM_AAPCS_VFP) 14310 return false; 14311 14312 HABaseType Base = HA_UNKNOWN; 14313 uint64_t Members = 0; 14314 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 14315 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 14316 14317 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 14318 return IsHA || IsIntArray; 14319 } 14320 14321 unsigned ARMTargetLowering::getExceptionPointerRegister( 14322 const Constant *PersonalityFn) const { 14323 // Platforms which do not use SjLj EH may return values in these registers 14324 // via the personality function. 14325 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 14326 } 14327 14328 unsigned ARMTargetLowering::getExceptionSelectorRegister( 14329 const Constant *PersonalityFn) const { 14330 // Platforms which do not use SjLj EH may return values in these registers 14331 // via the personality function. 14332 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 14333 } 14334 14335 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14336 // Update IsSplitCSR in ARMFunctionInfo. 14337 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 14338 AFI->setIsSplitCSR(true); 14339 } 14340 14341 void ARMTargetLowering::insertCopiesSplitCSR( 14342 MachineBasicBlock *Entry, 14343 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14344 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 14345 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14346 if (!IStart) 14347 return; 14348 14349 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 14350 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14351 MachineBasicBlock::iterator MBBI = Entry->begin(); 14352 for (const MCPhysReg *I = IStart; *I; ++I) { 14353 const TargetRegisterClass *RC = nullptr; 14354 if (ARM::GPRRegClass.contains(*I)) 14355 RC = &ARM::GPRRegClass; 14356 else if (ARM::DPRRegClass.contains(*I)) 14357 RC = &ARM::DPRRegClass; 14358 else 14359 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14360 14361 unsigned NewVR = MRI->createVirtualRegister(RC); 14362 // Create copy from CSR to a virtual register. 14363 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14364 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14365 // nounwind. If we want to generalize this later, we may need to emit 14366 // CFI pseudo-instructions. 14367 assert(Entry->getParent()->getFunction().hasFnAttribute( 14368 Attribute::NoUnwind) && 14369 "Function should be nounwind in insertCopiesSplitCSR!"); 14370 Entry->addLiveIn(*I); 14371 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14372 .addReg(*I); 14373 14374 // Insert the copy-back instructions right before the terminator. 14375 for (auto *Exit : Exits) 14376 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14377 TII->get(TargetOpcode::COPY), *I) 14378 .addReg(NewVR); 14379 } 14380 } 14381 14382 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 14383 MF.getFrameInfo().computeMaxCallFrameSize(MF); 14384 TargetLoweringBase::finalizeLowering(MF); 14385 } 14386