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 if (Subtarget->hasFullFP16()) { 526 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 527 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 528 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 529 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 530 } 531 532 for (MVT VT : MVT::vector_valuetypes()) { 533 for (MVT InnerVT : MVT::vector_valuetypes()) { 534 setTruncStoreAction(VT, InnerVT, Expand); 535 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 536 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 537 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 538 } 539 540 setOperationAction(ISD::MULHS, VT, Expand); 541 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 542 setOperationAction(ISD::MULHU, VT, Expand); 543 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 544 545 setOperationAction(ISD::BSWAP, VT, Expand); 546 } 547 548 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 549 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 550 551 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 552 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 553 554 if (Subtarget->hasNEON()) { 555 addDRTypeForNEON(MVT::v2f32); 556 addDRTypeForNEON(MVT::v8i8); 557 addDRTypeForNEON(MVT::v4i16); 558 addDRTypeForNEON(MVT::v2i32); 559 addDRTypeForNEON(MVT::v1i64); 560 561 addQRTypeForNEON(MVT::v4f32); 562 addQRTypeForNEON(MVT::v2f64); 563 addQRTypeForNEON(MVT::v16i8); 564 addQRTypeForNEON(MVT::v8i16); 565 addQRTypeForNEON(MVT::v4i32); 566 addQRTypeForNEON(MVT::v2i64); 567 568 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 569 // neither Neon nor VFP support any arithmetic operations on it. 570 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 571 // supported for v4f32. 572 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 573 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 574 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 575 // FIXME: Code duplication: FDIV and FREM are expanded always, see 576 // ARMTargetLowering::addTypeForNEON method for details. 577 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 578 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 579 // FIXME: Create unittest. 580 // In another words, find a way when "copysign" appears in DAG with vector 581 // operands. 582 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 583 // FIXME: Code duplication: SETCC has custom operation action, see 584 // ARMTargetLowering::addTypeForNEON method for details. 585 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 586 // FIXME: Create unittest for FNEG and for FABS. 587 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 588 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 589 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 590 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 591 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 592 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 593 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 594 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 595 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 596 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 597 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 598 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 599 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 600 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 601 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 602 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 603 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 604 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 605 606 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 607 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 608 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 609 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 610 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 611 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 612 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 613 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 614 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 615 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 616 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 617 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 618 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 619 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 620 621 // Mark v2f32 intrinsics. 622 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 623 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 624 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 625 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 626 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 627 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 628 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 629 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 630 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 631 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 632 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 633 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 634 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 635 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 636 637 // Neon does not support some operations on v1i64 and v2i64 types. 638 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 639 // Custom handling for some quad-vector types to detect VMULL. 640 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 641 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 642 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 643 // Custom handling for some vector types to avoid expensive expansions 644 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 645 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 646 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 647 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 648 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 649 // a destination type that is wider than the source, and nor does 650 // it have a FP_TO_[SU]INT instruction with a narrower destination than 651 // source. 652 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 653 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 654 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 655 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 656 657 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 658 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 659 660 // NEON does not have single instruction CTPOP for vectors with element 661 // types wider than 8-bits. However, custom lowering can leverage the 662 // v8i8/v16i8 vcnt instruction. 663 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 664 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 665 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 666 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 667 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 668 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 669 670 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 671 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 672 673 // NEON does not have single instruction CTTZ for vectors. 674 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 675 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 676 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 677 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 678 679 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 680 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 681 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 682 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 683 684 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 685 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 686 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 687 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 688 689 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 690 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 691 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 692 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 693 694 // NEON only has FMA instructions as of VFP4. 695 if (!Subtarget->hasVFP4()) { 696 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 697 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 698 } 699 700 setTargetDAGCombine(ISD::INTRINSIC_VOID); 701 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 702 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 703 setTargetDAGCombine(ISD::SHL); 704 setTargetDAGCombine(ISD::SRL); 705 setTargetDAGCombine(ISD::SRA); 706 setTargetDAGCombine(ISD::SIGN_EXTEND); 707 setTargetDAGCombine(ISD::ZERO_EXTEND); 708 setTargetDAGCombine(ISD::ANY_EXTEND); 709 setTargetDAGCombine(ISD::BUILD_VECTOR); 710 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 711 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 712 setTargetDAGCombine(ISD::STORE); 713 setTargetDAGCombine(ISD::FP_TO_SINT); 714 setTargetDAGCombine(ISD::FP_TO_UINT); 715 setTargetDAGCombine(ISD::FDIV); 716 setTargetDAGCombine(ISD::LOAD); 717 718 // It is legal to extload from v4i8 to v4i16 or v4i32. 719 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 720 MVT::v2i32}) { 721 for (MVT VT : MVT::integer_vector_valuetypes()) { 722 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 723 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 724 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 725 } 726 } 727 } 728 729 if (Subtarget->isFPOnlySP()) { 730 // When targeting a floating-point unit with only single-precision 731 // operations, f64 is legal for the few double-precision instructions which 732 // are present However, no double-precision operations other than moves, 733 // loads and stores are provided by the hardware. 734 setOperationAction(ISD::FADD, MVT::f64, Expand); 735 setOperationAction(ISD::FSUB, MVT::f64, Expand); 736 setOperationAction(ISD::FMUL, MVT::f64, Expand); 737 setOperationAction(ISD::FMA, MVT::f64, Expand); 738 setOperationAction(ISD::FDIV, MVT::f64, Expand); 739 setOperationAction(ISD::FREM, MVT::f64, Expand); 740 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 741 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 742 setOperationAction(ISD::FNEG, MVT::f64, Expand); 743 setOperationAction(ISD::FABS, MVT::f64, Expand); 744 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 745 setOperationAction(ISD::FSIN, MVT::f64, Expand); 746 setOperationAction(ISD::FCOS, MVT::f64, Expand); 747 setOperationAction(ISD::FPOW, MVT::f64, Expand); 748 setOperationAction(ISD::FLOG, MVT::f64, Expand); 749 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 750 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 751 setOperationAction(ISD::FEXP, MVT::f64, Expand); 752 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 753 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 754 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 755 setOperationAction(ISD::FRINT, MVT::f64, Expand); 756 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 757 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 758 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 759 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 760 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 761 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 762 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 763 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 764 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 765 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 766 } 767 768 computeRegisterProperties(Subtarget->getRegisterInfo()); 769 770 // ARM does not have floating-point extending loads. 771 for (MVT VT : MVT::fp_valuetypes()) { 772 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 773 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 774 } 775 776 // ... or truncating stores 777 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 778 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 779 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 780 781 // ARM does not have i1 sign extending load. 782 for (MVT VT : MVT::integer_valuetypes()) 783 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 784 785 // ARM supports all 4 flavors of integer indexed load / store. 786 if (!Subtarget->isThumb1Only()) { 787 for (unsigned im = (unsigned)ISD::PRE_INC; 788 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 789 setIndexedLoadAction(im, MVT::i1, Legal); 790 setIndexedLoadAction(im, MVT::i8, Legal); 791 setIndexedLoadAction(im, MVT::i16, Legal); 792 setIndexedLoadAction(im, MVT::i32, Legal); 793 setIndexedStoreAction(im, MVT::i1, Legal); 794 setIndexedStoreAction(im, MVT::i8, Legal); 795 setIndexedStoreAction(im, MVT::i16, Legal); 796 setIndexedStoreAction(im, MVT::i32, Legal); 797 } 798 } else { 799 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 800 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 801 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 802 } 803 804 setOperationAction(ISD::SADDO, MVT::i32, Custom); 805 setOperationAction(ISD::UADDO, MVT::i32, Custom); 806 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 807 setOperationAction(ISD::USUBO, MVT::i32, Custom); 808 809 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 810 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 811 812 // i64 operation support. 813 setOperationAction(ISD::MUL, MVT::i64, Expand); 814 setOperationAction(ISD::MULHU, MVT::i32, Expand); 815 if (Subtarget->isThumb1Only()) { 816 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 817 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 818 } 819 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 820 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 821 setOperationAction(ISD::MULHS, MVT::i32, Expand); 822 823 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 824 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 825 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 826 setOperationAction(ISD::SRL, MVT::i64, Custom); 827 setOperationAction(ISD::SRA, MVT::i64, Custom); 828 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 829 830 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 831 if (Subtarget->isThumb1Only()) { 832 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 833 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 834 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 835 } 836 837 setOperationAction(ISD::ADDC, MVT::i32, Custom); 838 setOperationAction(ISD::ADDE, MVT::i32, Custom); 839 setOperationAction(ISD::SUBC, MVT::i32, Custom); 840 setOperationAction(ISD::SUBE, MVT::i32, Custom); 841 842 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 843 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 844 845 // ARM does not have ROTL. 846 setOperationAction(ISD::ROTL, MVT::i32, Expand); 847 for (MVT VT : MVT::vector_valuetypes()) { 848 setOperationAction(ISD::ROTL, VT, Expand); 849 setOperationAction(ISD::ROTR, VT, Expand); 850 } 851 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 852 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 853 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 854 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 855 856 // @llvm.readcyclecounter requires the Performance Monitors extension. 857 // Default to the 0 expansion on unsupported platforms. 858 // FIXME: Technically there are older ARM CPUs that have 859 // implementation-specific ways of obtaining this information. 860 if (Subtarget->hasPerfMon()) 861 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 862 863 // Only ARMv6 has BSWAP. 864 if (!Subtarget->hasV6Ops()) 865 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 866 867 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 868 : Subtarget->hasDivideInARMMode(); 869 if (!hasDivide) { 870 // These are expanded into libcalls if the cpu doesn't have HW divider. 871 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 872 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 873 } 874 875 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 876 setOperationAction(ISD::SDIV, MVT::i32, Custom); 877 setOperationAction(ISD::UDIV, MVT::i32, Custom); 878 879 setOperationAction(ISD::SDIV, MVT::i64, Custom); 880 setOperationAction(ISD::UDIV, MVT::i64, Custom); 881 } 882 883 setOperationAction(ISD::SREM, MVT::i32, Expand); 884 setOperationAction(ISD::UREM, MVT::i32, Expand); 885 886 // Register based DivRem for AEABI (RTABI 4.2) 887 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 888 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 889 Subtarget->isTargetWindows()) { 890 setOperationAction(ISD::SREM, MVT::i64, Custom); 891 setOperationAction(ISD::UREM, MVT::i64, Custom); 892 HasStandaloneRem = false; 893 894 if (Subtarget->isTargetWindows()) { 895 const struct { 896 const RTLIB::Libcall Op; 897 const char * const Name; 898 const CallingConv::ID CC; 899 } LibraryCalls[] = { 900 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 901 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 902 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 903 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 904 905 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 906 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 907 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 908 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 909 }; 910 911 for (const auto &LC : LibraryCalls) { 912 setLibcallName(LC.Op, LC.Name); 913 setLibcallCallingConv(LC.Op, LC.CC); 914 } 915 } else { 916 const struct { 917 const RTLIB::Libcall Op; 918 const char * const Name; 919 const CallingConv::ID CC; 920 } LibraryCalls[] = { 921 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 922 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 923 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 924 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 925 926 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 927 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 928 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 929 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 930 }; 931 932 for (const auto &LC : LibraryCalls) { 933 setLibcallName(LC.Op, LC.Name); 934 setLibcallCallingConv(LC.Op, LC.CC); 935 } 936 } 937 938 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 939 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 940 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 941 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 942 } else { 943 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 944 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 945 } 946 947 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 948 for (auto &VT : {MVT::f32, MVT::f64}) 949 setOperationAction(ISD::FPOWI, VT, Custom); 950 951 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 952 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 953 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 954 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 955 956 setOperationAction(ISD::TRAP, MVT::Other, Legal); 957 958 // Use the default implementation. 959 setOperationAction(ISD::VASTART, MVT::Other, Custom); 960 setOperationAction(ISD::VAARG, MVT::Other, Expand); 961 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 962 setOperationAction(ISD::VAEND, MVT::Other, Expand); 963 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 964 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 965 966 if (Subtarget->isTargetWindows()) 967 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 968 else 969 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 970 971 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 972 // the default expansion. 973 InsertFencesForAtomic = false; 974 if (Subtarget->hasAnyDataBarrier() && 975 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 976 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 977 // to ldrex/strex loops already. 978 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 979 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 980 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 981 982 // On v8, we have particularly efficient implementations of atomic fences 983 // if they can be combined with nearby atomic loads and stores. 984 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 985 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 986 InsertFencesForAtomic = true; 987 } 988 } else { 989 // If there's anything we can use as a barrier, go through custom lowering 990 // for ATOMIC_FENCE. 991 // If target has DMB in thumb, Fences can be inserted. 992 if (Subtarget->hasDataBarrier()) 993 InsertFencesForAtomic = true; 994 995 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 996 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 997 998 // Set them all for expansion, which will force libcalls. 999 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1000 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1001 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1002 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1003 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1004 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1005 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1006 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1007 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1008 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1009 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1010 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1011 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1012 // Unordered/Monotonic case. 1013 if (!InsertFencesForAtomic) { 1014 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1015 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1016 } 1017 } 1018 1019 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1020 1021 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1022 if (!Subtarget->hasV6Ops()) { 1023 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1024 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1025 } 1026 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1027 1028 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1029 !Subtarget->isThumb1Only()) { 1030 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1031 // iff target supports vfp2. 1032 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1033 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1034 } 1035 1036 // We want to custom lower some of our intrinsics. 1037 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1038 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1039 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1040 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1041 if (Subtarget->useSjLjEH()) 1042 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1043 1044 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1045 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1046 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1047 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1048 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1049 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1050 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1051 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1052 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1053 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1054 1055 // Thumb-1 cannot currently select ARMISD::SUBE. 1056 if (!Subtarget->isThumb1Only()) 1057 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 1058 1059 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1060 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1061 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1062 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1063 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1064 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1065 1066 // We don't support sin/cos/fmod/copysign/pow 1067 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1068 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1069 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1070 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1071 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1072 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1073 setOperationAction(ISD::FREM, MVT::f64, Expand); 1074 setOperationAction(ISD::FREM, MVT::f32, Expand); 1075 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1076 !Subtarget->isThumb1Only()) { 1077 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1078 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1079 } 1080 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1081 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1082 1083 if (!Subtarget->hasVFP4()) { 1084 setOperationAction(ISD::FMA, MVT::f64, Expand); 1085 setOperationAction(ISD::FMA, MVT::f32, Expand); 1086 } 1087 1088 // Various VFP goodness 1089 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1090 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1091 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1092 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1093 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1094 } 1095 1096 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1097 if (!Subtarget->hasFP16()) { 1098 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1099 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1100 } 1101 } 1102 1103 // Use __sincos_stret if available. 1104 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1105 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1106 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1107 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1108 } 1109 1110 // FP-ARMv8 implements a lot of rounding-like FP operations. 1111 if (Subtarget->hasFPARMv8()) { 1112 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1113 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1114 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1115 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1116 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1117 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1118 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1119 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1120 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1121 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1122 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1123 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1124 1125 if (!Subtarget->isFPOnlySP()) { 1126 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1127 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1128 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1129 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1130 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1131 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1132 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1133 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1134 } 1135 } 1136 1137 if (Subtarget->hasNEON()) { 1138 // vmin and vmax aren't available in a scalar form, so we use 1139 // a NEON instruction with an undef lane instead. 1140 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1141 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1142 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1143 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1144 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1145 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1146 } 1147 1148 // We have target-specific dag combine patterns for the following nodes: 1149 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1150 setTargetDAGCombine(ISD::ADD); 1151 setTargetDAGCombine(ISD::SUB); 1152 setTargetDAGCombine(ISD::MUL); 1153 setTargetDAGCombine(ISD::AND); 1154 setTargetDAGCombine(ISD::OR); 1155 setTargetDAGCombine(ISD::XOR); 1156 1157 if (Subtarget->hasV6Ops()) 1158 setTargetDAGCombine(ISD::SRL); 1159 1160 setStackPointerRegisterToSaveRestore(ARM::SP); 1161 1162 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1163 !Subtarget->hasVFP2()) 1164 setSchedulingPreference(Sched::RegPressure); 1165 else 1166 setSchedulingPreference(Sched::Hybrid); 1167 1168 //// temporary - rewrite interface to use type 1169 MaxStoresPerMemset = 8; 1170 MaxStoresPerMemsetOptSize = 4; 1171 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1172 MaxStoresPerMemcpyOptSize = 2; 1173 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1174 MaxStoresPerMemmoveOptSize = 2; 1175 1176 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1177 // are at least 4 bytes aligned. 1178 setMinStackArgumentAlignment(4); 1179 1180 // Prefer likely predicted branches to selects on out-of-order cores. 1181 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1182 1183 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1184 } 1185 1186 bool ARMTargetLowering::useSoftFloat() const { 1187 return Subtarget->useSoftFloat(); 1188 } 1189 1190 // FIXME: It might make sense to define the representative register class as the 1191 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1192 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1193 // SPR's representative would be DPR_VFP2. This should work well if register 1194 // pressure tracking were modified such that a register use would increment the 1195 // pressure of the register class's representative and all of it's super 1196 // classes' representatives transitively. We have not implemented this because 1197 // of the difficulty prior to coalescing of modeling operand register classes 1198 // due to the common occurrence of cross class copies and subregister insertions 1199 // and extractions. 1200 std::pair<const TargetRegisterClass *, uint8_t> 1201 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1202 MVT VT) const { 1203 const TargetRegisterClass *RRC = nullptr; 1204 uint8_t Cost = 1; 1205 switch (VT.SimpleTy) { 1206 default: 1207 return TargetLowering::findRepresentativeClass(TRI, VT); 1208 // Use DPR as representative register class for all floating point 1209 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1210 // the cost is 1 for both f32 and f64. 1211 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1212 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1213 RRC = &ARM::DPRRegClass; 1214 // When NEON is used for SP, only half of the register file is available 1215 // because operations that define both SP and DP results will be constrained 1216 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1217 // coalescing by double-counting the SP regs. See the FIXME above. 1218 if (Subtarget->useNEONForSinglePrecisionFP()) 1219 Cost = 2; 1220 break; 1221 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1222 case MVT::v4f32: case MVT::v2f64: 1223 RRC = &ARM::DPRRegClass; 1224 Cost = 2; 1225 break; 1226 case MVT::v4i64: 1227 RRC = &ARM::DPRRegClass; 1228 Cost = 4; 1229 break; 1230 case MVT::v8i64: 1231 RRC = &ARM::DPRRegClass; 1232 Cost = 8; 1233 break; 1234 } 1235 return std::make_pair(RRC, Cost); 1236 } 1237 1238 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1239 switch ((ARMISD::NodeType)Opcode) { 1240 case ARMISD::FIRST_NUMBER: break; 1241 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1242 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1243 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1244 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1245 case ARMISD::CALL: return "ARMISD::CALL"; 1246 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1247 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1248 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1249 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1250 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1251 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1252 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1253 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1254 case ARMISD::CMP: return "ARMISD::CMP"; 1255 case ARMISD::CMN: return "ARMISD::CMN"; 1256 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1257 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1258 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1259 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1260 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1261 1262 case ARMISD::CMOV: return "ARMISD::CMOV"; 1263 1264 case ARMISD::SSAT: return "ARMISD::SSAT"; 1265 case ARMISD::USAT: return "ARMISD::USAT"; 1266 1267 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1268 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1269 case ARMISD::RRX: return "ARMISD::RRX"; 1270 1271 case ARMISD::ADDC: return "ARMISD::ADDC"; 1272 case ARMISD::ADDE: return "ARMISD::ADDE"; 1273 case ARMISD::SUBC: return "ARMISD::SUBC"; 1274 case ARMISD::SUBE: return "ARMISD::SUBE"; 1275 1276 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1277 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1278 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1279 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1280 1281 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1282 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1283 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1284 1285 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1286 1287 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1288 1289 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1290 1291 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1292 1293 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1294 1295 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1296 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1297 1298 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1299 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1300 case ARMISD::VCGE: return "ARMISD::VCGE"; 1301 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1302 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1303 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1304 case ARMISD::VCGT: return "ARMISD::VCGT"; 1305 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1306 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1307 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1308 case ARMISD::VTST: return "ARMISD::VTST"; 1309 1310 case ARMISD::VSHL: return "ARMISD::VSHL"; 1311 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1312 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1313 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1314 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1315 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1316 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1317 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1318 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1319 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1320 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1321 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1322 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1323 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1324 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1325 case ARMISD::VSLI: return "ARMISD::VSLI"; 1326 case ARMISD::VSRI: return "ARMISD::VSRI"; 1327 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1328 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1329 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1330 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1331 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1332 case ARMISD::VDUP: return "ARMISD::VDUP"; 1333 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1334 case ARMISD::VEXT: return "ARMISD::VEXT"; 1335 case ARMISD::VREV64: return "ARMISD::VREV64"; 1336 case ARMISD::VREV32: return "ARMISD::VREV32"; 1337 case ARMISD::VREV16: return "ARMISD::VREV16"; 1338 case ARMISD::VZIP: return "ARMISD::VZIP"; 1339 case ARMISD::VUZP: return "ARMISD::VUZP"; 1340 case ARMISD::VTRN: return "ARMISD::VTRN"; 1341 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1342 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1343 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1344 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1345 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1346 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1347 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1348 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1349 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1350 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1351 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1352 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1353 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1354 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1355 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1356 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1357 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1358 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1359 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1360 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1361 case ARMISD::BFI: return "ARMISD::BFI"; 1362 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1363 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1364 case ARMISD::VBSL: return "ARMISD::VBSL"; 1365 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1366 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1367 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1368 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1369 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1370 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1371 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1372 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1373 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1374 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1375 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1376 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1377 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1378 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1379 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1380 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1381 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1382 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1383 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1384 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1385 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1386 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1387 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1388 } 1389 return nullptr; 1390 } 1391 1392 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1393 EVT VT) const { 1394 if (!VT.isVector()) 1395 return getPointerTy(DL); 1396 return VT.changeVectorElementTypeToInteger(); 1397 } 1398 1399 /// getRegClassFor - Return the register class that should be used for the 1400 /// specified value type. 1401 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1402 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1403 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1404 // load / store 4 to 8 consecutive D registers. 1405 if (Subtarget->hasNEON()) { 1406 if (VT == MVT::v4i64) 1407 return &ARM::QQPRRegClass; 1408 if (VT == MVT::v8i64) 1409 return &ARM::QQQQPRRegClass; 1410 } 1411 return TargetLowering::getRegClassFor(VT); 1412 } 1413 1414 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1415 // source/dest is aligned and the copy size is large enough. We therefore want 1416 // to align such objects passed to memory intrinsics. 1417 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1418 unsigned &PrefAlign) const { 1419 if (!isa<MemIntrinsic>(CI)) 1420 return false; 1421 MinSize = 8; 1422 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1423 // cycle faster than 4-byte aligned LDM. 1424 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1425 return true; 1426 } 1427 1428 // Create a fast isel object. 1429 FastISel * 1430 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1431 const TargetLibraryInfo *libInfo) const { 1432 return ARM::createFastISel(funcInfo, libInfo); 1433 } 1434 1435 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1436 unsigned NumVals = N->getNumValues(); 1437 if (!NumVals) 1438 return Sched::RegPressure; 1439 1440 for (unsigned i = 0; i != NumVals; ++i) { 1441 EVT VT = N->getValueType(i); 1442 if (VT == MVT::Glue || VT == MVT::Other) 1443 continue; 1444 if (VT.isFloatingPoint() || VT.isVector()) 1445 return Sched::ILP; 1446 } 1447 1448 if (!N->isMachineOpcode()) 1449 return Sched::RegPressure; 1450 1451 // Load are scheduled for latency even if there instruction itinerary 1452 // is not available. 1453 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1454 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1455 1456 if (MCID.getNumDefs() == 0) 1457 return Sched::RegPressure; 1458 if (!Itins->isEmpty() && 1459 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1460 return Sched::ILP; 1461 1462 return Sched::RegPressure; 1463 } 1464 1465 //===----------------------------------------------------------------------===// 1466 // Lowering Code 1467 //===----------------------------------------------------------------------===// 1468 1469 static bool isSRL16(const SDValue &Op) { 1470 if (Op.getOpcode() != ISD::SRL) 1471 return false; 1472 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1473 return Const->getZExtValue() == 16; 1474 return false; 1475 } 1476 1477 static bool isSRA16(const SDValue &Op) { 1478 if (Op.getOpcode() != ISD::SRA) 1479 return false; 1480 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1481 return Const->getZExtValue() == 16; 1482 return false; 1483 } 1484 1485 static bool isSHL16(const SDValue &Op) { 1486 if (Op.getOpcode() != ISD::SHL) 1487 return false; 1488 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1489 return Const->getZExtValue() == 16; 1490 return false; 1491 } 1492 1493 // Check for a signed 16-bit value. We special case SRA because it makes it 1494 // more simple when also looking for SRAs that aren't sign extending a 1495 // smaller value. Without the check, we'd need to take extra care with 1496 // checking order for some operations. 1497 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1498 if (isSRA16(Op)) 1499 return isSHL16(Op.getOperand(0)); 1500 return DAG.ComputeNumSignBits(Op) == 17; 1501 } 1502 1503 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1504 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1505 switch (CC) { 1506 default: llvm_unreachable("Unknown condition code!"); 1507 case ISD::SETNE: return ARMCC::NE; 1508 case ISD::SETEQ: return ARMCC::EQ; 1509 case ISD::SETGT: return ARMCC::GT; 1510 case ISD::SETGE: return ARMCC::GE; 1511 case ISD::SETLT: return ARMCC::LT; 1512 case ISD::SETLE: return ARMCC::LE; 1513 case ISD::SETUGT: return ARMCC::HI; 1514 case ISD::SETUGE: return ARMCC::HS; 1515 case ISD::SETULT: return ARMCC::LO; 1516 case ISD::SETULE: return ARMCC::LS; 1517 } 1518 } 1519 1520 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1521 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1522 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1523 CondCode2 = ARMCC::AL; 1524 InvalidOnQNaN = true; 1525 switch (CC) { 1526 default: llvm_unreachable("Unknown FP condition!"); 1527 case ISD::SETEQ: 1528 case ISD::SETOEQ: 1529 CondCode = ARMCC::EQ; 1530 InvalidOnQNaN = false; 1531 break; 1532 case ISD::SETGT: 1533 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1534 case ISD::SETGE: 1535 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1536 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1537 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1538 case ISD::SETONE: 1539 CondCode = ARMCC::MI; 1540 CondCode2 = ARMCC::GT; 1541 InvalidOnQNaN = false; 1542 break; 1543 case ISD::SETO: CondCode = ARMCC::VC; break; 1544 case ISD::SETUO: CondCode = ARMCC::VS; break; 1545 case ISD::SETUEQ: 1546 CondCode = ARMCC::EQ; 1547 CondCode2 = ARMCC::VS; 1548 InvalidOnQNaN = false; 1549 break; 1550 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1551 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1552 case ISD::SETLT: 1553 case ISD::SETULT: CondCode = ARMCC::LT; break; 1554 case ISD::SETLE: 1555 case ISD::SETULE: CondCode = ARMCC::LE; break; 1556 case ISD::SETNE: 1557 case ISD::SETUNE: 1558 CondCode = ARMCC::NE; 1559 InvalidOnQNaN = false; 1560 break; 1561 } 1562 } 1563 1564 //===----------------------------------------------------------------------===// 1565 // Calling Convention Implementation 1566 //===----------------------------------------------------------------------===// 1567 1568 #include "ARMGenCallingConv.inc" 1569 1570 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1571 /// account presence of floating point hardware and calling convention 1572 /// limitations, such as support for variadic functions. 1573 CallingConv::ID 1574 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1575 bool isVarArg) const { 1576 switch (CC) { 1577 default: 1578 report_fatal_error("Unsupported calling convention"); 1579 case CallingConv::ARM_AAPCS: 1580 case CallingConv::ARM_APCS: 1581 case CallingConv::GHC: 1582 return CC; 1583 case CallingConv::PreserveMost: 1584 return CallingConv::PreserveMost; 1585 case CallingConv::ARM_AAPCS_VFP: 1586 case CallingConv::Swift: 1587 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1588 case CallingConv::C: 1589 if (!Subtarget->isAAPCS_ABI()) 1590 return CallingConv::ARM_APCS; 1591 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1592 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1593 !isVarArg) 1594 return CallingConv::ARM_AAPCS_VFP; 1595 else 1596 return CallingConv::ARM_AAPCS; 1597 case CallingConv::Fast: 1598 case CallingConv::CXX_FAST_TLS: 1599 if (!Subtarget->isAAPCS_ABI()) { 1600 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1601 return CallingConv::Fast; 1602 return CallingConv::ARM_APCS; 1603 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1604 return CallingConv::ARM_AAPCS_VFP; 1605 else 1606 return CallingConv::ARM_AAPCS; 1607 } 1608 } 1609 1610 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1611 bool isVarArg) const { 1612 return CCAssignFnForNode(CC, false, isVarArg); 1613 } 1614 1615 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1616 bool isVarArg) const { 1617 return CCAssignFnForNode(CC, true, isVarArg); 1618 } 1619 1620 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1621 /// CallingConvention. 1622 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1623 bool Return, 1624 bool isVarArg) const { 1625 switch (getEffectiveCallingConv(CC, isVarArg)) { 1626 default: 1627 report_fatal_error("Unsupported calling convention"); 1628 case CallingConv::ARM_APCS: 1629 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1630 case CallingConv::ARM_AAPCS: 1631 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1632 case CallingConv::ARM_AAPCS_VFP: 1633 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1634 case CallingConv::Fast: 1635 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1636 case CallingConv::GHC: 1637 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1638 case CallingConv::PreserveMost: 1639 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1640 } 1641 } 1642 1643 /// LowerCallResult - Lower the result values of a call into the 1644 /// appropriate copies out of appropriate physical registers. 1645 SDValue ARMTargetLowering::LowerCallResult( 1646 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1647 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1648 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1649 SDValue ThisVal) const { 1650 // Assign locations to each value returned by this call. 1651 SmallVector<CCValAssign, 16> RVLocs; 1652 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1653 *DAG.getContext()); 1654 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1655 1656 // Copy all of the result registers out of their specified physreg. 1657 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1658 CCValAssign VA = RVLocs[i]; 1659 1660 // Pass 'this' value directly from the argument to return value, to avoid 1661 // reg unit interference 1662 if (i == 0 && isThisReturn) { 1663 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1664 "unexpected return calling convention register assignment"); 1665 InVals.push_back(ThisVal); 1666 continue; 1667 } 1668 1669 SDValue Val; 1670 if (VA.needsCustom()) { 1671 // Handle f64 or half of a v2f64. 1672 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1673 InFlag); 1674 Chain = Lo.getValue(1); 1675 InFlag = Lo.getValue(2); 1676 VA = RVLocs[++i]; // skip ahead to next loc 1677 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1678 InFlag); 1679 Chain = Hi.getValue(1); 1680 InFlag = Hi.getValue(2); 1681 if (!Subtarget->isLittle()) 1682 std::swap (Lo, Hi); 1683 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1684 1685 if (VA.getLocVT() == MVT::v2f64) { 1686 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1687 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1688 DAG.getConstant(0, dl, MVT::i32)); 1689 1690 VA = RVLocs[++i]; // skip ahead to next loc 1691 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1692 Chain = Lo.getValue(1); 1693 InFlag = Lo.getValue(2); 1694 VA = RVLocs[++i]; // skip ahead to next loc 1695 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1696 Chain = Hi.getValue(1); 1697 InFlag = Hi.getValue(2); 1698 if (!Subtarget->isLittle()) 1699 std::swap (Lo, Hi); 1700 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1701 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1702 DAG.getConstant(1, dl, MVT::i32)); 1703 } 1704 } else { 1705 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1706 InFlag); 1707 Chain = Val.getValue(1); 1708 InFlag = Val.getValue(2); 1709 } 1710 1711 switch (VA.getLocInfo()) { 1712 default: llvm_unreachable("Unknown loc info!"); 1713 case CCValAssign::Full: break; 1714 case CCValAssign::BCvt: 1715 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1716 break; 1717 } 1718 1719 InVals.push_back(Val); 1720 } 1721 1722 return Chain; 1723 } 1724 1725 /// LowerMemOpCallTo - Store the argument to the stack. 1726 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1727 SDValue Arg, const SDLoc &dl, 1728 SelectionDAG &DAG, 1729 const CCValAssign &VA, 1730 ISD::ArgFlagsTy Flags) const { 1731 unsigned LocMemOffset = VA.getLocMemOffset(); 1732 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1733 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1734 StackPtr, PtrOff); 1735 return DAG.getStore( 1736 Chain, dl, Arg, PtrOff, 1737 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1738 } 1739 1740 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1741 SDValue Chain, SDValue &Arg, 1742 RegsToPassVector &RegsToPass, 1743 CCValAssign &VA, CCValAssign &NextVA, 1744 SDValue &StackPtr, 1745 SmallVectorImpl<SDValue> &MemOpChains, 1746 ISD::ArgFlagsTy Flags) const { 1747 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1748 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1749 unsigned id = Subtarget->isLittle() ? 0 : 1; 1750 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1751 1752 if (NextVA.isRegLoc()) 1753 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1754 else { 1755 assert(NextVA.isMemLoc()); 1756 if (!StackPtr.getNode()) 1757 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1758 getPointerTy(DAG.getDataLayout())); 1759 1760 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1761 dl, DAG, NextVA, 1762 Flags)); 1763 } 1764 } 1765 1766 /// LowerCall - Lowering a call into a callseq_start <- 1767 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1768 /// nodes. 1769 SDValue 1770 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1771 SmallVectorImpl<SDValue> &InVals) const { 1772 SelectionDAG &DAG = CLI.DAG; 1773 SDLoc &dl = CLI.DL; 1774 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1775 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1776 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1777 SDValue Chain = CLI.Chain; 1778 SDValue Callee = CLI.Callee; 1779 bool &isTailCall = CLI.IsTailCall; 1780 CallingConv::ID CallConv = CLI.CallConv; 1781 bool doesNotRet = CLI.DoesNotReturn; 1782 bool isVarArg = CLI.IsVarArg; 1783 1784 MachineFunction &MF = DAG.getMachineFunction(); 1785 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1786 bool isThisReturn = false; 1787 bool isSibCall = false; 1788 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 1789 1790 // Disable tail calls if they're not supported. 1791 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1792 isTailCall = false; 1793 1794 if (isTailCall) { 1795 // Check if it's really possible to do a tail call. 1796 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1797 isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(), 1798 Outs, OutVals, Ins, DAG); 1799 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1800 report_fatal_error("failed to perform tail call elimination on a call " 1801 "site marked musttail"); 1802 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1803 // detected sibcalls. 1804 if (isTailCall) { 1805 ++NumTailCalls; 1806 isSibCall = true; 1807 } 1808 } 1809 1810 // Analyze operands of the call, assigning locations to each operand. 1811 SmallVector<CCValAssign, 16> ArgLocs; 1812 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1813 *DAG.getContext()); 1814 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1815 1816 // Get a count of how many bytes are to be pushed on the stack. 1817 unsigned NumBytes = CCInfo.getNextStackOffset(); 1818 1819 // For tail calls, memory operands are available in our caller's stack. 1820 if (isSibCall) 1821 NumBytes = 0; 1822 1823 // Adjust the stack pointer for the new arguments... 1824 // These operations are automatically eliminated by the prolog/epilog pass 1825 if (!isSibCall) 1826 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 1827 1828 SDValue StackPtr = 1829 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1830 1831 RegsToPassVector RegsToPass; 1832 SmallVector<SDValue, 8> MemOpChains; 1833 1834 // Walk the register/memloc assignments, inserting copies/loads. In the case 1835 // of tail call optimization, arguments are handled later. 1836 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1837 i != e; 1838 ++i, ++realArgIdx) { 1839 CCValAssign &VA = ArgLocs[i]; 1840 SDValue Arg = OutVals[realArgIdx]; 1841 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1842 bool isByVal = Flags.isByVal(); 1843 1844 // Promote the value if needed. 1845 switch (VA.getLocInfo()) { 1846 default: llvm_unreachable("Unknown loc info!"); 1847 case CCValAssign::Full: break; 1848 case CCValAssign::SExt: 1849 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1850 break; 1851 case CCValAssign::ZExt: 1852 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1853 break; 1854 case CCValAssign::AExt: 1855 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1856 break; 1857 case CCValAssign::BCvt: 1858 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1859 break; 1860 } 1861 1862 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1863 if (VA.needsCustom()) { 1864 if (VA.getLocVT() == MVT::v2f64) { 1865 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1866 DAG.getConstant(0, dl, MVT::i32)); 1867 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1868 DAG.getConstant(1, dl, MVT::i32)); 1869 1870 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1871 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1872 1873 VA = ArgLocs[++i]; // skip ahead to next loc 1874 if (VA.isRegLoc()) { 1875 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1876 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1877 } else { 1878 assert(VA.isMemLoc()); 1879 1880 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1881 dl, DAG, VA, Flags)); 1882 } 1883 } else { 1884 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1885 StackPtr, MemOpChains, Flags); 1886 } 1887 } else if (VA.isRegLoc()) { 1888 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1889 Outs[0].VT == MVT::i32) { 1890 assert(VA.getLocVT() == MVT::i32 && 1891 "unexpected calling convention register assignment"); 1892 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1893 "unexpected use of 'returned'"); 1894 isThisReturn = true; 1895 } 1896 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1897 } else if (isByVal) { 1898 assert(VA.isMemLoc()); 1899 unsigned offset = 0; 1900 1901 // True if this byval aggregate will be split between registers 1902 // and memory. 1903 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1904 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1905 1906 if (CurByValIdx < ByValArgsCount) { 1907 1908 unsigned RegBegin, RegEnd; 1909 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1910 1911 EVT PtrVT = 1912 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1913 unsigned int i, j; 1914 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1915 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1916 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1917 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1918 MachinePointerInfo(), 1919 DAG.InferPtrAlignment(AddArg)); 1920 MemOpChains.push_back(Load.getValue(1)); 1921 RegsToPass.push_back(std::make_pair(j, Load)); 1922 } 1923 1924 // If parameter size outsides register area, "offset" value 1925 // helps us to calculate stack slot for remained part properly. 1926 offset = RegEnd - RegBegin; 1927 1928 CCInfo.nextInRegsParam(); 1929 } 1930 1931 if (Flags.getByValSize() > 4*offset) { 1932 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1933 unsigned LocMemOffset = VA.getLocMemOffset(); 1934 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1935 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1936 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1937 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1938 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1939 MVT::i32); 1940 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1941 MVT::i32); 1942 1943 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1944 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1945 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1946 Ops)); 1947 } 1948 } else if (!isSibCall) { 1949 assert(VA.isMemLoc()); 1950 1951 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1952 dl, DAG, VA, Flags)); 1953 } 1954 } 1955 1956 if (!MemOpChains.empty()) 1957 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1958 1959 // Build a sequence of copy-to-reg nodes chained together with token chain 1960 // and flag operands which copy the outgoing args into the appropriate regs. 1961 SDValue InFlag; 1962 // Tail call byval lowering might overwrite argument registers so in case of 1963 // tail call optimization the copies to registers are lowered later. 1964 if (!isTailCall) 1965 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1966 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1967 RegsToPass[i].second, InFlag); 1968 InFlag = Chain.getValue(1); 1969 } 1970 1971 // For tail calls lower the arguments to the 'real' stack slot. 1972 if (isTailCall) { 1973 // Force all the incoming stack arguments to be loaded from the stack 1974 // before any new outgoing arguments are stored to the stack, because the 1975 // outgoing stack slots may alias the incoming argument stack slots, and 1976 // the alias isn't otherwise explicit. This is slightly more conservative 1977 // than necessary, because it means that each store effectively depends 1978 // on every argument instead of just those arguments it would clobber. 1979 1980 // Do not flag preceding copytoreg stuff together with the following stuff. 1981 InFlag = SDValue(); 1982 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1983 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1984 RegsToPass[i].second, InFlag); 1985 InFlag = Chain.getValue(1); 1986 } 1987 InFlag = SDValue(); 1988 } 1989 1990 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1991 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1992 // node so that legalize doesn't hack it. 1993 bool isDirect = false; 1994 1995 const TargetMachine &TM = getTargetMachine(); 1996 const Module *Mod = MF.getFunction().getParent(); 1997 const GlobalValue *GV = nullptr; 1998 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1999 GV = G->getGlobal(); 2000 bool isStub = 2001 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2002 2003 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2004 bool isLocalARMFunc = false; 2005 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2006 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2007 2008 if (Subtarget->genLongCalls()) { 2009 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2010 "long-calls codegen is not position independent!"); 2011 // Handle a global address or an external symbol. If it's not one of 2012 // those, the target's already in a register, so we don't need to do 2013 // anything extra. 2014 if (isa<GlobalAddressSDNode>(Callee)) { 2015 // Create a constant pool entry for the callee address 2016 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2017 ARMConstantPoolValue *CPV = 2018 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2019 2020 // Get the address of the callee into a register 2021 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2022 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2023 Callee = DAG.getLoad( 2024 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2025 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2026 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2027 const char *Sym = S->getSymbol(); 2028 2029 // Create a constant pool entry for the callee address 2030 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2031 ARMConstantPoolValue *CPV = 2032 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2033 ARMPCLabelIndex, 0); 2034 // Get the address of the callee into a register 2035 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2036 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2037 Callee = DAG.getLoad( 2038 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2039 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2040 } 2041 } else if (isa<GlobalAddressSDNode>(Callee)) { 2042 // If we're optimizing for minimum size and the function is called three or 2043 // more times in this block, we can improve codesize by calling indirectly 2044 // as BLXr has a 16-bit encoding. 2045 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2046 auto *BB = CLI.CS.getParent(); 2047 bool PreferIndirect = 2048 Subtarget->isThumb() && MF.getFunction().optForMinSize() && 2049 count_if(GV->users(), [&BB](const User *U) { 2050 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2051 }) > 2; 2052 2053 if (!PreferIndirect) { 2054 isDirect = true; 2055 bool isDef = GV->isStrongDefinitionForLinker(); 2056 2057 // ARM call to a local ARM function is predicable. 2058 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2059 // tBX takes a register source operand. 2060 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2061 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2062 Callee = DAG.getNode( 2063 ARMISD::WrapperPIC, dl, PtrVt, 2064 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2065 Callee = DAG.getLoad( 2066 PtrVt, dl, DAG.getEntryNode(), Callee, 2067 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2068 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2069 MachineMemOperand::MOInvariant); 2070 } else if (Subtarget->isTargetCOFF()) { 2071 assert(Subtarget->isTargetWindows() && 2072 "Windows is the only supported COFF target"); 2073 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2074 ? ARMII::MO_DLLIMPORT 2075 : ARMII::MO_NO_FLAG; 2076 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2077 TargetFlags); 2078 if (GV->hasDLLImportStorageClass()) 2079 Callee = 2080 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2081 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2082 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2083 } else { 2084 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2085 } 2086 } 2087 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2088 isDirect = true; 2089 // tBX takes a register source operand. 2090 const char *Sym = S->getSymbol(); 2091 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2092 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2093 ARMConstantPoolValue *CPV = 2094 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2095 ARMPCLabelIndex, 4); 2096 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2097 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2098 Callee = DAG.getLoad( 2099 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2100 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2101 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2102 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2103 } else { 2104 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2105 } 2106 } 2107 2108 // FIXME: handle tail calls differently. 2109 unsigned CallOpc; 2110 if (Subtarget->isThumb()) { 2111 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2112 CallOpc = ARMISD::CALL_NOLINK; 2113 else 2114 CallOpc = ARMISD::CALL; 2115 } else { 2116 if (!isDirect && !Subtarget->hasV5TOps()) 2117 CallOpc = ARMISD::CALL_NOLINK; 2118 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2119 // Emit regular call when code size is the priority 2120 !MF.getFunction().optForMinSize()) 2121 // "mov lr, pc; b _foo" to avoid confusing the RSP 2122 CallOpc = ARMISD::CALL_NOLINK; 2123 else 2124 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2125 } 2126 2127 std::vector<SDValue> Ops; 2128 Ops.push_back(Chain); 2129 Ops.push_back(Callee); 2130 2131 // Add argument registers to the end of the list so that they are known live 2132 // into the call. 2133 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2134 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2135 RegsToPass[i].second.getValueType())); 2136 2137 // Add a register mask operand representing the call-preserved registers. 2138 if (!isTailCall) { 2139 const uint32_t *Mask; 2140 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2141 if (isThisReturn) { 2142 // For 'this' returns, use the R0-preserving mask if applicable 2143 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2144 if (!Mask) { 2145 // Set isThisReturn to false if the calling convention is not one that 2146 // allows 'returned' to be modeled in this way, so LowerCallResult does 2147 // not try to pass 'this' straight through 2148 isThisReturn = false; 2149 Mask = ARI->getCallPreservedMask(MF, CallConv); 2150 } 2151 } else 2152 Mask = ARI->getCallPreservedMask(MF, CallConv); 2153 2154 assert(Mask && "Missing call preserved mask for calling convention"); 2155 Ops.push_back(DAG.getRegisterMask(Mask)); 2156 } 2157 2158 if (InFlag.getNode()) 2159 Ops.push_back(InFlag); 2160 2161 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2162 if (isTailCall) { 2163 MF.getFrameInfo().setHasTailCall(); 2164 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2165 } 2166 2167 // Returns a chain and a flag for retval copy to use. 2168 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2169 InFlag = Chain.getValue(1); 2170 2171 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2172 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2173 if (!Ins.empty()) 2174 InFlag = Chain.getValue(1); 2175 2176 // Handle result values, copying them out of physregs into vregs that we 2177 // return. 2178 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2179 InVals, isThisReturn, 2180 isThisReturn ? OutVals[0] : SDValue()); 2181 } 2182 2183 /// HandleByVal - Every parameter *after* a byval parameter is passed 2184 /// on the stack. Remember the next parameter register to allocate, 2185 /// and then confiscate the rest of the parameter registers to insure 2186 /// this. 2187 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2188 unsigned Align) const { 2189 // Byval (as with any stack) slots are always at least 4 byte aligned. 2190 Align = std::max(Align, 4U); 2191 2192 unsigned Reg = State->AllocateReg(GPRArgRegs); 2193 if (!Reg) 2194 return; 2195 2196 unsigned AlignInRegs = Align / 4; 2197 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2198 for (unsigned i = 0; i < Waste; ++i) 2199 Reg = State->AllocateReg(GPRArgRegs); 2200 2201 if (!Reg) 2202 return; 2203 2204 unsigned Excess = 4 * (ARM::R4 - Reg); 2205 2206 // Special case when NSAA != SP and parameter size greater than size of 2207 // all remained GPR regs. In that case we can't split parameter, we must 2208 // send it to stack. We also must set NCRN to R4, so waste all 2209 // remained registers. 2210 const unsigned NSAAOffset = State->getNextStackOffset(); 2211 if (NSAAOffset != 0 && Size > Excess) { 2212 while (State->AllocateReg(GPRArgRegs)) 2213 ; 2214 return; 2215 } 2216 2217 // First register for byval parameter is the first register that wasn't 2218 // allocated before this method call, so it would be "reg". 2219 // If parameter is small enough to be saved in range [reg, r4), then 2220 // the end (first after last) register would be reg + param-size-in-regs, 2221 // else parameter would be splitted between registers and stack, 2222 // end register would be r4 in this case. 2223 unsigned ByValRegBegin = Reg; 2224 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2225 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2226 // Note, first register is allocated in the beginning of function already, 2227 // allocate remained amount of registers we need. 2228 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2229 State->AllocateReg(GPRArgRegs); 2230 // A byval parameter that is split between registers and memory needs its 2231 // size truncated here. 2232 // In the case where the entire structure fits in registers, we set the 2233 // size in memory to zero. 2234 Size = std::max<int>(Size - Excess, 0); 2235 } 2236 2237 /// MatchingStackOffset - Return true if the given stack call argument is 2238 /// already available in the same position (relatively) of the caller's 2239 /// incoming argument stack. 2240 static 2241 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2242 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2243 const TargetInstrInfo *TII) { 2244 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2245 int FI = std::numeric_limits<int>::max(); 2246 if (Arg.getOpcode() == ISD::CopyFromReg) { 2247 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2248 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2249 return false; 2250 MachineInstr *Def = MRI->getVRegDef(VR); 2251 if (!Def) 2252 return false; 2253 if (!Flags.isByVal()) { 2254 if (!TII->isLoadFromStackSlot(*Def, FI)) 2255 return false; 2256 } else { 2257 return false; 2258 } 2259 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2260 if (Flags.isByVal()) 2261 // ByVal argument is passed in as a pointer but it's now being 2262 // dereferenced. e.g. 2263 // define @foo(%struct.X* %A) { 2264 // tail call @bar(%struct.X* byval %A) 2265 // } 2266 return false; 2267 SDValue Ptr = Ld->getBasePtr(); 2268 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2269 if (!FINode) 2270 return false; 2271 FI = FINode->getIndex(); 2272 } else 2273 return false; 2274 2275 assert(FI != std::numeric_limits<int>::max()); 2276 if (!MFI.isFixedObjectIndex(FI)) 2277 return false; 2278 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2279 } 2280 2281 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2282 /// for tail call optimization. Targets which want to do tail call 2283 /// optimization should implement this function. 2284 bool 2285 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2286 CallingConv::ID CalleeCC, 2287 bool isVarArg, 2288 bool isCalleeStructRet, 2289 bool isCallerStructRet, 2290 const SmallVectorImpl<ISD::OutputArg> &Outs, 2291 const SmallVectorImpl<SDValue> &OutVals, 2292 const SmallVectorImpl<ISD::InputArg> &Ins, 2293 SelectionDAG& DAG) const { 2294 MachineFunction &MF = DAG.getMachineFunction(); 2295 const Function &CallerF = MF.getFunction(); 2296 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2297 2298 assert(Subtarget->supportsTailCall()); 2299 2300 // Tail calls to function pointers cannot be optimized for Thumb1 if the args 2301 // to the call take up r0-r3. The reason is that there are no legal registers 2302 // left to hold the pointer to the function to be called. 2303 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2304 !isa<GlobalAddressSDNode>(Callee.getNode())) 2305 return false; 2306 2307 // Look for obvious safe cases to perform tail call optimization that do not 2308 // require ABI changes. This is what gcc calls sibcall. 2309 2310 // Exception-handling functions need a special set of instructions to indicate 2311 // a return to the hardware. Tail-calling another function would probably 2312 // break this. 2313 if (CallerF.hasFnAttribute("interrupt")) 2314 return false; 2315 2316 // Also avoid sibcall optimization if either caller or callee uses struct 2317 // return semantics. 2318 if (isCalleeStructRet || isCallerStructRet) 2319 return false; 2320 2321 // Externally-defined functions with weak linkage should not be 2322 // tail-called on ARM when the OS does not support dynamic 2323 // pre-emption of symbols, as the AAELF spec requires normal calls 2324 // to undefined weak functions to be replaced with a NOP or jump to the 2325 // next instruction. The behaviour of branch instructions in this 2326 // situation (as used for tail calls) is implementation-defined, so we 2327 // cannot rely on the linker replacing the tail call with a return. 2328 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2329 const GlobalValue *GV = G->getGlobal(); 2330 const Triple &TT = getTargetMachine().getTargetTriple(); 2331 if (GV->hasExternalWeakLinkage() && 2332 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2333 return false; 2334 } 2335 2336 // Check that the call results are passed in the same way. 2337 LLVMContext &C = *DAG.getContext(); 2338 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2339 CCAssignFnForReturn(CalleeCC, isVarArg), 2340 CCAssignFnForReturn(CallerCC, isVarArg))) 2341 return false; 2342 // The callee has to preserve all registers the caller needs to preserve. 2343 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2344 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2345 if (CalleeCC != CallerCC) { 2346 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2347 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2348 return false; 2349 } 2350 2351 // If Caller's vararg or byval argument has been split between registers and 2352 // stack, do not perform tail call, since part of the argument is in caller's 2353 // local frame. 2354 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2355 if (AFI_Caller->getArgRegsSaveSize()) 2356 return false; 2357 2358 // If the callee takes no arguments then go on to check the results of the 2359 // call. 2360 if (!Outs.empty()) { 2361 // Check if stack adjustment is needed. For now, do not do this if any 2362 // argument is passed on the stack. 2363 SmallVector<CCValAssign, 16> ArgLocs; 2364 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2365 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2366 if (CCInfo.getNextStackOffset()) { 2367 // Check if the arguments are already laid out in the right way as 2368 // the caller's fixed stack objects. 2369 MachineFrameInfo &MFI = MF.getFrameInfo(); 2370 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2371 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2372 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2373 i != e; 2374 ++i, ++realArgIdx) { 2375 CCValAssign &VA = ArgLocs[i]; 2376 EVT RegVT = VA.getLocVT(); 2377 SDValue Arg = OutVals[realArgIdx]; 2378 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2379 if (VA.getLocInfo() == CCValAssign::Indirect) 2380 return false; 2381 if (VA.needsCustom()) { 2382 // f64 and vector types are split into multiple registers or 2383 // register/stack-slot combinations. The types will not match 2384 // the registers; give up on memory f64 refs until we figure 2385 // out what to do about this. 2386 if (!VA.isRegLoc()) 2387 return false; 2388 if (!ArgLocs[++i].isRegLoc()) 2389 return false; 2390 if (RegVT == MVT::v2f64) { 2391 if (!ArgLocs[++i].isRegLoc()) 2392 return false; 2393 if (!ArgLocs[++i].isRegLoc()) 2394 return false; 2395 } 2396 } else if (!VA.isRegLoc()) { 2397 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2398 MFI, MRI, TII)) 2399 return false; 2400 } 2401 } 2402 } 2403 2404 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2405 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2406 return false; 2407 } 2408 2409 return true; 2410 } 2411 2412 bool 2413 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2414 MachineFunction &MF, bool isVarArg, 2415 const SmallVectorImpl<ISD::OutputArg> &Outs, 2416 LLVMContext &Context) const { 2417 SmallVector<CCValAssign, 16> RVLocs; 2418 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2419 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2420 } 2421 2422 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2423 const SDLoc &DL, SelectionDAG &DAG) { 2424 const MachineFunction &MF = DAG.getMachineFunction(); 2425 const Function &F = MF.getFunction(); 2426 2427 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2428 2429 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2430 // version of the "preferred return address". These offsets affect the return 2431 // instruction if this is a return from PL1 without hypervisor extensions. 2432 // IRQ/FIQ: +4 "subs pc, lr, #4" 2433 // SWI: 0 "subs pc, lr, #0" 2434 // ABORT: +4 "subs pc, lr, #4" 2435 // UNDEF: +4/+2 "subs pc, lr, #0" 2436 // UNDEF varies depending on where the exception came from ARM or Thumb 2437 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2438 2439 int64_t LROffset; 2440 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2441 IntKind == "ABORT") 2442 LROffset = 4; 2443 else if (IntKind == "SWI" || IntKind == "UNDEF") 2444 LROffset = 0; 2445 else 2446 report_fatal_error("Unsupported interrupt attribute. If present, value " 2447 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2448 2449 RetOps.insert(RetOps.begin() + 1, 2450 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2451 2452 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2453 } 2454 2455 SDValue 2456 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2457 bool isVarArg, 2458 const SmallVectorImpl<ISD::OutputArg> &Outs, 2459 const SmallVectorImpl<SDValue> &OutVals, 2460 const SDLoc &dl, SelectionDAG &DAG) const { 2461 // CCValAssign - represent the assignment of the return value to a location. 2462 SmallVector<CCValAssign, 16> RVLocs; 2463 2464 // CCState - Info about the registers and stack slots. 2465 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2466 *DAG.getContext()); 2467 2468 // Analyze outgoing return values. 2469 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2470 2471 SDValue Flag; 2472 SmallVector<SDValue, 4> RetOps; 2473 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2474 bool isLittleEndian = Subtarget->isLittle(); 2475 2476 MachineFunction &MF = DAG.getMachineFunction(); 2477 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2478 AFI->setReturnRegsCount(RVLocs.size()); 2479 2480 // Copy the result values into the output registers. 2481 for (unsigned i = 0, realRVLocIdx = 0; 2482 i != RVLocs.size(); 2483 ++i, ++realRVLocIdx) { 2484 CCValAssign &VA = RVLocs[i]; 2485 assert(VA.isRegLoc() && "Can only return in registers!"); 2486 2487 SDValue Arg = OutVals[realRVLocIdx]; 2488 bool ReturnF16 = false; 2489 2490 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2491 // Half-precision return values can be returned like this: 2492 // 2493 // t11 f16 = fadd ... 2494 // t12: i16 = bitcast t11 2495 // t13: i32 = zero_extend t12 2496 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2497 // 2498 // to avoid code generation for bitcasts, we simply set Arg to the node 2499 // that produces the f16 value, t11 in this case. 2500 // 2501 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2502 SDValue ZE = Arg.getOperand(0); 2503 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2504 SDValue BC = ZE.getOperand(0); 2505 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2506 Arg = BC.getOperand(0); 2507 ReturnF16 = true; 2508 } 2509 } 2510 } 2511 } 2512 2513 switch (VA.getLocInfo()) { 2514 default: llvm_unreachable("Unknown loc info!"); 2515 case CCValAssign::Full: break; 2516 case CCValAssign::BCvt: 2517 if (!ReturnF16) 2518 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2519 break; 2520 } 2521 2522 if (VA.needsCustom()) { 2523 if (VA.getLocVT() == MVT::v2f64) { 2524 // Extract the first half and return it in two registers. 2525 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2526 DAG.getConstant(0, dl, MVT::i32)); 2527 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2528 DAG.getVTList(MVT::i32, MVT::i32), Half); 2529 2530 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2531 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2532 Flag); 2533 Flag = Chain.getValue(1); 2534 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2535 VA = RVLocs[++i]; // skip ahead to next loc 2536 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2537 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2538 Flag); 2539 Flag = Chain.getValue(1); 2540 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2541 VA = RVLocs[++i]; // skip ahead to next loc 2542 2543 // Extract the 2nd half and fall through to handle it as an f64 value. 2544 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2545 DAG.getConstant(1, dl, MVT::i32)); 2546 } 2547 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2548 // available. 2549 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2550 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2551 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2552 fmrrd.getValue(isLittleEndian ? 0 : 1), 2553 Flag); 2554 Flag = Chain.getValue(1); 2555 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2556 VA = RVLocs[++i]; // skip ahead to next loc 2557 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2558 fmrrd.getValue(isLittleEndian ? 1 : 0), 2559 Flag); 2560 } else 2561 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2562 2563 // Guarantee that all emitted copies are 2564 // stuck together, avoiding something bad. 2565 Flag = Chain.getValue(1); 2566 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2567 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2568 } 2569 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2570 const MCPhysReg *I = 2571 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2572 if (I) { 2573 for (; *I; ++I) { 2574 if (ARM::GPRRegClass.contains(*I)) 2575 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2576 else if (ARM::DPRRegClass.contains(*I)) 2577 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2578 else 2579 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2580 } 2581 } 2582 2583 // Update chain and glue. 2584 RetOps[0] = Chain; 2585 if (Flag.getNode()) 2586 RetOps.push_back(Flag); 2587 2588 // CPUs which aren't M-class use a special sequence to return from 2589 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2590 // though we use "subs pc, lr, #N"). 2591 // 2592 // M-class CPUs actually use a normal return sequence with a special 2593 // (hardware-provided) value in LR, so the normal code path works. 2594 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2595 !Subtarget->isMClass()) { 2596 if (Subtarget->isThumb1Only()) 2597 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2598 return LowerInterruptReturn(RetOps, dl, DAG); 2599 } 2600 2601 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2602 } 2603 2604 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2605 if (N->getNumValues() != 1) 2606 return false; 2607 if (!N->hasNUsesOfValue(1, 0)) 2608 return false; 2609 2610 SDValue TCChain = Chain; 2611 SDNode *Copy = *N->use_begin(); 2612 if (Copy->getOpcode() == ISD::CopyToReg) { 2613 // If the copy has a glue operand, we conservatively assume it isn't safe to 2614 // perform a tail call. 2615 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2616 return false; 2617 TCChain = Copy->getOperand(0); 2618 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2619 SDNode *VMov = Copy; 2620 // f64 returned in a pair of GPRs. 2621 SmallPtrSet<SDNode*, 2> Copies; 2622 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2623 UI != UE; ++UI) { 2624 if (UI->getOpcode() != ISD::CopyToReg) 2625 return false; 2626 Copies.insert(*UI); 2627 } 2628 if (Copies.size() > 2) 2629 return false; 2630 2631 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2632 UI != UE; ++UI) { 2633 SDValue UseChain = UI->getOperand(0); 2634 if (Copies.count(UseChain.getNode())) 2635 // Second CopyToReg 2636 Copy = *UI; 2637 else { 2638 // We are at the top of this chain. 2639 // If the copy has a glue operand, we conservatively assume it 2640 // isn't safe to perform a tail call. 2641 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2642 return false; 2643 // First CopyToReg 2644 TCChain = UseChain; 2645 } 2646 } 2647 } else if (Copy->getOpcode() == ISD::BITCAST) { 2648 // f32 returned in a single GPR. 2649 if (!Copy->hasOneUse()) 2650 return false; 2651 Copy = *Copy->use_begin(); 2652 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2653 return false; 2654 // If the copy has a glue operand, we conservatively assume it isn't safe to 2655 // perform a tail call. 2656 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2657 return false; 2658 TCChain = Copy->getOperand(0); 2659 } else { 2660 return false; 2661 } 2662 2663 bool HasRet = false; 2664 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2665 UI != UE; ++UI) { 2666 if (UI->getOpcode() != ARMISD::RET_FLAG && 2667 UI->getOpcode() != ARMISD::INTRET_FLAG) 2668 return false; 2669 HasRet = true; 2670 } 2671 2672 if (!HasRet) 2673 return false; 2674 2675 Chain = TCChain; 2676 return true; 2677 } 2678 2679 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2680 if (!Subtarget->supportsTailCall()) 2681 return false; 2682 2683 auto Attr = 2684 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2685 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2686 return false; 2687 2688 return true; 2689 } 2690 2691 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2692 // and pass the lower and high parts through. 2693 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2694 SDLoc DL(Op); 2695 SDValue WriteValue = Op->getOperand(2); 2696 2697 // This function is only supposed to be called for i64 type argument. 2698 assert(WriteValue.getValueType() == MVT::i64 2699 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2700 2701 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2702 DAG.getConstant(0, DL, MVT::i32)); 2703 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2704 DAG.getConstant(1, DL, MVT::i32)); 2705 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2706 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2707 } 2708 2709 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2710 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2711 // one of the above mentioned nodes. It has to be wrapped because otherwise 2712 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2713 // be used to form addressing mode. These wrapped nodes will be selected 2714 // into MOVi. 2715 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2716 SelectionDAG &DAG) const { 2717 EVT PtrVT = Op.getValueType(); 2718 // FIXME there is no actual debug info here 2719 SDLoc dl(Op); 2720 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2721 SDValue Res; 2722 2723 // When generating execute-only code Constant Pools must be promoted to the 2724 // global data section. It's a bit ugly that we can't share them across basic 2725 // blocks, but this way we guarantee that execute-only behaves correct with 2726 // position-independent addressing modes. 2727 if (Subtarget->genExecuteOnly()) { 2728 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2729 auto T = const_cast<Type*>(CP->getType()); 2730 auto C = const_cast<Constant*>(CP->getConstVal()); 2731 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2732 getFunction().getParent()); 2733 auto GV = new GlobalVariable( 2734 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2735 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2736 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2737 Twine(AFI->createPICLabelUId()) 2738 ); 2739 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2740 dl, PtrVT); 2741 return LowerGlobalAddress(GA, DAG); 2742 } 2743 2744 if (CP->isMachineConstantPoolEntry()) 2745 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2746 CP->getAlignment()); 2747 else 2748 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2749 CP->getAlignment()); 2750 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2751 } 2752 2753 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2754 return MachineJumpTableInfo::EK_Inline; 2755 } 2756 2757 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2758 SelectionDAG &DAG) const { 2759 MachineFunction &MF = DAG.getMachineFunction(); 2760 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2761 unsigned ARMPCLabelIndex = 0; 2762 SDLoc DL(Op); 2763 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2764 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2765 SDValue CPAddr; 2766 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2767 if (!IsPositionIndependent) { 2768 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2769 } else { 2770 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2771 ARMPCLabelIndex = AFI->createPICLabelUId(); 2772 ARMConstantPoolValue *CPV = 2773 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2774 ARMCP::CPBlockAddress, PCAdj); 2775 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2776 } 2777 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2778 SDValue Result = DAG.getLoad( 2779 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2780 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2781 if (!IsPositionIndependent) 2782 return Result; 2783 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2784 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2785 } 2786 2787 /// \brief Convert a TLS address reference into the correct sequence of loads 2788 /// and calls to compute the variable's address for Darwin, and return an 2789 /// SDValue containing the final node. 2790 2791 /// Darwin only has one TLS scheme which must be capable of dealing with the 2792 /// fully general situation, in the worst case. This means: 2793 /// + "extern __thread" declaration. 2794 /// + Defined in a possibly unknown dynamic library. 2795 /// 2796 /// The general system is that each __thread variable has a [3 x i32] descriptor 2797 /// which contains information used by the runtime to calculate the address. The 2798 /// only part of this the compiler needs to know about is the first word, which 2799 /// contains a function pointer that must be called with the address of the 2800 /// entire descriptor in "r0". 2801 /// 2802 /// Since this descriptor may be in a different unit, in general access must 2803 /// proceed along the usual ARM rules. A common sequence to produce is: 2804 /// 2805 /// movw rT1, :lower16:_var$non_lazy_ptr 2806 /// movt rT1, :upper16:_var$non_lazy_ptr 2807 /// ldr r0, [rT1] 2808 /// ldr rT2, [r0] 2809 /// blx rT2 2810 /// [...address now in r0...] 2811 SDValue 2812 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2813 SelectionDAG &DAG) const { 2814 assert(Subtarget->isTargetDarwin() && 2815 "This function expects a Darwin target"); 2816 SDLoc DL(Op); 2817 2818 // First step is to get the address of the actua global symbol. This is where 2819 // the TLS descriptor lives. 2820 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2821 2822 // The first entry in the descriptor is a function pointer that we must call 2823 // to obtain the address of the variable. 2824 SDValue Chain = DAG.getEntryNode(); 2825 SDValue FuncTLVGet = DAG.getLoad( 2826 MVT::i32, DL, Chain, DescAddr, 2827 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2828 /* Alignment = */ 4, 2829 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2830 MachineMemOperand::MOInvariant); 2831 Chain = FuncTLVGet.getValue(1); 2832 2833 MachineFunction &F = DAG.getMachineFunction(); 2834 MachineFrameInfo &MFI = F.getFrameInfo(); 2835 MFI.setAdjustsStack(true); 2836 2837 // TLS calls preserve all registers except those that absolutely must be 2838 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2839 // silly). 2840 auto TRI = 2841 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 2842 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2843 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2844 2845 // Finally, we can make the call. This is just a degenerate version of a 2846 // normal AArch64 call node: r0 takes the address of the descriptor, and 2847 // returns the address of the variable in this thread. 2848 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2849 Chain = 2850 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2851 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2852 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2853 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2854 } 2855 2856 SDValue 2857 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2858 SelectionDAG &DAG) const { 2859 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2860 2861 SDValue Chain = DAG.getEntryNode(); 2862 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2863 SDLoc DL(Op); 2864 2865 // Load the current TEB (thread environment block) 2866 SDValue Ops[] = {Chain, 2867 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2868 DAG.getConstant(15, DL, MVT::i32), 2869 DAG.getConstant(0, DL, MVT::i32), 2870 DAG.getConstant(13, DL, MVT::i32), 2871 DAG.getConstant(0, DL, MVT::i32), 2872 DAG.getConstant(2, DL, MVT::i32)}; 2873 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2874 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2875 2876 SDValue TEB = CurrentTEB.getValue(0); 2877 Chain = CurrentTEB.getValue(1); 2878 2879 // Load the ThreadLocalStoragePointer from the TEB 2880 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2881 SDValue TLSArray = 2882 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2883 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2884 2885 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2886 // offset into the TLSArray. 2887 2888 // Load the TLS index from the C runtime 2889 SDValue TLSIndex = 2890 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2891 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2892 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2893 2894 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2895 DAG.getConstant(2, DL, MVT::i32)); 2896 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2897 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2898 MachinePointerInfo()); 2899 2900 // Get the offset of the start of the .tls section (section base) 2901 const auto *GA = cast<GlobalAddressSDNode>(Op); 2902 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2903 SDValue Offset = DAG.getLoad( 2904 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2905 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2906 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2907 2908 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2909 } 2910 2911 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2912 SDValue 2913 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2914 SelectionDAG &DAG) const { 2915 SDLoc dl(GA); 2916 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2917 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2918 MachineFunction &MF = DAG.getMachineFunction(); 2919 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2920 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2921 ARMConstantPoolValue *CPV = 2922 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2923 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2924 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2925 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2926 Argument = DAG.getLoad( 2927 PtrVT, dl, DAG.getEntryNode(), Argument, 2928 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2929 SDValue Chain = Argument.getValue(1); 2930 2931 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2932 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2933 2934 // call __tls_get_addr. 2935 ArgListTy Args; 2936 ArgListEntry Entry; 2937 Entry.Node = Argument; 2938 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2939 Args.push_back(Entry); 2940 2941 // FIXME: is there useful debug info available here? 2942 TargetLowering::CallLoweringInfo CLI(DAG); 2943 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2944 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2945 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2946 2947 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2948 return CallResult.first; 2949 } 2950 2951 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2952 // "local exec" model. 2953 SDValue 2954 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2955 SelectionDAG &DAG, 2956 TLSModel::Model model) const { 2957 const GlobalValue *GV = GA->getGlobal(); 2958 SDLoc dl(GA); 2959 SDValue Offset; 2960 SDValue Chain = DAG.getEntryNode(); 2961 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2962 // Get the Thread Pointer 2963 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2964 2965 if (model == TLSModel::InitialExec) { 2966 MachineFunction &MF = DAG.getMachineFunction(); 2967 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2968 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2969 // Initial exec model. 2970 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2971 ARMConstantPoolValue *CPV = 2972 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2973 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2974 true); 2975 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2976 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2977 Offset = DAG.getLoad( 2978 PtrVT, dl, Chain, Offset, 2979 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2980 Chain = Offset.getValue(1); 2981 2982 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2983 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2984 2985 Offset = DAG.getLoad( 2986 PtrVT, dl, Chain, Offset, 2987 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2988 } else { 2989 // local exec model 2990 assert(model == TLSModel::LocalExec); 2991 ARMConstantPoolValue *CPV = 2992 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2993 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2994 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2995 Offset = DAG.getLoad( 2996 PtrVT, dl, Chain, Offset, 2997 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2998 } 2999 3000 // The address of the thread local variable is the add of the thread 3001 // pointer with the offset of the variable. 3002 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3003 } 3004 3005 SDValue 3006 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3007 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3008 if (DAG.getTarget().useEmulatedTLS()) 3009 return LowerToTLSEmulatedModel(GA, DAG); 3010 3011 if (Subtarget->isTargetDarwin()) 3012 return LowerGlobalTLSAddressDarwin(Op, DAG); 3013 3014 if (Subtarget->isTargetWindows()) 3015 return LowerGlobalTLSAddressWindows(Op, DAG); 3016 3017 // TODO: implement the "local dynamic" model 3018 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3019 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3020 3021 switch (model) { 3022 case TLSModel::GeneralDynamic: 3023 case TLSModel::LocalDynamic: 3024 return LowerToTLSGeneralDynamicModel(GA, DAG); 3025 case TLSModel::InitialExec: 3026 case TLSModel::LocalExec: 3027 return LowerToTLSExecModels(GA, DAG, model); 3028 } 3029 llvm_unreachable("bogus TLS model"); 3030 } 3031 3032 /// Return true if all users of V are within function F, looking through 3033 /// ConstantExprs. 3034 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3035 SmallVector<const User*,4> Worklist; 3036 for (auto *U : V->users()) 3037 Worklist.push_back(U); 3038 while (!Worklist.empty()) { 3039 auto *U = Worklist.pop_back_val(); 3040 if (isa<ConstantExpr>(U)) { 3041 for (auto *UU : U->users()) 3042 Worklist.push_back(UU); 3043 continue; 3044 } 3045 3046 auto *I = dyn_cast<Instruction>(U); 3047 if (!I || I->getParent()->getParent() != F) 3048 return false; 3049 } 3050 return true; 3051 } 3052 3053 /// Return true if all users of V are within some (any) function, looking through 3054 /// ConstantExprs. In other words, are there any global constant users? 3055 static bool allUsersAreInFunctions(const Value *V) { 3056 SmallVector<const User*,4> Worklist; 3057 for (auto *U : V->users()) 3058 Worklist.push_back(U); 3059 while (!Worklist.empty()) { 3060 auto *U = Worklist.pop_back_val(); 3061 if (isa<ConstantExpr>(U)) { 3062 for (auto *UU : U->users()) 3063 Worklist.push_back(UU); 3064 continue; 3065 } 3066 3067 if (!isa<Instruction>(U)) 3068 return false; 3069 } 3070 return true; 3071 } 3072 3073 // Return true if T is an integer, float or an array/vector of either. 3074 static bool isSimpleType(Type *T) { 3075 if (T->isIntegerTy() || T->isFloatingPointTy()) 3076 return true; 3077 Type *SubT = nullptr; 3078 if (T->isArrayTy()) 3079 SubT = T->getArrayElementType(); 3080 else if (T->isVectorTy()) 3081 SubT = T->getVectorElementType(); 3082 else 3083 return false; 3084 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 3085 } 3086 3087 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 3088 EVT PtrVT, const SDLoc &dl) { 3089 // If we're creating a pool entry for a constant global with unnamed address, 3090 // and the global is small enough, we can emit it inline into the constant pool 3091 // to save ourselves an indirection. 3092 // 3093 // This is a win if the constant is only used in one function (so it doesn't 3094 // need to be duplicated) or duplicating the constant wouldn't increase code 3095 // size (implying the constant is no larger than 4 bytes). 3096 const Function &F = DAG.getMachineFunction().getFunction(); 3097 3098 // We rely on this decision to inline being idemopotent and unrelated to the 3099 // use-site. We know that if we inline a variable at one use site, we'll 3100 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3101 // doesn't know about this optimization, so bail out if it's enabled else 3102 // we could decide to inline here (and thus never emit the GV) but require 3103 // the GV from fast-isel generated code. 3104 if (!EnableConstpoolPromotion || 3105 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3106 return SDValue(); 3107 3108 auto *GVar = dyn_cast<GlobalVariable>(GV); 3109 if (!GVar || !GVar->hasInitializer() || 3110 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3111 !GVar->hasLocalLinkage()) 3112 return SDValue(); 3113 3114 // Ensure that we don't try and inline any type that contains pointers. If 3115 // we inline a value that contains relocations, we move the relocations from 3116 // .data to .text which is not ideal. 3117 auto *Init = GVar->getInitializer(); 3118 if (!isSimpleType(Init->getType())) 3119 return SDValue(); 3120 3121 // The constant islands pass can only really deal with alignment requests 3122 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3123 // any type wanting greater alignment requirements than 4 bytes. We also 3124 // can only promote constants that are multiples of 4 bytes in size or 3125 // are paddable to a multiple of 4. Currently we only try and pad constants 3126 // that are strings for simplicity. 3127 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3128 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3129 unsigned Align = GVar->getAlignment(); 3130 unsigned RequiredPadding = 4 - (Size % 4); 3131 bool PaddingPossible = 3132 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3133 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3134 Size == 0) 3135 return SDValue(); 3136 3137 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3138 MachineFunction &MF = DAG.getMachineFunction(); 3139 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3140 3141 // We can't bloat the constant pool too much, else the ConstantIslands pass 3142 // may fail to converge. If we haven't promoted this global yet (it may have 3143 // multiple uses), and promoting it would increase the constant pool size (Sz 3144 // > 4), ensure we have space to do so up to MaxTotal. 3145 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3146 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3147 ConstpoolPromotionMaxTotal) 3148 return SDValue(); 3149 3150 // This is only valid if all users are in a single function OR it has users 3151 // in multiple functions but it no larger than a pointer. We also check if 3152 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3153 // address taken. 3154 if (!allUsersAreInFunction(GVar, &F) && 3155 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3156 return SDValue(); 3157 3158 // We're going to inline this global. Pad it out if needed. 3159 if (RequiredPadding != 4) { 3160 StringRef S = CDAInit->getAsString(); 3161 3162 SmallVector<uint8_t,16> V(S.size()); 3163 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3164 while (RequiredPadding--) 3165 V.push_back(0); 3166 Init = ConstantDataArray::get(*DAG.getContext(), V); 3167 } 3168 3169 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3170 SDValue CPAddr = 3171 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3172 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3173 AFI->markGlobalAsPromotedToConstantPool(GVar); 3174 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3175 PaddedSize - 4); 3176 } 3177 ++NumConstpoolPromoted; 3178 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3179 } 3180 3181 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3182 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3183 GV = GA->getBaseObject(); 3184 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3185 isa<Function>(GV); 3186 } 3187 3188 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3189 SelectionDAG &DAG) const { 3190 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3191 default: llvm_unreachable("unknown object format"); 3192 case Triple::COFF: 3193 return LowerGlobalAddressWindows(Op, DAG); 3194 case Triple::ELF: 3195 return LowerGlobalAddressELF(Op, DAG); 3196 case Triple::MachO: 3197 return LowerGlobalAddressDarwin(Op, DAG); 3198 } 3199 } 3200 3201 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3202 SelectionDAG &DAG) const { 3203 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3204 SDLoc dl(Op); 3205 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3206 const TargetMachine &TM = getTargetMachine(); 3207 bool IsRO = isReadOnly(GV); 3208 3209 // promoteToConstantPool only if not generating XO text section 3210 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3211 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3212 return V; 3213 3214 if (isPositionIndependent()) { 3215 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3216 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3217 UseGOT_PREL ? ARMII::MO_GOT : 0); 3218 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3219 if (UseGOT_PREL) 3220 Result = 3221 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3222 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3223 return Result; 3224 } else if (Subtarget->isROPI() && IsRO) { 3225 // PC-relative. 3226 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3227 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3228 return Result; 3229 } else if (Subtarget->isRWPI() && !IsRO) { 3230 // SB-relative. 3231 SDValue RelAddr; 3232 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3233 ++NumMovwMovt; 3234 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3235 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3236 } else { // use literal pool for address constant 3237 ARMConstantPoolValue *CPV = 3238 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3239 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3240 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3241 RelAddr = DAG.getLoad( 3242 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3243 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3244 } 3245 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3246 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3247 return Result; 3248 } 3249 3250 // If we have T2 ops, we can materialize the address directly via movt/movw 3251 // pair. This is always cheaper. 3252 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3253 ++NumMovwMovt; 3254 // FIXME: Once remat is capable of dealing with instructions with register 3255 // operands, expand this into two nodes. 3256 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3257 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3258 } else { 3259 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3260 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3261 return DAG.getLoad( 3262 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3263 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3264 } 3265 } 3266 3267 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3268 SelectionDAG &DAG) const { 3269 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3270 "ROPI/RWPI not currently supported for Darwin"); 3271 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3272 SDLoc dl(Op); 3273 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3274 3275 if (Subtarget->useMovt(DAG.getMachineFunction())) 3276 ++NumMovwMovt; 3277 3278 // FIXME: Once remat is capable of dealing with instructions with register 3279 // operands, expand this into multiple nodes 3280 unsigned Wrapper = 3281 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3282 3283 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3284 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3285 3286 if (Subtarget->isGVIndirectSymbol(GV)) 3287 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3288 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3289 return Result; 3290 } 3291 3292 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3293 SelectionDAG &DAG) const { 3294 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3295 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3296 "Windows on ARM expects to use movw/movt"); 3297 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3298 "ROPI/RWPI not currently supported for Windows"); 3299 3300 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3301 const ARMII::TOF TargetFlags = 3302 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3303 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3304 SDValue Result; 3305 SDLoc DL(Op); 3306 3307 ++NumMovwMovt; 3308 3309 // FIXME: Once remat is capable of dealing with instructions with register 3310 // operands, expand this into two nodes. 3311 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3312 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3313 TargetFlags)); 3314 if (GV->hasDLLImportStorageClass()) 3315 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3316 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3317 return Result; 3318 } 3319 3320 SDValue 3321 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3322 SDLoc dl(Op); 3323 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3324 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3325 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3326 Op.getOperand(1), Val); 3327 } 3328 3329 SDValue 3330 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3331 SDLoc dl(Op); 3332 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3333 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3334 } 3335 3336 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3337 SelectionDAG &DAG) const { 3338 SDLoc dl(Op); 3339 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3340 Op.getOperand(0)); 3341 } 3342 3343 SDValue 3344 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3345 const ARMSubtarget *Subtarget) const { 3346 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3347 SDLoc dl(Op); 3348 switch (IntNo) { 3349 default: return SDValue(); // Don't custom lower most intrinsics. 3350 case Intrinsic::thread_pointer: { 3351 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3352 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3353 } 3354 case Intrinsic::eh_sjlj_lsda: { 3355 MachineFunction &MF = DAG.getMachineFunction(); 3356 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3357 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3358 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3359 SDValue CPAddr; 3360 bool IsPositionIndependent = isPositionIndependent(); 3361 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3362 ARMConstantPoolValue *CPV = 3363 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3364 ARMCP::CPLSDA, PCAdj); 3365 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3366 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3367 SDValue Result = DAG.getLoad( 3368 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3369 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3370 3371 if (IsPositionIndependent) { 3372 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3373 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3374 } 3375 return Result; 3376 } 3377 case Intrinsic::arm_neon_vabs: 3378 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3379 Op.getOperand(1)); 3380 case Intrinsic::arm_neon_vmulls: 3381 case Intrinsic::arm_neon_vmullu: { 3382 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3383 ? ARMISD::VMULLs : ARMISD::VMULLu; 3384 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3385 Op.getOperand(1), Op.getOperand(2)); 3386 } 3387 case Intrinsic::arm_neon_vminnm: 3388 case Intrinsic::arm_neon_vmaxnm: { 3389 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3390 ? ISD::FMINNUM : ISD::FMAXNUM; 3391 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3392 Op.getOperand(1), Op.getOperand(2)); 3393 } 3394 case Intrinsic::arm_neon_vminu: 3395 case Intrinsic::arm_neon_vmaxu: { 3396 if (Op.getValueType().isFloatingPoint()) 3397 return SDValue(); 3398 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3399 ? ISD::UMIN : ISD::UMAX; 3400 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3401 Op.getOperand(1), Op.getOperand(2)); 3402 } 3403 case Intrinsic::arm_neon_vmins: 3404 case Intrinsic::arm_neon_vmaxs: { 3405 // v{min,max}s is overloaded between signed integers and floats. 3406 if (!Op.getValueType().isFloatingPoint()) { 3407 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3408 ? ISD::SMIN : ISD::SMAX; 3409 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3410 Op.getOperand(1), Op.getOperand(2)); 3411 } 3412 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3413 ? ISD::FMINNAN : ISD::FMAXNAN; 3414 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3415 Op.getOperand(1), Op.getOperand(2)); 3416 } 3417 case Intrinsic::arm_neon_vtbl1: 3418 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3419 Op.getOperand(1), Op.getOperand(2)); 3420 case Intrinsic::arm_neon_vtbl2: 3421 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3422 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3423 } 3424 } 3425 3426 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3427 const ARMSubtarget *Subtarget) { 3428 SDLoc dl(Op); 3429 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3430 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3431 if (SSID == SyncScope::SingleThread) 3432 return Op; 3433 3434 if (!Subtarget->hasDataBarrier()) { 3435 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3436 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3437 // here. 3438 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3439 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3440 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3441 DAG.getConstant(0, dl, MVT::i32)); 3442 } 3443 3444 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3445 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3446 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3447 if (Subtarget->isMClass()) { 3448 // Only a full system barrier exists in the M-class architectures. 3449 Domain = ARM_MB::SY; 3450 } else if (Subtarget->preferISHSTBarriers() && 3451 Ord == AtomicOrdering::Release) { 3452 // Swift happens to implement ISHST barriers in a way that's compatible with 3453 // Release semantics but weaker than ISH so we'd be fools not to use 3454 // it. Beware: other processors probably don't! 3455 Domain = ARM_MB::ISHST; 3456 } 3457 3458 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3459 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3460 DAG.getConstant(Domain, dl, MVT::i32)); 3461 } 3462 3463 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3464 const ARMSubtarget *Subtarget) { 3465 // ARM pre v5TE and Thumb1 does not have preload instructions. 3466 if (!(Subtarget->isThumb2() || 3467 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3468 // Just preserve the chain. 3469 return Op.getOperand(0); 3470 3471 SDLoc dl(Op); 3472 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3473 if (!isRead && 3474 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3475 // ARMv7 with MP extension has PLDW. 3476 return Op.getOperand(0); 3477 3478 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3479 if (Subtarget->isThumb()) { 3480 // Invert the bits. 3481 isRead = ~isRead & 1; 3482 isData = ~isData & 1; 3483 } 3484 3485 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3486 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3487 DAG.getConstant(isData, dl, MVT::i32)); 3488 } 3489 3490 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3491 MachineFunction &MF = DAG.getMachineFunction(); 3492 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3493 3494 // vastart just stores the address of the VarArgsFrameIndex slot into the 3495 // memory location argument. 3496 SDLoc dl(Op); 3497 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3498 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3499 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3500 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3501 MachinePointerInfo(SV)); 3502 } 3503 3504 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3505 CCValAssign &NextVA, 3506 SDValue &Root, 3507 SelectionDAG &DAG, 3508 const SDLoc &dl) const { 3509 MachineFunction &MF = DAG.getMachineFunction(); 3510 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3511 3512 const TargetRegisterClass *RC; 3513 if (AFI->isThumb1OnlyFunction()) 3514 RC = &ARM::tGPRRegClass; 3515 else 3516 RC = &ARM::GPRRegClass; 3517 3518 // Transform the arguments stored in physical registers into virtual ones. 3519 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3520 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3521 3522 SDValue ArgValue2; 3523 if (NextVA.isMemLoc()) { 3524 MachineFrameInfo &MFI = MF.getFrameInfo(); 3525 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3526 3527 // Create load node to retrieve arguments from the stack. 3528 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3529 ArgValue2 = DAG.getLoad( 3530 MVT::i32, dl, Root, FIN, 3531 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3532 } else { 3533 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3534 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3535 } 3536 if (!Subtarget->isLittle()) 3537 std::swap (ArgValue, ArgValue2); 3538 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3539 } 3540 3541 // The remaining GPRs hold either the beginning of variable-argument 3542 // data, or the beginning of an aggregate passed by value (usually 3543 // byval). Either way, we allocate stack slots adjacent to the data 3544 // provided by our caller, and store the unallocated registers there. 3545 // If this is a variadic function, the va_list pointer will begin with 3546 // these values; otherwise, this reassembles a (byval) structure that 3547 // was split between registers and memory. 3548 // Return: The frame index registers were stored into. 3549 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3550 const SDLoc &dl, SDValue &Chain, 3551 const Value *OrigArg, 3552 unsigned InRegsParamRecordIdx, 3553 int ArgOffset, unsigned ArgSize) const { 3554 // Currently, two use-cases possible: 3555 // Case #1. Non-var-args function, and we meet first byval parameter. 3556 // Setup first unallocated register as first byval register; 3557 // eat all remained registers 3558 // (these two actions are performed by HandleByVal method). 3559 // Then, here, we initialize stack frame with 3560 // "store-reg" instructions. 3561 // Case #2. Var-args function, that doesn't contain byval parameters. 3562 // The same: eat all remained unallocated registers, 3563 // initialize stack frame. 3564 3565 MachineFunction &MF = DAG.getMachineFunction(); 3566 MachineFrameInfo &MFI = MF.getFrameInfo(); 3567 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3568 unsigned RBegin, REnd; 3569 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3570 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3571 } else { 3572 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3573 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3574 REnd = ARM::R4; 3575 } 3576 3577 if (REnd != RBegin) 3578 ArgOffset = -4 * (ARM::R4 - RBegin); 3579 3580 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3581 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3582 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3583 3584 SmallVector<SDValue, 4> MemOps; 3585 const TargetRegisterClass *RC = 3586 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3587 3588 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3589 unsigned VReg = MF.addLiveIn(Reg, RC); 3590 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3591 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3592 MachinePointerInfo(OrigArg, 4 * i)); 3593 MemOps.push_back(Store); 3594 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3595 } 3596 3597 if (!MemOps.empty()) 3598 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3599 return FrameIndex; 3600 } 3601 3602 // Setup stack frame, the va_list pointer will start from. 3603 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3604 const SDLoc &dl, SDValue &Chain, 3605 unsigned ArgOffset, 3606 unsigned TotalArgRegsSaveSize, 3607 bool ForceMutable) const { 3608 MachineFunction &MF = DAG.getMachineFunction(); 3609 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3610 3611 // Try to store any remaining integer argument regs 3612 // to their spots on the stack so that they may be loaded by dereferencing 3613 // the result of va_next. 3614 // If there is no regs to be stored, just point address after last 3615 // argument passed via stack. 3616 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3617 CCInfo.getInRegsParamsCount(), 3618 CCInfo.getNextStackOffset(), 4); 3619 AFI->setVarArgsFrameIndex(FrameIndex); 3620 } 3621 3622 SDValue ARMTargetLowering::LowerFormalArguments( 3623 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3624 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3625 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3626 MachineFunction &MF = DAG.getMachineFunction(); 3627 MachineFrameInfo &MFI = MF.getFrameInfo(); 3628 3629 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3630 3631 // Assign locations to all of the incoming arguments. 3632 SmallVector<CCValAssign, 16> ArgLocs; 3633 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3634 *DAG.getContext()); 3635 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3636 3637 SmallVector<SDValue, 16> ArgValues; 3638 SDValue ArgValue; 3639 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3640 unsigned CurArgIdx = 0; 3641 3642 // Initially ArgRegsSaveSize is zero. 3643 // Then we increase this value each time we meet byval parameter. 3644 // We also increase this value in case of varargs function. 3645 AFI->setArgRegsSaveSize(0); 3646 3647 // Calculate the amount of stack space that we need to allocate to store 3648 // byval and variadic arguments that are passed in registers. 3649 // We need to know this before we allocate the first byval or variadic 3650 // argument, as they will be allocated a stack slot below the CFA (Canonical 3651 // Frame Address, the stack pointer at entry to the function). 3652 unsigned ArgRegBegin = ARM::R4; 3653 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3654 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3655 break; 3656 3657 CCValAssign &VA = ArgLocs[i]; 3658 unsigned Index = VA.getValNo(); 3659 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3660 if (!Flags.isByVal()) 3661 continue; 3662 3663 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3664 unsigned RBegin, REnd; 3665 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3666 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3667 3668 CCInfo.nextInRegsParam(); 3669 } 3670 CCInfo.rewindByValRegsInfo(); 3671 3672 int lastInsIndex = -1; 3673 if (isVarArg && MFI.hasVAStart()) { 3674 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3675 if (RegIdx != array_lengthof(GPRArgRegs)) 3676 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3677 } 3678 3679 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3680 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3681 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3682 3683 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3684 CCValAssign &VA = ArgLocs[i]; 3685 if (Ins[VA.getValNo()].isOrigArg()) { 3686 std::advance(CurOrigArg, 3687 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3688 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3689 } 3690 // Arguments stored in registers. 3691 if (VA.isRegLoc()) { 3692 EVT RegVT = VA.getLocVT(); 3693 3694 if (VA.needsCustom()) { 3695 // f64 and vector types are split up into multiple registers or 3696 // combinations of registers and stack slots. 3697 if (VA.getLocVT() == MVT::v2f64) { 3698 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3699 Chain, DAG, dl); 3700 VA = ArgLocs[++i]; // skip ahead to next loc 3701 SDValue ArgValue2; 3702 if (VA.isMemLoc()) { 3703 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3704 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3705 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3706 MachinePointerInfo::getFixedStack( 3707 DAG.getMachineFunction(), FI)); 3708 } else { 3709 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3710 Chain, DAG, dl); 3711 } 3712 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3713 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3714 ArgValue, ArgValue1, 3715 DAG.getIntPtrConstant(0, dl)); 3716 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3717 ArgValue, ArgValue2, 3718 DAG.getIntPtrConstant(1, dl)); 3719 } else 3720 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3721 } else { 3722 const TargetRegisterClass *RC; 3723 3724 3725 if (RegVT == MVT::f16) 3726 RC = &ARM::HPRRegClass; 3727 else if (RegVT == MVT::f32) 3728 RC = &ARM::SPRRegClass; 3729 else if (RegVT == MVT::f64) 3730 RC = &ARM::DPRRegClass; 3731 else if (RegVT == MVT::v2f64) 3732 RC = &ARM::QPRRegClass; 3733 else if (RegVT == MVT::i32) 3734 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3735 : &ARM::GPRRegClass; 3736 else 3737 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3738 3739 // Transform the arguments in physical registers into virtual ones. 3740 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3741 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3742 } 3743 3744 // If this is an 8 or 16-bit value, it is really passed promoted 3745 // to 32 bits. Insert an assert[sz]ext to capture this, then 3746 // truncate to the right size. 3747 switch (VA.getLocInfo()) { 3748 default: llvm_unreachable("Unknown loc info!"); 3749 case CCValAssign::Full: break; 3750 case CCValAssign::BCvt: 3751 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3752 break; 3753 case CCValAssign::SExt: 3754 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3755 DAG.getValueType(VA.getValVT())); 3756 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3757 break; 3758 case CCValAssign::ZExt: 3759 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3760 DAG.getValueType(VA.getValVT())); 3761 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3762 break; 3763 } 3764 3765 InVals.push_back(ArgValue); 3766 } else { // VA.isRegLoc() 3767 // sanity check 3768 assert(VA.isMemLoc()); 3769 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3770 3771 int index = VA.getValNo(); 3772 3773 // Some Ins[] entries become multiple ArgLoc[] entries. 3774 // Process them only once. 3775 if (index != lastInsIndex) 3776 { 3777 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3778 // FIXME: For now, all byval parameter objects are marked mutable. 3779 // This can be changed with more analysis. 3780 // In case of tail call optimization mark all arguments mutable. 3781 // Since they could be overwritten by lowering of arguments in case of 3782 // a tail call. 3783 if (Flags.isByVal()) { 3784 assert(Ins[index].isOrigArg() && 3785 "Byval arguments cannot be implicit"); 3786 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3787 3788 int FrameIndex = StoreByValRegs( 3789 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3790 VA.getLocMemOffset(), Flags.getByValSize()); 3791 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3792 CCInfo.nextInRegsParam(); 3793 } else { 3794 unsigned FIOffset = VA.getLocMemOffset(); 3795 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3796 FIOffset, true); 3797 3798 // Create load nodes to retrieve arguments from the stack. 3799 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3800 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3801 MachinePointerInfo::getFixedStack( 3802 DAG.getMachineFunction(), FI))); 3803 } 3804 lastInsIndex = index; 3805 } 3806 } 3807 } 3808 3809 // varargs 3810 if (isVarArg && MFI.hasVAStart()) 3811 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3812 CCInfo.getNextStackOffset(), 3813 TotalArgRegsSaveSize); 3814 3815 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3816 3817 return Chain; 3818 } 3819 3820 /// isFloatingPointZero - Return true if this is +0.0. 3821 static bool isFloatingPointZero(SDValue Op) { 3822 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3823 return CFP->getValueAPF().isPosZero(); 3824 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3825 // Maybe this has already been legalized into the constant pool? 3826 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3827 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3828 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3829 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3830 return CFP->getValueAPF().isPosZero(); 3831 } 3832 } else if (Op->getOpcode() == ISD::BITCAST && 3833 Op->getValueType(0) == MVT::f64) { 3834 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3835 // created by LowerConstantFP(). 3836 SDValue BitcastOp = Op->getOperand(0); 3837 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3838 isNullConstant(BitcastOp->getOperand(0))) 3839 return true; 3840 } 3841 return false; 3842 } 3843 3844 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3845 /// the given operands. 3846 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3847 SDValue &ARMcc, SelectionDAG &DAG, 3848 const SDLoc &dl) const { 3849 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3850 unsigned C = RHSC->getZExtValue(); 3851 if (!isLegalICmpImmediate(C)) { 3852 // Constant does not fit, try adjusting it by one? 3853 switch (CC) { 3854 default: break; 3855 case ISD::SETLT: 3856 case ISD::SETGE: 3857 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3858 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3859 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3860 } 3861 break; 3862 case ISD::SETULT: 3863 case ISD::SETUGE: 3864 if (C != 0 && isLegalICmpImmediate(C-1)) { 3865 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3866 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3867 } 3868 break; 3869 case ISD::SETLE: 3870 case ISD::SETGT: 3871 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3872 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3873 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3874 } 3875 break; 3876 case ISD::SETULE: 3877 case ISD::SETUGT: 3878 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3879 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3880 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3881 } 3882 break; 3883 } 3884 } 3885 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 3886 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 3887 // In ARM and Thumb-2, the compare instructions can shift their second 3888 // operand. 3889 CC = ISD::getSetCCSwappedOperands(CC); 3890 std::swap(LHS, RHS); 3891 } 3892 3893 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3894 ARMISD::NodeType CompareType; 3895 switch (CondCode) { 3896 default: 3897 CompareType = ARMISD::CMP; 3898 break; 3899 case ARMCC::EQ: 3900 case ARMCC::NE: 3901 // Uses only Z Flag 3902 CompareType = ARMISD::CMPZ; 3903 break; 3904 } 3905 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3906 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3907 } 3908 3909 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3910 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3911 SelectionDAG &DAG, const SDLoc &dl, 3912 bool InvalidOnQNaN) const { 3913 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3914 SDValue Cmp; 3915 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3916 if (!isFloatingPointZero(RHS)) 3917 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3918 else 3919 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3920 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3921 } 3922 3923 /// duplicateCmp - Glue values can have only one use, so this function 3924 /// duplicates a comparison node. 3925 SDValue 3926 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3927 unsigned Opc = Cmp.getOpcode(); 3928 SDLoc DL(Cmp); 3929 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3930 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3931 3932 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3933 Cmp = Cmp.getOperand(0); 3934 Opc = Cmp.getOpcode(); 3935 if (Opc == ARMISD::CMPFP) 3936 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3937 Cmp.getOperand(1), Cmp.getOperand(2)); 3938 else { 3939 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3940 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3941 Cmp.getOperand(1)); 3942 } 3943 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3944 } 3945 3946 // This function returns three things: the arithmetic computation itself 3947 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 3948 // comparison and the condition code define the case in which the arithmetic 3949 // computation *does not* overflow. 3950 std::pair<SDValue, SDValue> 3951 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3952 SDValue &ARMcc) const { 3953 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3954 3955 SDValue Value, OverflowCmp; 3956 SDValue LHS = Op.getOperand(0); 3957 SDValue RHS = Op.getOperand(1); 3958 SDLoc dl(Op); 3959 3960 // FIXME: We are currently always generating CMPs because we don't support 3961 // generating CMN through the backend. This is not as good as the natural 3962 // CMP case because it causes a register dependency and cannot be folded 3963 // later. 3964 3965 switch (Op.getOpcode()) { 3966 default: 3967 llvm_unreachable("Unknown overflow instruction!"); 3968 case ISD::SADDO: 3969 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3970 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3971 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3972 break; 3973 case ISD::UADDO: 3974 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3975 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 3976 // We do not use it in the USUBO case as Value may not be used. 3977 Value = DAG.getNode(ARMISD::ADDC, dl, 3978 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 3979 .getValue(0); 3980 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3981 break; 3982 case ISD::SSUBO: 3983 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3984 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3985 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3986 break; 3987 case ISD::USUBO: 3988 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3989 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3990 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3991 break; 3992 case ISD::UMULO: 3993 // We generate a UMUL_LOHI and then check if the high word is 0. 3994 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 3995 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 3996 DAG.getVTList(Op.getValueType(), Op.getValueType()), 3997 LHS, RHS); 3998 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 3999 DAG.getConstant(0, dl, MVT::i32)); 4000 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4001 break; 4002 case ISD::SMULO: 4003 // We generate a SMUL_LOHI and then check if all the bits of the high word 4004 // are the same as the sign bit of the low word. 4005 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4006 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4007 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4008 LHS, RHS); 4009 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4010 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4011 Value.getValue(0), 4012 DAG.getConstant(31, dl, MVT::i32))); 4013 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4014 break; 4015 } // switch (...) 4016 4017 return std::make_pair(Value, OverflowCmp); 4018 } 4019 4020 SDValue 4021 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4022 // Let legalize expand this if it isn't a legal type yet. 4023 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4024 return SDValue(); 4025 4026 SDValue Value, OverflowCmp; 4027 SDValue ARMcc; 4028 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4029 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4030 SDLoc dl(Op); 4031 // We use 0 and 1 as false and true values. 4032 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4033 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4034 EVT VT = Op.getValueType(); 4035 4036 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4037 ARMcc, CCR, OverflowCmp); 4038 4039 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4040 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4041 } 4042 4043 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4044 SelectionDAG &DAG) { 4045 SDLoc DL(BoolCarry); 4046 EVT CarryVT = BoolCarry.getValueType(); 4047 4048 // This converts the boolean value carry into the carry flag by doing 4049 // ARMISD::SUBC Carry, 1 4050 return DAG.getNode(ARMISD::SUBC, DL, DAG.getVTList(CarryVT, MVT::i32), 4051 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4052 } 4053 4054 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4055 SelectionDAG &DAG) { 4056 SDLoc DL(Flags); 4057 4058 // Now convert the carry flag into a boolean carry. We do this 4059 // using ARMISD:ADDE 0, 0, Carry 4060 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4061 DAG.getConstant(0, DL, MVT::i32), 4062 DAG.getConstant(0, DL, MVT::i32), Flags); 4063 } 4064 4065 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4066 SelectionDAG &DAG) const { 4067 // Let legalize expand this if it isn't a legal type yet. 4068 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4069 return SDValue(); 4070 4071 SDValue LHS = Op.getOperand(0); 4072 SDValue RHS = Op.getOperand(1); 4073 SDLoc dl(Op); 4074 4075 EVT VT = Op.getValueType(); 4076 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4077 SDValue Value; 4078 SDValue Overflow; 4079 switch (Op.getOpcode()) { 4080 default: 4081 llvm_unreachable("Unknown overflow instruction!"); 4082 case ISD::UADDO: 4083 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4084 // Convert the carry flag into a boolean value. 4085 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4086 break; 4087 case ISD::USUBO: { 4088 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4089 // Convert the carry flag into a boolean value. 4090 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4091 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4092 // value. So compute 1 - C. 4093 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4094 DAG.getConstant(1, dl, MVT::i32), Overflow); 4095 break; 4096 } 4097 } 4098 4099 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4100 } 4101 4102 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4103 SDValue Cond = Op.getOperand(0); 4104 SDValue SelectTrue = Op.getOperand(1); 4105 SDValue SelectFalse = Op.getOperand(2); 4106 SDLoc dl(Op); 4107 unsigned Opc = Cond.getOpcode(); 4108 4109 if (Cond.getResNo() == 1 && 4110 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4111 Opc == ISD::USUBO)) { 4112 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4113 return SDValue(); 4114 4115 SDValue Value, OverflowCmp; 4116 SDValue ARMcc; 4117 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4118 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4119 EVT VT = Op.getValueType(); 4120 4121 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4122 OverflowCmp, DAG); 4123 } 4124 4125 // Convert: 4126 // 4127 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4128 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4129 // 4130 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4131 const ConstantSDNode *CMOVTrue = 4132 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4133 const ConstantSDNode *CMOVFalse = 4134 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4135 4136 if (CMOVTrue && CMOVFalse) { 4137 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4138 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4139 4140 SDValue True; 4141 SDValue False; 4142 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4143 True = SelectTrue; 4144 False = SelectFalse; 4145 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4146 True = SelectFalse; 4147 False = SelectTrue; 4148 } 4149 4150 if (True.getNode() && False.getNode()) { 4151 EVT VT = Op.getValueType(); 4152 SDValue ARMcc = Cond.getOperand(2); 4153 SDValue CCR = Cond.getOperand(3); 4154 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4155 assert(True.getValueType() == VT); 4156 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4157 } 4158 } 4159 } 4160 4161 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4162 // undefined bits before doing a full-word comparison with zero. 4163 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4164 DAG.getConstant(1, dl, Cond.getValueType())); 4165 4166 return DAG.getSelectCC(dl, Cond, 4167 DAG.getConstant(0, dl, Cond.getValueType()), 4168 SelectTrue, SelectFalse, ISD::SETNE); 4169 } 4170 4171 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4172 bool &swpCmpOps, bool &swpVselOps) { 4173 // Start by selecting the GE condition code for opcodes that return true for 4174 // 'equality' 4175 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4176 CC == ISD::SETULE) 4177 CondCode = ARMCC::GE; 4178 4179 // and GT for opcodes that return false for 'equality'. 4180 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4181 CC == ISD::SETULT) 4182 CondCode = ARMCC::GT; 4183 4184 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4185 // to swap the compare operands. 4186 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4187 CC == ISD::SETULT) 4188 swpCmpOps = true; 4189 4190 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4191 // If we have an unordered opcode, we need to swap the operands to the VSEL 4192 // instruction (effectively negating the condition). 4193 // 4194 // This also has the effect of swapping which one of 'less' or 'greater' 4195 // returns true, so we also swap the compare operands. It also switches 4196 // whether we return true for 'equality', so we compensate by picking the 4197 // opposite condition code to our original choice. 4198 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4199 CC == ISD::SETUGT) { 4200 swpCmpOps = !swpCmpOps; 4201 swpVselOps = !swpVselOps; 4202 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4203 } 4204 4205 // 'ordered' is 'anything but unordered', so use the VS condition code and 4206 // swap the VSEL operands. 4207 if (CC == ISD::SETO) { 4208 CondCode = ARMCC::VS; 4209 swpVselOps = true; 4210 } 4211 4212 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4213 // code and swap the VSEL operands. 4214 if (CC == ISD::SETUNE) { 4215 CondCode = ARMCC::EQ; 4216 swpVselOps = true; 4217 } 4218 } 4219 4220 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4221 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4222 SDValue Cmp, SelectionDAG &DAG) const { 4223 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4224 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4225 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4226 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4227 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4228 4229 SDValue TrueLow = TrueVal.getValue(0); 4230 SDValue TrueHigh = TrueVal.getValue(1); 4231 SDValue FalseLow = FalseVal.getValue(0); 4232 SDValue FalseHigh = FalseVal.getValue(1); 4233 4234 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4235 ARMcc, CCR, Cmp); 4236 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4237 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4238 4239 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4240 } else { 4241 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4242 Cmp); 4243 } 4244 } 4245 4246 static bool isGTorGE(ISD::CondCode CC) { 4247 return CC == ISD::SETGT || CC == ISD::SETGE; 4248 } 4249 4250 static bool isLTorLE(ISD::CondCode CC) { 4251 return CC == ISD::SETLT || CC == ISD::SETLE; 4252 } 4253 4254 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4255 // All of these conditions (and their <= and >= counterparts) will do: 4256 // x < k ? k : x 4257 // x > k ? x : k 4258 // k < x ? x : k 4259 // k > x ? k : x 4260 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4261 const SDValue TrueVal, const SDValue FalseVal, 4262 const ISD::CondCode CC, const SDValue K) { 4263 return (isGTorGE(CC) && 4264 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4265 (isLTorLE(CC) && 4266 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4267 } 4268 4269 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4270 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4271 const SDValue TrueVal, const SDValue FalseVal, 4272 const ISD::CondCode CC, const SDValue K) { 4273 return (isGTorGE(CC) && 4274 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4275 (isLTorLE(CC) && 4276 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4277 } 4278 4279 // Check if two chained conditionals could be converted into SSAT or USAT. 4280 // 4281 // SSAT can replace a set of two conditional selectors that bound a number to an 4282 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4283 // 4284 // x < -k ? -k : (x > k ? k : x) 4285 // x < -k ? -k : (x < k ? x : k) 4286 // x > -k ? (x > k ? k : x) : -k 4287 // x < k ? (x < -k ? -k : x) : k 4288 // etc. 4289 // 4290 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4291 // a power of 2. 4292 // 4293 // It returns true if the conversion can be done, false otherwise. 4294 // Additionally, the variable is returned in parameter V, the constant in K and 4295 // usat is set to true if the conditional represents an unsigned saturation 4296 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4297 uint64_t &K, bool &usat) { 4298 SDValue LHS1 = Op.getOperand(0); 4299 SDValue RHS1 = Op.getOperand(1); 4300 SDValue TrueVal1 = Op.getOperand(2); 4301 SDValue FalseVal1 = Op.getOperand(3); 4302 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4303 4304 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4305 if (Op2.getOpcode() != ISD::SELECT_CC) 4306 return false; 4307 4308 SDValue LHS2 = Op2.getOperand(0); 4309 SDValue RHS2 = Op2.getOperand(1); 4310 SDValue TrueVal2 = Op2.getOperand(2); 4311 SDValue FalseVal2 = Op2.getOperand(3); 4312 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4313 4314 // Find out which are the constants and which are the variables 4315 // in each conditional 4316 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4317 ? &RHS1 4318 : nullptr; 4319 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4320 ? &RHS2 4321 : nullptr; 4322 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4323 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4324 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4325 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4326 4327 // We must detect cases where the original operations worked with 16- or 4328 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4329 // must work with sign-extended values but the select operations return 4330 // the original non-extended value. 4331 SDValue V2TmpReg = V2Tmp; 4332 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4333 V2TmpReg = V2Tmp->getOperand(0); 4334 4335 // Check that the registers and the constants have the correct values 4336 // in both conditionals 4337 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4338 V2TmpReg != V2) 4339 return false; 4340 4341 // Figure out which conditional is saturating the lower/upper bound. 4342 const SDValue *LowerCheckOp = 4343 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4344 ? &Op 4345 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4346 ? &Op2 4347 : nullptr; 4348 const SDValue *UpperCheckOp = 4349 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4350 ? &Op 4351 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4352 ? &Op2 4353 : nullptr; 4354 4355 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4356 return false; 4357 4358 // Check that the constant in the lower-bound check is 4359 // the opposite of the constant in the upper-bound check 4360 // in 1's complement. 4361 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4362 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4363 int64_t PosVal = std::max(Val1, Val2); 4364 int64_t NegVal = std::min(Val1, Val2); 4365 4366 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4367 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4368 isPowerOf2_64(PosVal + 1)) { 4369 4370 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4371 if (Val1 == ~Val2) 4372 usat = false; 4373 else if (NegVal == 0) 4374 usat = true; 4375 else 4376 return false; 4377 4378 V = V2; 4379 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4380 4381 return true; 4382 } 4383 4384 return false; 4385 } 4386 4387 // Check if a condition of the type x < k ? k : x can be converted into a 4388 // bit operation instead of conditional moves. 4389 // Currently this is allowed given: 4390 // - The conditions and values match up 4391 // - k is 0 or -1 (all ones) 4392 // This function will not check the last condition, thats up to the caller 4393 // It returns true if the transformation can be made, and in such case 4394 // returns x in V, and k in SatK. 4395 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4396 SDValue &SatK) 4397 { 4398 SDValue LHS = Op.getOperand(0); 4399 SDValue RHS = Op.getOperand(1); 4400 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4401 SDValue TrueVal = Op.getOperand(2); 4402 SDValue FalseVal = Op.getOperand(3); 4403 4404 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4405 ? &RHS 4406 : nullptr; 4407 4408 // No constant operation in comparison, early out 4409 if (!K) 4410 return false; 4411 4412 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4413 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4414 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4415 4416 // If the constant on left and right side, or variable on left and right, 4417 // does not match, early out 4418 if (*K != KTmp || V != VTmp) 4419 return false; 4420 4421 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4422 SatK = *K; 4423 return true; 4424 } 4425 4426 return false; 4427 } 4428 4429 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4430 EVT VT = Op.getValueType(); 4431 SDLoc dl(Op); 4432 4433 // Try to convert two saturating conditional selects into a single SSAT 4434 SDValue SatValue; 4435 uint64_t SatConstant; 4436 bool SatUSat; 4437 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4438 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4439 if (SatUSat) 4440 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4441 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4442 else 4443 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4444 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4445 } 4446 4447 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4448 // into more efficient bit operations, which is possible when k is 0 or -1 4449 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4450 // single instructions. On Thumb the shift and the bit operation will be two 4451 // instructions. 4452 // Only allow this transformation on full-width (32-bit) operations 4453 SDValue LowerSatConstant; 4454 if (VT == MVT::i32 && 4455 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4456 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4457 DAG.getConstant(31, dl, VT)); 4458 if (isNullConstant(LowerSatConstant)) { 4459 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4460 DAG.getAllOnesConstant(dl, VT)); 4461 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4462 } else if (isAllOnesConstant(LowerSatConstant)) 4463 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4464 } 4465 4466 SDValue LHS = Op.getOperand(0); 4467 SDValue RHS = Op.getOperand(1); 4468 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4469 SDValue TrueVal = Op.getOperand(2); 4470 SDValue FalseVal = Op.getOperand(3); 4471 4472 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4473 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4474 dl); 4475 4476 // If softenSetCCOperands only returned one value, we should compare it to 4477 // zero. 4478 if (!RHS.getNode()) { 4479 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4480 CC = ISD::SETNE; 4481 } 4482 } 4483 4484 if (LHS.getValueType() == MVT::i32) { 4485 // Try to generate VSEL on ARMv8. 4486 // The VSEL instruction can't use all the usual ARM condition 4487 // codes: it only has two bits to select the condition code, so it's 4488 // constrained to use only GE, GT, VS and EQ. 4489 // 4490 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4491 // swap the operands of the previous compare instruction (effectively 4492 // inverting the compare condition, swapping 'less' and 'greater') and 4493 // sometimes need to swap the operands to the VSEL (which inverts the 4494 // condition in the sense of firing whenever the previous condition didn't) 4495 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4496 TrueVal.getValueType() == MVT::f64)) { 4497 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4498 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4499 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4500 CC = ISD::getSetCCInverse(CC, true); 4501 std::swap(TrueVal, FalseVal); 4502 } 4503 } 4504 4505 SDValue ARMcc; 4506 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4507 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4508 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4509 } 4510 4511 ARMCC::CondCodes CondCode, CondCode2; 4512 bool InvalidOnQNaN; 4513 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4514 4515 // Try to generate VMAXNM/VMINNM on ARMv8. 4516 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4517 TrueVal.getValueType() == MVT::f64)) { 4518 bool swpCmpOps = false; 4519 bool swpVselOps = false; 4520 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4521 4522 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4523 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4524 if (swpCmpOps) 4525 std::swap(LHS, RHS); 4526 if (swpVselOps) 4527 std::swap(TrueVal, FalseVal); 4528 } 4529 } 4530 4531 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4532 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4533 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4534 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4535 if (CondCode2 != ARMCC::AL) { 4536 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4537 // FIXME: Needs another CMP because flag can have but one use. 4538 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4539 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4540 } 4541 return Result; 4542 } 4543 4544 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4545 /// to morph to an integer compare sequence. 4546 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4547 const ARMSubtarget *Subtarget) { 4548 SDNode *N = Op.getNode(); 4549 if (!N->hasOneUse()) 4550 // Otherwise it requires moving the value from fp to integer registers. 4551 return false; 4552 if (!N->getNumValues()) 4553 return false; 4554 EVT VT = Op.getValueType(); 4555 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4556 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4557 // vmrs are very slow, e.g. cortex-a8. 4558 return false; 4559 4560 if (isFloatingPointZero(Op)) { 4561 SeenZero = true; 4562 return true; 4563 } 4564 return ISD::isNormalLoad(N); 4565 } 4566 4567 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4568 if (isFloatingPointZero(Op)) 4569 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4570 4571 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4572 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4573 Ld->getPointerInfo(), Ld->getAlignment(), 4574 Ld->getMemOperand()->getFlags()); 4575 4576 llvm_unreachable("Unknown VFP cmp argument!"); 4577 } 4578 4579 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4580 SDValue &RetVal1, SDValue &RetVal2) { 4581 SDLoc dl(Op); 4582 4583 if (isFloatingPointZero(Op)) { 4584 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4585 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4586 return; 4587 } 4588 4589 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4590 SDValue Ptr = Ld->getBasePtr(); 4591 RetVal1 = 4592 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4593 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4594 4595 EVT PtrType = Ptr.getValueType(); 4596 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4597 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4598 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4599 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4600 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4601 Ld->getMemOperand()->getFlags()); 4602 return; 4603 } 4604 4605 llvm_unreachable("Unknown VFP cmp argument!"); 4606 } 4607 4608 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4609 /// f32 and even f64 comparisons to integer ones. 4610 SDValue 4611 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4612 SDValue Chain = Op.getOperand(0); 4613 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4614 SDValue LHS = Op.getOperand(2); 4615 SDValue RHS = Op.getOperand(3); 4616 SDValue Dest = Op.getOperand(4); 4617 SDLoc dl(Op); 4618 4619 bool LHSSeenZero = false; 4620 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4621 bool RHSSeenZero = false; 4622 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4623 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4624 // If unsafe fp math optimization is enabled and there are no other uses of 4625 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4626 // to an integer comparison. 4627 if (CC == ISD::SETOEQ) 4628 CC = ISD::SETEQ; 4629 else if (CC == ISD::SETUNE) 4630 CC = ISD::SETNE; 4631 4632 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4633 SDValue ARMcc; 4634 if (LHS.getValueType() == MVT::f32) { 4635 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4636 bitcastf32Toi32(LHS, DAG), Mask); 4637 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4638 bitcastf32Toi32(RHS, DAG), Mask); 4639 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4640 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4641 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4642 Chain, Dest, ARMcc, CCR, Cmp); 4643 } 4644 4645 SDValue LHS1, LHS2; 4646 SDValue RHS1, RHS2; 4647 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4648 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4649 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4650 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4651 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4652 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4653 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4654 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4655 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4656 } 4657 4658 return SDValue(); 4659 } 4660 4661 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4662 SDValue Chain = Op.getOperand(0); 4663 SDValue Cond = Op.getOperand(1); 4664 SDValue Dest = Op.getOperand(2); 4665 SDLoc dl(Op); 4666 4667 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4668 // instruction. 4669 unsigned Opc = Cond.getOpcode(); 4670 if (Cond.getResNo() == 1 && 4671 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4672 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 4673 // Only lower legal XALUO ops. 4674 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4675 return SDValue(); 4676 4677 // The actual operation with overflow check. 4678 SDValue Value, OverflowCmp; 4679 SDValue ARMcc; 4680 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4681 4682 // Reverse the condition code. 4683 ARMCC::CondCodes CondCode = 4684 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4685 CondCode = ARMCC::getOppositeCondition(CondCode); 4686 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4687 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4688 4689 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4690 OverflowCmp); 4691 } 4692 4693 return SDValue(); 4694 } 4695 4696 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4697 SDValue Chain = Op.getOperand(0); 4698 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4699 SDValue LHS = Op.getOperand(2); 4700 SDValue RHS = Op.getOperand(3); 4701 SDValue Dest = Op.getOperand(4); 4702 SDLoc dl(Op); 4703 4704 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4705 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4706 dl); 4707 4708 // If softenSetCCOperands only returned one value, we should compare it to 4709 // zero. 4710 if (!RHS.getNode()) { 4711 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4712 CC = ISD::SETNE; 4713 } 4714 } 4715 4716 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4717 // instruction. 4718 unsigned Opc = LHS.getOpcode(); 4719 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 4720 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4721 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO) && 4722 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4723 // Only lower legal XALUO ops. 4724 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4725 return SDValue(); 4726 4727 // The actual operation with overflow check. 4728 SDValue Value, OverflowCmp; 4729 SDValue ARMcc; 4730 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 4731 4732 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 4733 // Reverse the condition code. 4734 ARMCC::CondCodes CondCode = 4735 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4736 CondCode = ARMCC::getOppositeCondition(CondCode); 4737 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4738 } 4739 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4740 4741 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4742 OverflowCmp); 4743 } 4744 4745 if (LHS.getValueType() == MVT::i32) { 4746 SDValue ARMcc; 4747 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4748 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4749 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4750 Chain, Dest, ARMcc, CCR, Cmp); 4751 } 4752 4753 if (getTargetMachine().Options.UnsafeFPMath && 4754 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4755 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4756 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4757 return Result; 4758 } 4759 4760 ARMCC::CondCodes CondCode, CondCode2; 4761 bool InvalidOnQNaN; 4762 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4763 4764 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4765 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4766 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4767 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4768 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4769 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4770 if (CondCode2 != ARMCC::AL) { 4771 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4772 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4773 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4774 } 4775 return Res; 4776 } 4777 4778 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4779 SDValue Chain = Op.getOperand(0); 4780 SDValue Table = Op.getOperand(1); 4781 SDValue Index = Op.getOperand(2); 4782 SDLoc dl(Op); 4783 4784 EVT PTy = getPointerTy(DAG.getDataLayout()); 4785 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4786 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4787 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4788 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4789 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 4790 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4791 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4792 // which does another jump to the destination. This also makes it easier 4793 // to translate it to TBB / TBH later (Thumb2 only). 4794 // FIXME: This might not work if the function is extremely large. 4795 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4796 Addr, Op.getOperand(2), JTI); 4797 } 4798 if (isPositionIndependent() || Subtarget->isROPI()) { 4799 Addr = 4800 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4801 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4802 Chain = Addr.getValue(1); 4803 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 4804 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4805 } else { 4806 Addr = 4807 DAG.getLoad(PTy, dl, Chain, Addr, 4808 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4809 Chain = Addr.getValue(1); 4810 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4811 } 4812 } 4813 4814 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4815 EVT VT = Op.getValueType(); 4816 SDLoc dl(Op); 4817 4818 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4819 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4820 return Op; 4821 return DAG.UnrollVectorOp(Op.getNode()); 4822 } 4823 4824 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4825 "Invalid type for custom lowering!"); 4826 if (VT != MVT::v4i16) 4827 return DAG.UnrollVectorOp(Op.getNode()); 4828 4829 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4830 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4831 } 4832 4833 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4834 EVT VT = Op.getValueType(); 4835 if (VT.isVector()) 4836 return LowerVectorFP_TO_INT(Op, DAG); 4837 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4838 RTLIB::Libcall LC; 4839 if (Op.getOpcode() == ISD::FP_TO_SINT) 4840 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4841 Op.getValueType()); 4842 else 4843 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4844 Op.getValueType()); 4845 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4846 /*isSigned*/ false, SDLoc(Op)).first; 4847 } 4848 4849 return Op; 4850 } 4851 4852 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4853 EVT VT = Op.getValueType(); 4854 SDLoc dl(Op); 4855 4856 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4857 if (VT.getVectorElementType() == MVT::f32) 4858 return Op; 4859 return DAG.UnrollVectorOp(Op.getNode()); 4860 } 4861 4862 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4863 "Invalid type for custom lowering!"); 4864 if (VT != MVT::v4f32) 4865 return DAG.UnrollVectorOp(Op.getNode()); 4866 4867 unsigned CastOpc; 4868 unsigned Opc; 4869 switch (Op.getOpcode()) { 4870 default: llvm_unreachable("Invalid opcode!"); 4871 case ISD::SINT_TO_FP: 4872 CastOpc = ISD::SIGN_EXTEND; 4873 Opc = ISD::SINT_TO_FP; 4874 break; 4875 case ISD::UINT_TO_FP: 4876 CastOpc = ISD::ZERO_EXTEND; 4877 Opc = ISD::UINT_TO_FP; 4878 break; 4879 } 4880 4881 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4882 return DAG.getNode(Opc, dl, VT, Op); 4883 } 4884 4885 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4886 EVT VT = Op.getValueType(); 4887 if (VT.isVector()) 4888 return LowerVectorINT_TO_FP(Op, DAG); 4889 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4890 RTLIB::Libcall LC; 4891 if (Op.getOpcode() == ISD::SINT_TO_FP) 4892 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4893 Op.getValueType()); 4894 else 4895 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4896 Op.getValueType()); 4897 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4898 /*isSigned*/ false, SDLoc(Op)).first; 4899 } 4900 4901 return Op; 4902 } 4903 4904 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4905 // Implement fcopysign with a fabs and a conditional fneg. 4906 SDValue Tmp0 = Op.getOperand(0); 4907 SDValue Tmp1 = Op.getOperand(1); 4908 SDLoc dl(Op); 4909 EVT VT = Op.getValueType(); 4910 EVT SrcVT = Tmp1.getValueType(); 4911 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4912 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4913 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4914 4915 if (UseNEON) { 4916 // Use VBSL to copy the sign bit. 4917 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4918 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4919 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4920 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4921 if (VT == MVT::f64) 4922 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4923 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4924 DAG.getConstant(32, dl, MVT::i32)); 4925 else /*if (VT == MVT::f32)*/ 4926 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4927 if (SrcVT == MVT::f32) { 4928 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4929 if (VT == MVT::f64) 4930 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4931 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4932 DAG.getConstant(32, dl, MVT::i32)); 4933 } else if (VT == MVT::f32) 4934 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4935 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4936 DAG.getConstant(32, dl, MVT::i32)); 4937 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4938 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4939 4940 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4941 dl, MVT::i32); 4942 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4943 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4944 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4945 4946 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4947 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4948 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4949 if (VT == MVT::f32) { 4950 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4951 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4952 DAG.getConstant(0, dl, MVT::i32)); 4953 } else { 4954 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4955 } 4956 4957 return Res; 4958 } 4959 4960 // Bitcast operand 1 to i32. 4961 if (SrcVT == MVT::f64) 4962 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4963 Tmp1).getValue(1); 4964 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4965 4966 // Or in the signbit with integer operations. 4967 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4968 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4969 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4970 if (VT == MVT::f32) { 4971 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4972 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4973 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4974 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4975 } 4976 4977 // f64: Or the high part with signbit and then combine two parts. 4978 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4979 Tmp0); 4980 SDValue Lo = Tmp0.getValue(0); 4981 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4982 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4983 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4984 } 4985 4986 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4987 MachineFunction &MF = DAG.getMachineFunction(); 4988 MachineFrameInfo &MFI = MF.getFrameInfo(); 4989 MFI.setReturnAddressIsTaken(true); 4990 4991 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4992 return SDValue(); 4993 4994 EVT VT = Op.getValueType(); 4995 SDLoc dl(Op); 4996 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4997 if (Depth) { 4998 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4999 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5000 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5001 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5002 MachinePointerInfo()); 5003 } 5004 5005 // Return LR, which contains the return address. Mark it an implicit live-in. 5006 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5007 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5008 } 5009 5010 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5011 const ARMBaseRegisterInfo &ARI = 5012 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5013 MachineFunction &MF = DAG.getMachineFunction(); 5014 MachineFrameInfo &MFI = MF.getFrameInfo(); 5015 MFI.setFrameAddressIsTaken(true); 5016 5017 EVT VT = Op.getValueType(); 5018 SDLoc dl(Op); // FIXME probably not meaningful 5019 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5020 unsigned FrameReg = ARI.getFrameRegister(MF); 5021 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5022 while (Depth--) 5023 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5024 MachinePointerInfo()); 5025 return FrameAddr; 5026 } 5027 5028 // FIXME? Maybe this could be a TableGen attribute on some registers and 5029 // this table could be generated automatically from RegInfo. 5030 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5031 SelectionDAG &DAG) const { 5032 unsigned Reg = StringSwitch<unsigned>(RegName) 5033 .Case("sp", ARM::SP) 5034 .Default(0); 5035 if (Reg) 5036 return Reg; 5037 report_fatal_error(Twine("Invalid register name \"" 5038 + StringRef(RegName) + "\".")); 5039 } 5040 5041 // Result is 64 bit value so split into two 32 bit values and return as a 5042 // pair of values. 5043 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5044 SelectionDAG &DAG) { 5045 SDLoc DL(N); 5046 5047 // This function is only supposed to be called for i64 type destination. 5048 assert(N->getValueType(0) == MVT::i64 5049 && "ExpandREAD_REGISTER called for non-i64 type result."); 5050 5051 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5052 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5053 N->getOperand(0), 5054 N->getOperand(1)); 5055 5056 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5057 Read.getValue(1))); 5058 Results.push_back(Read.getOperand(0)); 5059 } 5060 5061 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5062 /// When \p DstVT, the destination type of \p BC, is on the vector 5063 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5064 /// it might be possible to combine them, such that everything stays on the 5065 /// vector register bank. 5066 /// \p return The node that would replace \p BT, if the combine 5067 /// is possible. 5068 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5069 SelectionDAG &DAG) { 5070 SDValue Op = BC->getOperand(0); 5071 EVT DstVT = BC->getValueType(0); 5072 5073 // The only vector instruction that can produce a scalar (remember, 5074 // since the bitcast was about to be turned into VMOVDRR, the source 5075 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5076 // Moreover, we can do this combine only if there is one use. 5077 // Finally, if the destination type is not a vector, there is not 5078 // much point on forcing everything on the vector bank. 5079 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5080 !Op.hasOneUse()) 5081 return SDValue(); 5082 5083 // If the index is not constant, we will introduce an additional 5084 // multiply that will stick. 5085 // Give up in that case. 5086 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5087 if (!Index) 5088 return SDValue(); 5089 unsigned DstNumElt = DstVT.getVectorNumElements(); 5090 5091 // Compute the new index. 5092 const APInt &APIntIndex = Index->getAPIntValue(); 5093 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5094 NewIndex *= APIntIndex; 5095 // Check if the new constant index fits into i32. 5096 if (NewIndex.getBitWidth() > 32) 5097 return SDValue(); 5098 5099 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5100 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5101 SDLoc dl(Op); 5102 SDValue ExtractSrc = Op.getOperand(0); 5103 EVT VecVT = EVT::getVectorVT( 5104 *DAG.getContext(), DstVT.getScalarType(), 5105 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5106 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5107 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5108 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5109 } 5110 5111 /// ExpandBITCAST - If the target supports VFP, this function is called to 5112 /// expand a bit convert where either the source or destination type is i64 to 5113 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5114 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5115 /// vectors), since the legalizer won't know what to do with that. 5116 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5117 const ARMSubtarget *Subtarget) { 5118 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5119 SDLoc dl(N); 5120 SDValue Op = N->getOperand(0); 5121 5122 // This function is only supposed to be called for i64 types, either as the 5123 // source or destination of the bit convert. 5124 EVT SrcVT = Op.getValueType(); 5125 EVT DstVT = N->getValueType(0); 5126 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5127 5128 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5129 // FullFP16: half values are passed in S-registers, and we don't 5130 // need any of the bitcast and moves: 5131 // 5132 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5133 // t5: i32 = bitcast t2 5134 // t18: f16 = ARMISD::VMOVhr t5 5135 if (Op.getOpcode() != ISD::CopyFromReg || 5136 Op.getValueType() != MVT::f32) 5137 return SDValue(); 5138 5139 auto Move = N->use_begin(); 5140 if (Move->getOpcode() != ARMISD::VMOVhr) 5141 return SDValue(); 5142 5143 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5144 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5145 DAG.ReplaceAllUsesWith(*Move, &Copy); 5146 return Copy; 5147 } 5148 5149 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5150 if (!HasFullFP16) 5151 return SDValue(); 5152 // SoftFP: read half-precision arguments: 5153 // 5154 // t2: i32,ch = ... 5155 // t7: i16 = truncate t2 <~~~~ Op 5156 // t8: f16 = bitcast t7 <~~~~ N 5157 // 5158 if (Op.getOperand(0).getValueType() == MVT::i32) 5159 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5160 MVT::f16, Op.getOperand(0)); 5161 5162 return SDValue(); 5163 } 5164 5165 // Half-precision return values 5166 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5167 if (!HasFullFP16) 5168 return SDValue(); 5169 // 5170 // t11: f16 = fadd t8, t10 5171 // t12: i16 = bitcast t11 <~~~ SDNode N 5172 // t13: i32 = zero_extend t12 5173 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5174 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5175 // 5176 // transform this into: 5177 // 5178 // t20: i32 = ARMISD::VMOVrh t11 5179 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5180 // 5181 auto ZeroExtend = N->use_begin(); 5182 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5183 ZeroExtend->getValueType(0) != MVT::i32) 5184 return SDValue(); 5185 5186 auto Copy = ZeroExtend->use_begin(); 5187 if (Copy->getOpcode() == ISD::CopyToReg && 5188 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5189 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5190 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5191 return Cvt; 5192 } 5193 return SDValue(); 5194 } 5195 5196 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5197 return SDValue(); 5198 5199 // Turn i64->f64 into VMOVDRR. 5200 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5201 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5202 // if we can combine the bitcast with its source. 5203 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5204 return Val; 5205 5206 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5207 DAG.getConstant(0, dl, MVT::i32)); 5208 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5209 DAG.getConstant(1, dl, MVT::i32)); 5210 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5211 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5212 } 5213 5214 // Turn f64->i64 into VMOVRRD. 5215 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5216 SDValue Cvt; 5217 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5218 SrcVT.getVectorNumElements() > 1) 5219 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5220 DAG.getVTList(MVT::i32, MVT::i32), 5221 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5222 else 5223 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5224 DAG.getVTList(MVT::i32, MVT::i32), Op); 5225 // Merge the pieces into a single i64 value. 5226 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5227 } 5228 5229 return SDValue(); 5230 } 5231 5232 /// getZeroVector - Returns a vector of specified type with all zero elements. 5233 /// Zero vectors are used to represent vector negation and in those cases 5234 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5235 /// not support i64 elements, so sometimes the zero vectors will need to be 5236 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5237 /// zero vector. 5238 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5239 assert(VT.isVector() && "Expected a vector type"); 5240 // The canonical modified immediate encoding of a zero vector is....0! 5241 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5242 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5243 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5244 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5245 } 5246 5247 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5248 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5249 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5250 SelectionDAG &DAG) const { 5251 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5252 EVT VT = Op.getValueType(); 5253 unsigned VTBits = VT.getSizeInBits(); 5254 SDLoc dl(Op); 5255 SDValue ShOpLo = Op.getOperand(0); 5256 SDValue ShOpHi = Op.getOperand(1); 5257 SDValue ShAmt = Op.getOperand(2); 5258 SDValue ARMcc; 5259 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5260 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5261 5262 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5263 5264 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5265 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5266 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5267 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5268 DAG.getConstant(VTBits, dl, MVT::i32)); 5269 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5270 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5271 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5272 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5273 ISD::SETGE, ARMcc, DAG, dl); 5274 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5275 ARMcc, CCR, CmpLo); 5276 5277 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5278 SDValue HiBigShift = Opc == ISD::SRA 5279 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5280 DAG.getConstant(VTBits - 1, dl, VT)) 5281 : DAG.getConstant(0, dl, VT); 5282 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5283 ISD::SETGE, ARMcc, DAG, dl); 5284 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5285 ARMcc, CCR, CmpHi); 5286 5287 SDValue Ops[2] = { Lo, Hi }; 5288 return DAG.getMergeValues(Ops, dl); 5289 } 5290 5291 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5292 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5293 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5294 SelectionDAG &DAG) const { 5295 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5296 EVT VT = Op.getValueType(); 5297 unsigned VTBits = VT.getSizeInBits(); 5298 SDLoc dl(Op); 5299 SDValue ShOpLo = Op.getOperand(0); 5300 SDValue ShOpHi = Op.getOperand(1); 5301 SDValue ShAmt = Op.getOperand(2); 5302 SDValue ARMcc; 5303 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5304 5305 assert(Op.getOpcode() == ISD::SHL_PARTS); 5306 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5307 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5308 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5309 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5310 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5311 5312 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5313 DAG.getConstant(VTBits, dl, MVT::i32)); 5314 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5315 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5316 ISD::SETGE, ARMcc, DAG, dl); 5317 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5318 ARMcc, CCR, CmpHi); 5319 5320 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5321 ISD::SETGE, ARMcc, DAG, dl); 5322 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5323 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5324 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5325 5326 SDValue Ops[2] = { Lo, Hi }; 5327 return DAG.getMergeValues(Ops, dl); 5328 } 5329 5330 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5331 SelectionDAG &DAG) const { 5332 // The rounding mode is in bits 23:22 of the FPSCR. 5333 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5334 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5335 // so that the shift + and get folded into a bitfield extract. 5336 SDLoc dl(Op); 5337 SDValue Ops[] = { DAG.getEntryNode(), 5338 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5339 5340 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5341 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5342 DAG.getConstant(1U << 22, dl, MVT::i32)); 5343 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5344 DAG.getConstant(22, dl, MVT::i32)); 5345 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5346 DAG.getConstant(3, dl, MVT::i32)); 5347 } 5348 5349 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5350 const ARMSubtarget *ST) { 5351 SDLoc dl(N); 5352 EVT VT = N->getValueType(0); 5353 if (VT.isVector()) { 5354 assert(ST->hasNEON()); 5355 5356 // Compute the least significant set bit: LSB = X & -X 5357 SDValue X = N->getOperand(0); 5358 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5359 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5360 5361 EVT ElemTy = VT.getVectorElementType(); 5362 5363 if (ElemTy == MVT::i8) { 5364 // Compute with: cttz(x) = ctpop(lsb - 1) 5365 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5366 DAG.getTargetConstant(1, dl, ElemTy)); 5367 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5368 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5369 } 5370 5371 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5372 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5373 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5374 unsigned NumBits = ElemTy.getSizeInBits(); 5375 SDValue WidthMinus1 = 5376 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5377 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5378 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5379 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5380 } 5381 5382 // Compute with: cttz(x) = ctpop(lsb - 1) 5383 5384 // Since we can only compute the number of bits in a byte with vcnt.8, we 5385 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 5386 // and i64. 5387 5388 // Compute LSB - 1. 5389 SDValue Bits; 5390 if (ElemTy == MVT::i64) { 5391 // Load constant 0xffff'ffff'ffff'ffff to register. 5392 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5393 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5394 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5395 } else { 5396 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5397 DAG.getTargetConstant(1, dl, ElemTy)); 5398 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5399 } 5400 5401 // Count #bits with vcnt.8. 5402 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5403 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 5404 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 5405 5406 // Gather the #bits with vpaddl (pairwise add.) 5407 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5408 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 5409 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5410 Cnt8); 5411 if (ElemTy == MVT::i16) 5412 return Cnt16; 5413 5414 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 5415 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 5416 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5417 Cnt16); 5418 if (ElemTy == MVT::i32) 5419 return Cnt32; 5420 5421 assert(ElemTy == MVT::i64); 5422 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5423 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5424 Cnt32); 5425 return Cnt64; 5426 } 5427 5428 if (!ST->hasV6T2Ops()) 5429 return SDValue(); 5430 5431 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5432 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5433 } 5434 5435 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 5436 /// for each 16-bit element from operand, repeated. The basic idea is to 5437 /// leverage vcnt to get the 8-bit counts, gather and add the results. 5438 /// 5439 /// Trace for v4i16: 5440 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5441 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 5442 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 5443 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 5444 /// [b0 b1 b2 b3 b4 b5 b6 b7] 5445 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 5446 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 5447 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 5448 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 5449 EVT VT = N->getValueType(0); 5450 SDLoc DL(N); 5451 5452 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5453 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5454 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5455 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5456 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5457 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5458 } 5459 5460 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5461 /// bit-count for each 16-bit element from the operand. We need slightly 5462 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5463 /// 64/128-bit registers. 5464 /// 5465 /// Trace for v4i16: 5466 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5467 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5468 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5469 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5470 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5471 EVT VT = N->getValueType(0); 5472 SDLoc DL(N); 5473 5474 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5475 if (VT.is64BitVector()) { 5476 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5477 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5478 DAG.getIntPtrConstant(0, DL)); 5479 } else { 5480 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5481 BitCounts, DAG.getIntPtrConstant(0, DL)); 5482 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5483 } 5484 } 5485 5486 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5487 /// bit-count for each 32-bit element from the operand. The idea here is 5488 /// to split the vector into 16-bit elements, leverage the 16-bit count 5489 /// routine, and then combine the results. 5490 /// 5491 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5492 /// input = [v0 v1 ] (vi: 32-bit elements) 5493 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5494 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5495 /// vrev: N0 = [k1 k0 k3 k2 ] 5496 /// [k0 k1 k2 k3 ] 5497 /// N1 =+[k1 k0 k3 k2 ] 5498 /// [k0 k2 k1 k3 ] 5499 /// N2 =+[k1 k3 k0 k2 ] 5500 /// [k0 k2 k1 k3 ] 5501 /// Extended =+[k1 k3 k0 k2 ] 5502 /// [k0 k2 ] 5503 /// Extracted=+[k1 k3 ] 5504 /// 5505 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5506 EVT VT = N->getValueType(0); 5507 SDLoc DL(N); 5508 5509 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5510 5511 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5512 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5513 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5514 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5515 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5516 5517 if (VT.is64BitVector()) { 5518 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5519 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5520 DAG.getIntPtrConstant(0, DL)); 5521 } else { 5522 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5523 DAG.getIntPtrConstant(0, DL)); 5524 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5525 } 5526 } 5527 5528 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5529 const ARMSubtarget *ST) { 5530 EVT VT = N->getValueType(0); 5531 5532 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5533 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5534 VT == MVT::v4i16 || VT == MVT::v8i16) && 5535 "Unexpected type for custom ctpop lowering"); 5536 5537 if (VT.getVectorElementType() == MVT::i32) 5538 return lowerCTPOP32BitElements(N, DAG); 5539 else 5540 return lowerCTPOP16BitElements(N, DAG); 5541 } 5542 5543 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5544 const ARMSubtarget *ST) { 5545 EVT VT = N->getValueType(0); 5546 SDLoc dl(N); 5547 5548 if (!VT.isVector()) 5549 return SDValue(); 5550 5551 // Lower vector shifts on NEON to use VSHL. 5552 assert(ST->hasNEON() && "unexpected vector shift"); 5553 5554 // Left shifts translate directly to the vshiftu intrinsic. 5555 if (N->getOpcode() == ISD::SHL) 5556 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5557 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5558 MVT::i32), 5559 N->getOperand(0), N->getOperand(1)); 5560 5561 assert((N->getOpcode() == ISD::SRA || 5562 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5563 5564 // NEON uses the same intrinsics for both left and right shifts. For 5565 // right shifts, the shift amounts are negative, so negate the vector of 5566 // shift amounts. 5567 EVT ShiftVT = N->getOperand(1).getValueType(); 5568 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5569 getZeroVector(ShiftVT, DAG, dl), 5570 N->getOperand(1)); 5571 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5572 Intrinsic::arm_neon_vshifts : 5573 Intrinsic::arm_neon_vshiftu); 5574 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5575 DAG.getConstant(vshiftInt, dl, MVT::i32), 5576 N->getOperand(0), NegatedCount); 5577 } 5578 5579 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5580 const ARMSubtarget *ST) { 5581 EVT VT = N->getValueType(0); 5582 SDLoc dl(N); 5583 5584 // We can get here for a node like i32 = ISD::SHL i32, i64 5585 if (VT != MVT::i64) 5586 return SDValue(); 5587 5588 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5589 "Unknown shift to lower!"); 5590 5591 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5592 if (!isOneConstant(N->getOperand(1))) 5593 return SDValue(); 5594 5595 // If we are in thumb mode, we don't have RRX. 5596 if (ST->isThumb1Only()) return SDValue(); 5597 5598 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5599 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5600 DAG.getConstant(0, dl, MVT::i32)); 5601 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5602 DAG.getConstant(1, dl, MVT::i32)); 5603 5604 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5605 // captures the result into a carry flag. 5606 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5607 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5608 5609 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5610 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5611 5612 // Merge the pieces into a single i64 value. 5613 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5614 } 5615 5616 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5617 SDValue TmpOp0, TmpOp1; 5618 bool Invert = false; 5619 bool Swap = false; 5620 unsigned Opc = 0; 5621 5622 SDValue Op0 = Op.getOperand(0); 5623 SDValue Op1 = Op.getOperand(1); 5624 SDValue CC = Op.getOperand(2); 5625 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5626 EVT VT = Op.getValueType(); 5627 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5628 SDLoc dl(Op); 5629 5630 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5631 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5632 // Special-case integer 64-bit equality comparisons. They aren't legal, 5633 // but they can be lowered with a few vector instructions. 5634 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5635 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5636 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5637 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5638 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5639 DAG.getCondCode(ISD::SETEQ)); 5640 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5641 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5642 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5643 if (SetCCOpcode == ISD::SETNE) 5644 Merged = DAG.getNOT(dl, Merged, CmpVT); 5645 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5646 return Merged; 5647 } 5648 5649 if (CmpVT.getVectorElementType() == MVT::i64) 5650 // 64-bit comparisons are not legal in general. 5651 return SDValue(); 5652 5653 if (Op1.getValueType().isFloatingPoint()) { 5654 switch (SetCCOpcode) { 5655 default: llvm_unreachable("Illegal FP comparison"); 5656 case ISD::SETUNE: 5657 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5658 case ISD::SETOEQ: 5659 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5660 case ISD::SETOLT: 5661 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5662 case ISD::SETOGT: 5663 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5664 case ISD::SETOLE: 5665 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5666 case ISD::SETOGE: 5667 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5668 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5669 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5670 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5671 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5672 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5673 case ISD::SETONE: 5674 // Expand this to (OLT | OGT). 5675 TmpOp0 = Op0; 5676 TmpOp1 = Op1; 5677 Opc = ISD::OR; 5678 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5679 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5680 break; 5681 case ISD::SETUO: 5682 Invert = true; 5683 LLVM_FALLTHROUGH; 5684 case ISD::SETO: 5685 // Expand this to (OLT | OGE). 5686 TmpOp0 = Op0; 5687 TmpOp1 = Op1; 5688 Opc = ISD::OR; 5689 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5690 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5691 break; 5692 } 5693 } else { 5694 // Integer comparisons. 5695 switch (SetCCOpcode) { 5696 default: llvm_unreachable("Illegal integer comparison"); 5697 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5698 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5699 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5700 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5701 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5702 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5703 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5704 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5705 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5706 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5707 } 5708 5709 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5710 if (Opc == ARMISD::VCEQ) { 5711 SDValue AndOp; 5712 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5713 AndOp = Op0; 5714 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5715 AndOp = Op1; 5716 5717 // Ignore bitconvert. 5718 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5719 AndOp = AndOp.getOperand(0); 5720 5721 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5722 Opc = ARMISD::VTST; 5723 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5724 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5725 Invert = !Invert; 5726 } 5727 } 5728 } 5729 5730 if (Swap) 5731 std::swap(Op0, Op1); 5732 5733 // If one of the operands is a constant vector zero, attempt to fold the 5734 // comparison to a specialized compare-against-zero form. 5735 SDValue SingleOp; 5736 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5737 SingleOp = Op0; 5738 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5739 if (Opc == ARMISD::VCGE) 5740 Opc = ARMISD::VCLEZ; 5741 else if (Opc == ARMISD::VCGT) 5742 Opc = ARMISD::VCLTZ; 5743 SingleOp = Op1; 5744 } 5745 5746 SDValue Result; 5747 if (SingleOp.getNode()) { 5748 switch (Opc) { 5749 case ARMISD::VCEQ: 5750 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5751 case ARMISD::VCGE: 5752 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5753 case ARMISD::VCLEZ: 5754 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5755 case ARMISD::VCGT: 5756 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5757 case ARMISD::VCLTZ: 5758 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5759 default: 5760 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5761 } 5762 } else { 5763 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5764 } 5765 5766 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5767 5768 if (Invert) 5769 Result = DAG.getNOT(dl, Result, VT); 5770 5771 return Result; 5772 } 5773 5774 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5775 SDValue LHS = Op.getOperand(0); 5776 SDValue RHS = Op.getOperand(1); 5777 SDValue Carry = Op.getOperand(2); 5778 SDValue Cond = Op.getOperand(3); 5779 SDLoc DL(Op); 5780 5781 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5782 5783 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5784 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5785 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5786 5787 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5788 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5789 SDValue ARMcc = DAG.getConstant( 5790 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5791 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5792 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5793 Cmp.getValue(1), SDValue()); 5794 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5795 CCR, Chain.getValue(1)); 5796 } 5797 5798 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5799 /// valid vector constant for a NEON instruction with a "modified immediate" 5800 /// operand (e.g., VMOV). If so, return the encoded value. 5801 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5802 unsigned SplatBitSize, SelectionDAG &DAG, 5803 const SDLoc &dl, EVT &VT, bool is128Bits, 5804 NEONModImmType type) { 5805 unsigned OpCmode, Imm; 5806 5807 // SplatBitSize is set to the smallest size that splats the vector, so a 5808 // zero vector will always have SplatBitSize == 8. However, NEON modified 5809 // immediate instructions others than VMOV do not support the 8-bit encoding 5810 // of a zero vector, and the default encoding of zero is supposed to be the 5811 // 32-bit version. 5812 if (SplatBits == 0) 5813 SplatBitSize = 32; 5814 5815 switch (SplatBitSize) { 5816 case 8: 5817 if (type != VMOVModImm) 5818 return SDValue(); 5819 // Any 1-byte value is OK. Op=0, Cmode=1110. 5820 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5821 OpCmode = 0xe; 5822 Imm = SplatBits; 5823 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5824 break; 5825 5826 case 16: 5827 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5828 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5829 if ((SplatBits & ~0xff) == 0) { 5830 // Value = 0x00nn: Op=x, Cmode=100x. 5831 OpCmode = 0x8; 5832 Imm = SplatBits; 5833 break; 5834 } 5835 if ((SplatBits & ~0xff00) == 0) { 5836 // Value = 0xnn00: Op=x, Cmode=101x. 5837 OpCmode = 0xa; 5838 Imm = SplatBits >> 8; 5839 break; 5840 } 5841 return SDValue(); 5842 5843 case 32: 5844 // NEON's 32-bit VMOV supports splat values where: 5845 // * only one byte is nonzero, or 5846 // * the least significant byte is 0xff and the second byte is nonzero, or 5847 // * the least significant 2 bytes are 0xff and the third is nonzero. 5848 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5849 if ((SplatBits & ~0xff) == 0) { 5850 // Value = 0x000000nn: Op=x, Cmode=000x. 5851 OpCmode = 0; 5852 Imm = SplatBits; 5853 break; 5854 } 5855 if ((SplatBits & ~0xff00) == 0) { 5856 // Value = 0x0000nn00: Op=x, Cmode=001x. 5857 OpCmode = 0x2; 5858 Imm = SplatBits >> 8; 5859 break; 5860 } 5861 if ((SplatBits & ~0xff0000) == 0) { 5862 // Value = 0x00nn0000: Op=x, Cmode=010x. 5863 OpCmode = 0x4; 5864 Imm = SplatBits >> 16; 5865 break; 5866 } 5867 if ((SplatBits & ~0xff000000) == 0) { 5868 // Value = 0xnn000000: Op=x, Cmode=011x. 5869 OpCmode = 0x6; 5870 Imm = SplatBits >> 24; 5871 break; 5872 } 5873 5874 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5875 if (type == OtherModImm) return SDValue(); 5876 5877 if ((SplatBits & ~0xffff) == 0 && 5878 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5879 // Value = 0x0000nnff: Op=x, Cmode=1100. 5880 OpCmode = 0xc; 5881 Imm = SplatBits >> 8; 5882 break; 5883 } 5884 5885 if ((SplatBits & ~0xffffff) == 0 && 5886 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5887 // Value = 0x00nnffff: Op=x, Cmode=1101. 5888 OpCmode = 0xd; 5889 Imm = SplatBits >> 16; 5890 break; 5891 } 5892 5893 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5894 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5895 // VMOV.I32. A (very) minor optimization would be to replicate the value 5896 // and fall through here to test for a valid 64-bit splat. But, then the 5897 // caller would also need to check and handle the change in size. 5898 return SDValue(); 5899 5900 case 64: { 5901 if (type != VMOVModImm) 5902 return SDValue(); 5903 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5904 uint64_t BitMask = 0xff; 5905 uint64_t Val = 0; 5906 unsigned ImmMask = 1; 5907 Imm = 0; 5908 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5909 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5910 Val |= BitMask; 5911 Imm |= ImmMask; 5912 } else if ((SplatBits & BitMask) != 0) { 5913 return SDValue(); 5914 } 5915 BitMask <<= 8; 5916 ImmMask <<= 1; 5917 } 5918 5919 if (DAG.getDataLayout().isBigEndian()) 5920 // swap higher and lower 32 bit word 5921 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5922 5923 // Op=1, Cmode=1110. 5924 OpCmode = 0x1e; 5925 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5926 break; 5927 } 5928 5929 default: 5930 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5931 } 5932 5933 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5934 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5935 } 5936 5937 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5938 const ARMSubtarget *ST) const { 5939 bool IsDouble = Op.getValueType() == MVT::f64; 5940 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5941 const APFloat &FPVal = CFP->getValueAPF(); 5942 5943 // Prevent floating-point constants from using literal loads 5944 // when execute-only is enabled. 5945 if (ST->genExecuteOnly()) { 5946 APInt INTVal = FPVal.bitcastToAPInt(); 5947 SDLoc DL(CFP); 5948 if (IsDouble) { 5949 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5950 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5951 if (!ST->isLittle()) 5952 std::swap(Lo, Hi); 5953 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5954 } else { 5955 return DAG.getConstant(INTVal, DL, MVT::i32); 5956 } 5957 } 5958 5959 if (!ST->hasVFP3()) 5960 return SDValue(); 5961 5962 // Use the default (constant pool) lowering for double constants when we have 5963 // an SP-only FPU 5964 if (IsDouble && Subtarget->isFPOnlySP()) 5965 return SDValue(); 5966 5967 // Try splatting with a VMOV.f32... 5968 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5969 5970 if (ImmVal != -1) { 5971 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5972 // We have code in place to select a valid ConstantFP already, no need to 5973 // do any mangling. 5974 return Op; 5975 } 5976 5977 // It's a float and we are trying to use NEON operations where 5978 // possible. Lower it to a splat followed by an extract. 5979 SDLoc DL(Op); 5980 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5981 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5982 NewVal); 5983 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5984 DAG.getConstant(0, DL, MVT::i32)); 5985 } 5986 5987 // The rest of our options are NEON only, make sure that's allowed before 5988 // proceeding.. 5989 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5990 return SDValue(); 5991 5992 EVT VMovVT; 5993 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5994 5995 // It wouldn't really be worth bothering for doubles except for one very 5996 // important value, which does happen to match: 0.0. So make sure we don't do 5997 // anything stupid. 5998 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5999 return SDValue(); 6000 6001 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6002 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6003 VMovVT, false, VMOVModImm); 6004 if (NewVal != SDValue()) { 6005 SDLoc DL(Op); 6006 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6007 NewVal); 6008 if (IsDouble) 6009 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6010 6011 // It's a float: cast and extract a vector element. 6012 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6013 VecConstant); 6014 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6015 DAG.getConstant(0, DL, MVT::i32)); 6016 } 6017 6018 // Finally, try a VMVN.i32 6019 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6020 false, VMVNModImm); 6021 if (NewVal != SDValue()) { 6022 SDLoc DL(Op); 6023 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6024 6025 if (IsDouble) 6026 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6027 6028 // It's a float: cast and extract a vector element. 6029 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6030 VecConstant); 6031 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6032 DAG.getConstant(0, DL, MVT::i32)); 6033 } 6034 6035 return SDValue(); 6036 } 6037 6038 // check if an VEXT instruction can handle the shuffle mask when the 6039 // vector sources of the shuffle are the same. 6040 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6041 unsigned NumElts = VT.getVectorNumElements(); 6042 6043 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6044 if (M[0] < 0) 6045 return false; 6046 6047 Imm = M[0]; 6048 6049 // If this is a VEXT shuffle, the immediate value is the index of the first 6050 // element. The other shuffle indices must be the successive elements after 6051 // the first one. 6052 unsigned ExpectedElt = Imm; 6053 for (unsigned i = 1; i < NumElts; ++i) { 6054 // Increment the expected index. If it wraps around, just follow it 6055 // back to index zero and keep going. 6056 ++ExpectedElt; 6057 if (ExpectedElt == NumElts) 6058 ExpectedElt = 0; 6059 6060 if (M[i] < 0) continue; // ignore UNDEF indices 6061 if (ExpectedElt != static_cast<unsigned>(M[i])) 6062 return false; 6063 } 6064 6065 return true; 6066 } 6067 6068 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6069 bool &ReverseVEXT, unsigned &Imm) { 6070 unsigned NumElts = VT.getVectorNumElements(); 6071 ReverseVEXT = false; 6072 6073 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6074 if (M[0] < 0) 6075 return false; 6076 6077 Imm = M[0]; 6078 6079 // If this is a VEXT shuffle, the immediate value is the index of the first 6080 // element. The other shuffle indices must be the successive elements after 6081 // the first one. 6082 unsigned ExpectedElt = Imm; 6083 for (unsigned i = 1; i < NumElts; ++i) { 6084 // Increment the expected index. If it wraps around, it may still be 6085 // a VEXT but the source vectors must be swapped. 6086 ExpectedElt += 1; 6087 if (ExpectedElt == NumElts * 2) { 6088 ExpectedElt = 0; 6089 ReverseVEXT = true; 6090 } 6091 6092 if (M[i] < 0) continue; // ignore UNDEF indices 6093 if (ExpectedElt != static_cast<unsigned>(M[i])) 6094 return false; 6095 } 6096 6097 // Adjust the index value if the source operands will be swapped. 6098 if (ReverseVEXT) 6099 Imm -= NumElts; 6100 6101 return true; 6102 } 6103 6104 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6105 /// instruction with the specified blocksize. (The order of the elements 6106 /// within each block of the vector is reversed.) 6107 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6108 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6109 "Only possible block sizes for VREV are: 16, 32, 64"); 6110 6111 unsigned EltSz = VT.getScalarSizeInBits(); 6112 if (EltSz == 64) 6113 return false; 6114 6115 unsigned NumElts = VT.getVectorNumElements(); 6116 unsigned BlockElts = M[0] + 1; 6117 // If the first shuffle index is UNDEF, be optimistic. 6118 if (M[0] < 0) 6119 BlockElts = BlockSize / EltSz; 6120 6121 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6122 return false; 6123 6124 for (unsigned i = 0; i < NumElts; ++i) { 6125 if (M[i] < 0) continue; // ignore UNDEF indices 6126 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6127 return false; 6128 } 6129 6130 return true; 6131 } 6132 6133 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6134 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6135 // range, then 0 is placed into the resulting vector. So pretty much any mask 6136 // of 8 elements can work here. 6137 return VT == MVT::v8i8 && M.size() == 8; 6138 } 6139 6140 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6141 unsigned Index) { 6142 if (Mask.size() == Elements * 2) 6143 return Index / Elements; 6144 return Mask[Index] == 0 ? 0 : 1; 6145 } 6146 6147 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6148 // checking that pairs of elements in the shuffle mask represent the same index 6149 // in each vector, incrementing the expected index by 2 at each step. 6150 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6151 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6152 // v2={e,f,g,h} 6153 // WhichResult gives the offset for each element in the mask based on which 6154 // of the two results it belongs to. 6155 // 6156 // The transpose can be represented either as: 6157 // result1 = shufflevector v1, v2, result1_shuffle_mask 6158 // result2 = shufflevector v1, v2, result2_shuffle_mask 6159 // where v1/v2 and the shuffle masks have the same number of elements 6160 // (here WhichResult (see below) indicates which result is being checked) 6161 // 6162 // or as: 6163 // results = shufflevector v1, v2, shuffle_mask 6164 // where both results are returned in one vector and the shuffle mask has twice 6165 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6166 // want to check the low half and high half of the shuffle mask as if it were 6167 // the other case 6168 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6169 unsigned EltSz = VT.getScalarSizeInBits(); 6170 if (EltSz == 64) 6171 return false; 6172 6173 unsigned NumElts = VT.getVectorNumElements(); 6174 if (M.size() != NumElts && M.size() != NumElts*2) 6175 return false; 6176 6177 // If the mask is twice as long as the input vector then we need to check the 6178 // upper and lower parts of the mask with a matching value for WhichResult 6179 // FIXME: A mask with only even values will be rejected in case the first 6180 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6181 // M[0] is used to determine WhichResult 6182 for (unsigned i = 0; i < M.size(); i += NumElts) { 6183 WhichResult = SelectPairHalf(NumElts, M, i); 6184 for (unsigned j = 0; j < NumElts; j += 2) { 6185 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6186 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6187 return false; 6188 } 6189 } 6190 6191 if (M.size() == NumElts*2) 6192 WhichResult = 0; 6193 6194 return true; 6195 } 6196 6197 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6198 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6199 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6200 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6201 unsigned EltSz = VT.getScalarSizeInBits(); 6202 if (EltSz == 64) 6203 return false; 6204 6205 unsigned NumElts = VT.getVectorNumElements(); 6206 if (M.size() != NumElts && M.size() != NumElts*2) 6207 return false; 6208 6209 for (unsigned i = 0; i < M.size(); i += NumElts) { 6210 WhichResult = SelectPairHalf(NumElts, M, i); 6211 for (unsigned j = 0; j < NumElts; j += 2) { 6212 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6213 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6214 return false; 6215 } 6216 } 6217 6218 if (M.size() == NumElts*2) 6219 WhichResult = 0; 6220 6221 return true; 6222 } 6223 6224 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6225 // that the mask elements are either all even and in steps of size 2 or all odd 6226 // and in steps of size 2. 6227 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6228 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6229 // v2={e,f,g,h} 6230 // Requires similar checks to that of isVTRNMask with 6231 // respect the how results are returned. 6232 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6233 unsigned EltSz = VT.getScalarSizeInBits(); 6234 if (EltSz == 64) 6235 return false; 6236 6237 unsigned NumElts = VT.getVectorNumElements(); 6238 if (M.size() != NumElts && M.size() != NumElts*2) 6239 return false; 6240 6241 for (unsigned i = 0; i < M.size(); i += NumElts) { 6242 WhichResult = SelectPairHalf(NumElts, M, i); 6243 for (unsigned j = 0; j < NumElts; ++j) { 6244 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6245 return false; 6246 } 6247 } 6248 6249 if (M.size() == NumElts*2) 6250 WhichResult = 0; 6251 6252 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6253 if (VT.is64BitVector() && EltSz == 32) 6254 return false; 6255 6256 return true; 6257 } 6258 6259 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6260 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6261 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6262 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6263 unsigned EltSz = VT.getScalarSizeInBits(); 6264 if (EltSz == 64) 6265 return false; 6266 6267 unsigned NumElts = VT.getVectorNumElements(); 6268 if (M.size() != NumElts && M.size() != NumElts*2) 6269 return false; 6270 6271 unsigned Half = NumElts / 2; 6272 for (unsigned i = 0; i < M.size(); i += NumElts) { 6273 WhichResult = SelectPairHalf(NumElts, M, i); 6274 for (unsigned j = 0; j < NumElts; j += Half) { 6275 unsigned Idx = WhichResult; 6276 for (unsigned k = 0; k < Half; ++k) { 6277 int MIdx = M[i + j + k]; 6278 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6279 return false; 6280 Idx += 2; 6281 } 6282 } 6283 } 6284 6285 if (M.size() == NumElts*2) 6286 WhichResult = 0; 6287 6288 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6289 if (VT.is64BitVector() && EltSz == 32) 6290 return false; 6291 6292 return true; 6293 } 6294 6295 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6296 // that pairs of elements of the shufflemask represent the same index in each 6297 // vector incrementing sequentially through the vectors. 6298 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6299 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6300 // v2={e,f,g,h} 6301 // Requires similar checks to that of isVTRNMask with respect the how results 6302 // are returned. 6303 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6304 unsigned EltSz = VT.getScalarSizeInBits(); 6305 if (EltSz == 64) 6306 return false; 6307 6308 unsigned NumElts = VT.getVectorNumElements(); 6309 if (M.size() != NumElts && M.size() != NumElts*2) 6310 return false; 6311 6312 for (unsigned i = 0; i < M.size(); i += NumElts) { 6313 WhichResult = SelectPairHalf(NumElts, M, i); 6314 unsigned Idx = WhichResult * NumElts / 2; 6315 for (unsigned j = 0; j < NumElts; j += 2) { 6316 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6317 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6318 return false; 6319 Idx += 1; 6320 } 6321 } 6322 6323 if (M.size() == NumElts*2) 6324 WhichResult = 0; 6325 6326 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6327 if (VT.is64BitVector() && EltSz == 32) 6328 return false; 6329 6330 return true; 6331 } 6332 6333 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6334 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6335 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6336 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6337 unsigned EltSz = VT.getScalarSizeInBits(); 6338 if (EltSz == 64) 6339 return false; 6340 6341 unsigned NumElts = VT.getVectorNumElements(); 6342 if (M.size() != NumElts && M.size() != NumElts*2) 6343 return false; 6344 6345 for (unsigned i = 0; i < M.size(); i += NumElts) { 6346 WhichResult = SelectPairHalf(NumElts, M, i); 6347 unsigned Idx = WhichResult * NumElts / 2; 6348 for (unsigned j = 0; j < NumElts; j += 2) { 6349 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6350 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6351 return false; 6352 Idx += 1; 6353 } 6354 } 6355 6356 if (M.size() == NumElts*2) 6357 WhichResult = 0; 6358 6359 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6360 if (VT.is64BitVector() && EltSz == 32) 6361 return false; 6362 6363 return true; 6364 } 6365 6366 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6367 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6368 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6369 unsigned &WhichResult, 6370 bool &isV_UNDEF) { 6371 isV_UNDEF = false; 6372 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6373 return ARMISD::VTRN; 6374 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6375 return ARMISD::VUZP; 6376 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6377 return ARMISD::VZIP; 6378 6379 isV_UNDEF = true; 6380 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6381 return ARMISD::VTRN; 6382 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6383 return ARMISD::VUZP; 6384 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6385 return ARMISD::VZIP; 6386 6387 return 0; 6388 } 6389 6390 /// \return true if this is a reverse operation on an vector. 6391 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6392 unsigned NumElts = VT.getVectorNumElements(); 6393 // Make sure the mask has the right size. 6394 if (NumElts != M.size()) 6395 return false; 6396 6397 // Look for <15, ..., 3, -1, 1, 0>. 6398 for (unsigned i = 0; i != NumElts; ++i) 6399 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6400 return false; 6401 6402 return true; 6403 } 6404 6405 // If N is an integer constant that can be moved into a register in one 6406 // instruction, return an SDValue of such a constant (will become a MOV 6407 // instruction). Otherwise return null. 6408 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6409 const ARMSubtarget *ST, const SDLoc &dl) { 6410 uint64_t Val; 6411 if (!isa<ConstantSDNode>(N)) 6412 return SDValue(); 6413 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6414 6415 if (ST->isThumb1Only()) { 6416 if (Val <= 255 || ~Val <= 255) 6417 return DAG.getConstant(Val, dl, MVT::i32); 6418 } else { 6419 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6420 return DAG.getConstant(Val, dl, MVT::i32); 6421 } 6422 return SDValue(); 6423 } 6424 6425 // If this is a case we can't handle, return null and let the default 6426 // expansion code take care of it. 6427 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6428 const ARMSubtarget *ST) const { 6429 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6430 SDLoc dl(Op); 6431 EVT VT = Op.getValueType(); 6432 6433 APInt SplatBits, SplatUndef; 6434 unsigned SplatBitSize; 6435 bool HasAnyUndefs; 6436 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6437 if (SplatUndef.isAllOnesValue()) 6438 return DAG.getUNDEF(VT); 6439 6440 if (SplatBitSize <= 64) { 6441 // Check if an immediate VMOV works. 6442 EVT VmovVT; 6443 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6444 SplatUndef.getZExtValue(), SplatBitSize, 6445 DAG, dl, VmovVT, VT.is128BitVector(), 6446 VMOVModImm); 6447 if (Val.getNode()) { 6448 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6449 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6450 } 6451 6452 // Try an immediate VMVN. 6453 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6454 Val = isNEONModifiedImm(NegatedImm, 6455 SplatUndef.getZExtValue(), SplatBitSize, 6456 DAG, dl, VmovVT, VT.is128BitVector(), 6457 VMVNModImm); 6458 if (Val.getNode()) { 6459 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6460 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6461 } 6462 6463 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6464 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6465 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6466 if (ImmVal != -1) { 6467 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6468 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6469 } 6470 } 6471 } 6472 } 6473 6474 // Scan through the operands to see if only one value is used. 6475 // 6476 // As an optimisation, even if more than one value is used it may be more 6477 // profitable to splat with one value then change some lanes. 6478 // 6479 // Heuristically we decide to do this if the vector has a "dominant" value, 6480 // defined as splatted to more than half of the lanes. 6481 unsigned NumElts = VT.getVectorNumElements(); 6482 bool isOnlyLowElement = true; 6483 bool usesOnlyOneValue = true; 6484 bool hasDominantValue = false; 6485 bool isConstant = true; 6486 6487 // Map of the number of times a particular SDValue appears in the 6488 // element list. 6489 DenseMap<SDValue, unsigned> ValueCounts; 6490 SDValue Value; 6491 for (unsigned i = 0; i < NumElts; ++i) { 6492 SDValue V = Op.getOperand(i); 6493 if (V.isUndef()) 6494 continue; 6495 if (i > 0) 6496 isOnlyLowElement = false; 6497 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6498 isConstant = false; 6499 6500 ValueCounts.insert(std::make_pair(V, 0)); 6501 unsigned &Count = ValueCounts[V]; 6502 6503 // Is this value dominant? (takes up more than half of the lanes) 6504 if (++Count > (NumElts / 2)) { 6505 hasDominantValue = true; 6506 Value = V; 6507 } 6508 } 6509 if (ValueCounts.size() != 1) 6510 usesOnlyOneValue = false; 6511 if (!Value.getNode() && !ValueCounts.empty()) 6512 Value = ValueCounts.begin()->first; 6513 6514 if (ValueCounts.empty()) 6515 return DAG.getUNDEF(VT); 6516 6517 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6518 // Keep going if we are hitting this case. 6519 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6520 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6521 6522 unsigned EltSize = VT.getScalarSizeInBits(); 6523 6524 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6525 // i32 and try again. 6526 if (hasDominantValue && EltSize <= 32) { 6527 if (!isConstant) { 6528 SDValue N; 6529 6530 // If we are VDUPing a value that comes directly from a vector, that will 6531 // cause an unnecessary move to and from a GPR, where instead we could 6532 // just use VDUPLANE. We can only do this if the lane being extracted 6533 // is at a constant index, as the VDUP from lane instructions only have 6534 // constant-index forms. 6535 ConstantSDNode *constIndex; 6536 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6537 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6538 // We need to create a new undef vector to use for the VDUPLANE if the 6539 // size of the vector from which we get the value is different than the 6540 // size of the vector that we need to create. We will insert the element 6541 // such that the register coalescer will remove unnecessary copies. 6542 if (VT != Value->getOperand(0).getValueType()) { 6543 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6544 VT.getVectorNumElements(); 6545 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6546 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6547 Value, DAG.getConstant(index, dl, MVT::i32)), 6548 DAG.getConstant(index, dl, MVT::i32)); 6549 } else 6550 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6551 Value->getOperand(0), Value->getOperand(1)); 6552 } else 6553 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6554 6555 if (!usesOnlyOneValue) { 6556 // The dominant value was splatted as 'N', but we now have to insert 6557 // all differing elements. 6558 for (unsigned I = 0; I < NumElts; ++I) { 6559 if (Op.getOperand(I) == Value) 6560 continue; 6561 SmallVector<SDValue, 3> Ops; 6562 Ops.push_back(N); 6563 Ops.push_back(Op.getOperand(I)); 6564 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6565 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6566 } 6567 } 6568 return N; 6569 } 6570 if (VT.getVectorElementType().isFloatingPoint()) { 6571 SmallVector<SDValue, 8> Ops; 6572 for (unsigned i = 0; i < NumElts; ++i) 6573 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6574 Op.getOperand(i))); 6575 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6576 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6577 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6578 if (Val.getNode()) 6579 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6580 } 6581 if (usesOnlyOneValue) { 6582 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6583 if (isConstant && Val.getNode()) 6584 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6585 } 6586 } 6587 6588 // If all elements are constants and the case above didn't get hit, fall back 6589 // to the default expansion, which will generate a load from the constant 6590 // pool. 6591 if (isConstant) 6592 return SDValue(); 6593 6594 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6595 if (NumElts >= 4) { 6596 SDValue shuffle = ReconstructShuffle(Op, DAG); 6597 if (shuffle != SDValue()) 6598 return shuffle; 6599 } 6600 6601 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6602 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6603 // into two 64-bit vectors; we might discover a better way to lower it. 6604 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6605 EVT ExtVT = VT.getVectorElementType(); 6606 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6607 SDValue Lower = 6608 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6609 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6610 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6611 SDValue Upper = DAG.getBuildVector( 6612 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6613 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6614 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6615 if (Lower && Upper) 6616 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6617 } 6618 6619 // Vectors with 32- or 64-bit elements can be built by directly assigning 6620 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6621 // will be legalized. 6622 if (EltSize >= 32) { 6623 // Do the expansion with floating-point types, since that is what the VFP 6624 // registers are defined to use, and since i64 is not legal. 6625 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6626 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6627 SmallVector<SDValue, 8> Ops; 6628 for (unsigned i = 0; i < NumElts; ++i) 6629 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6630 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6631 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6632 } 6633 6634 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6635 // know the default expansion would otherwise fall back on something even 6636 // worse. For a vector with one or two non-undef values, that's 6637 // scalar_to_vector for the elements followed by a shuffle (provided the 6638 // shuffle is valid for the target) and materialization element by element 6639 // on the stack followed by a load for everything else. 6640 if (!isConstant && !usesOnlyOneValue) { 6641 SDValue Vec = DAG.getUNDEF(VT); 6642 for (unsigned i = 0 ; i < NumElts; ++i) { 6643 SDValue V = Op.getOperand(i); 6644 if (V.isUndef()) 6645 continue; 6646 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6647 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6648 } 6649 return Vec; 6650 } 6651 6652 return SDValue(); 6653 } 6654 6655 // Gather data to see if the operation can be modelled as a 6656 // shuffle in combination with VEXTs. 6657 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6658 SelectionDAG &DAG) const { 6659 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6660 SDLoc dl(Op); 6661 EVT VT = Op.getValueType(); 6662 unsigned NumElts = VT.getVectorNumElements(); 6663 6664 struct ShuffleSourceInfo { 6665 SDValue Vec; 6666 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6667 unsigned MaxElt = 0; 6668 6669 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6670 // be compatible with the shuffle we intend to construct. As a result 6671 // ShuffleVec will be some sliding window into the original Vec. 6672 SDValue ShuffleVec; 6673 6674 // Code should guarantee that element i in Vec starts at element "WindowBase 6675 // + i * WindowScale in ShuffleVec". 6676 int WindowBase = 0; 6677 int WindowScale = 1; 6678 6679 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6680 6681 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6682 }; 6683 6684 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6685 // node. 6686 SmallVector<ShuffleSourceInfo, 2> Sources; 6687 for (unsigned i = 0; i < NumElts; ++i) { 6688 SDValue V = Op.getOperand(i); 6689 if (V.isUndef()) 6690 continue; 6691 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6692 // A shuffle can only come from building a vector from various 6693 // elements of other vectors. 6694 return SDValue(); 6695 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6696 // Furthermore, shuffles require a constant mask, whereas extractelts 6697 // accept variable indices. 6698 return SDValue(); 6699 } 6700 6701 // Add this element source to the list if it's not already there. 6702 SDValue SourceVec = V.getOperand(0); 6703 auto Source = llvm::find(Sources, SourceVec); 6704 if (Source == Sources.end()) 6705 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6706 6707 // Update the minimum and maximum lane number seen. 6708 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6709 Source->MinElt = std::min(Source->MinElt, EltNo); 6710 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6711 } 6712 6713 // Currently only do something sane when at most two source vectors 6714 // are involved. 6715 if (Sources.size() > 2) 6716 return SDValue(); 6717 6718 // Find out the smallest element size among result and two sources, and use 6719 // it as element size to build the shuffle_vector. 6720 EVT SmallestEltTy = VT.getVectorElementType(); 6721 for (auto &Source : Sources) { 6722 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6723 if (SrcEltTy.bitsLT(SmallestEltTy)) 6724 SmallestEltTy = SrcEltTy; 6725 } 6726 unsigned ResMultiplier = 6727 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6728 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6729 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6730 6731 // If the source vector is too wide or too narrow, we may nevertheless be able 6732 // to construct a compatible shuffle either by concatenating it with UNDEF or 6733 // extracting a suitable range of elements. 6734 for (auto &Src : Sources) { 6735 EVT SrcVT = Src.ShuffleVec.getValueType(); 6736 6737 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6738 continue; 6739 6740 // This stage of the search produces a source with the same element type as 6741 // the original, but with a total width matching the BUILD_VECTOR output. 6742 EVT EltVT = SrcVT.getVectorElementType(); 6743 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6744 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6745 6746 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6747 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6748 return SDValue(); 6749 // We can pad out the smaller vector for free, so if it's part of a 6750 // shuffle... 6751 Src.ShuffleVec = 6752 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6753 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6754 continue; 6755 } 6756 6757 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6758 return SDValue(); 6759 6760 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6761 // Span too large for a VEXT to cope 6762 return SDValue(); 6763 } 6764 6765 if (Src.MinElt >= NumSrcElts) { 6766 // The extraction can just take the second half 6767 Src.ShuffleVec = 6768 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6769 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6770 Src.WindowBase = -NumSrcElts; 6771 } else if (Src.MaxElt < NumSrcElts) { 6772 // The extraction can just take the first half 6773 Src.ShuffleVec = 6774 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6775 DAG.getConstant(0, dl, MVT::i32)); 6776 } else { 6777 // An actual VEXT is needed 6778 SDValue VEXTSrc1 = 6779 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6780 DAG.getConstant(0, dl, MVT::i32)); 6781 SDValue VEXTSrc2 = 6782 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6783 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6784 6785 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6786 VEXTSrc2, 6787 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6788 Src.WindowBase = -Src.MinElt; 6789 } 6790 } 6791 6792 // Another possible incompatibility occurs from the vector element types. We 6793 // can fix this by bitcasting the source vectors to the same type we intend 6794 // for the shuffle. 6795 for (auto &Src : Sources) { 6796 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6797 if (SrcEltTy == SmallestEltTy) 6798 continue; 6799 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6800 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6801 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6802 Src.WindowBase *= Src.WindowScale; 6803 } 6804 6805 // Final sanity check before we try to actually produce a shuffle. 6806 DEBUG( 6807 for (auto Src : Sources) 6808 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6809 ); 6810 6811 // The stars all align, our next step is to produce the mask for the shuffle. 6812 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6813 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6814 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6815 SDValue Entry = Op.getOperand(i); 6816 if (Entry.isUndef()) 6817 continue; 6818 6819 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6820 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6821 6822 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6823 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6824 // segment. 6825 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6826 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6827 VT.getScalarSizeInBits()); 6828 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6829 6830 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6831 // starting at the appropriate offset. 6832 int *LaneMask = &Mask[i * ResMultiplier]; 6833 6834 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6835 ExtractBase += NumElts * (Src - Sources.begin()); 6836 for (int j = 0; j < LanesDefined; ++j) 6837 LaneMask[j] = ExtractBase + j; 6838 } 6839 6840 // Final check before we try to produce nonsense... 6841 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6842 return SDValue(); 6843 6844 // We can't handle more than two sources. This should have already 6845 // been checked before this point. 6846 assert(Sources.size() <= 2 && "Too many sources!"); 6847 6848 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6849 for (unsigned i = 0; i < Sources.size(); ++i) 6850 ShuffleOps[i] = Sources[i].ShuffleVec; 6851 6852 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6853 ShuffleOps[1], Mask); 6854 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6855 } 6856 6857 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6858 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6859 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6860 /// are assumed to be legal. 6861 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 6862 if (VT.getVectorNumElements() == 4 && 6863 (VT.is128BitVector() || VT.is64BitVector())) { 6864 unsigned PFIndexes[4]; 6865 for (unsigned i = 0; i != 4; ++i) { 6866 if (M[i] < 0) 6867 PFIndexes[i] = 8; 6868 else 6869 PFIndexes[i] = M[i]; 6870 } 6871 6872 // Compute the index in the perfect shuffle table. 6873 unsigned PFTableIndex = 6874 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6875 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6876 unsigned Cost = (PFEntry >> 30); 6877 6878 if (Cost <= 4) 6879 return true; 6880 } 6881 6882 bool ReverseVEXT, isV_UNDEF; 6883 unsigned Imm, WhichResult; 6884 6885 unsigned EltSize = VT.getScalarSizeInBits(); 6886 return (EltSize >= 32 || 6887 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6888 isVREVMask(M, VT, 64) || 6889 isVREVMask(M, VT, 32) || 6890 isVREVMask(M, VT, 16) || 6891 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6892 isVTBLMask(M, VT) || 6893 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6894 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6895 } 6896 6897 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6898 /// the specified operations to build the shuffle. 6899 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6900 SDValue RHS, SelectionDAG &DAG, 6901 const SDLoc &dl) { 6902 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6903 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6904 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6905 6906 enum { 6907 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6908 OP_VREV, 6909 OP_VDUP0, 6910 OP_VDUP1, 6911 OP_VDUP2, 6912 OP_VDUP3, 6913 OP_VEXT1, 6914 OP_VEXT2, 6915 OP_VEXT3, 6916 OP_VUZPL, // VUZP, left result 6917 OP_VUZPR, // VUZP, right result 6918 OP_VZIPL, // VZIP, left result 6919 OP_VZIPR, // VZIP, right result 6920 OP_VTRNL, // VTRN, left result 6921 OP_VTRNR // VTRN, right result 6922 }; 6923 6924 if (OpNum == OP_COPY) { 6925 if (LHSID == (1*9+2)*9+3) return LHS; 6926 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6927 return RHS; 6928 } 6929 6930 SDValue OpLHS, OpRHS; 6931 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6932 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6933 EVT VT = OpLHS.getValueType(); 6934 6935 switch (OpNum) { 6936 default: llvm_unreachable("Unknown shuffle opcode!"); 6937 case OP_VREV: 6938 // VREV divides the vector in half and swaps within the half. 6939 if (VT.getVectorElementType() == MVT::i32 || 6940 VT.getVectorElementType() == MVT::f32) 6941 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6942 // vrev <4 x i16> -> VREV32 6943 if (VT.getVectorElementType() == MVT::i16) 6944 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6945 // vrev <4 x i8> -> VREV16 6946 assert(VT.getVectorElementType() == MVT::i8); 6947 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6948 case OP_VDUP0: 6949 case OP_VDUP1: 6950 case OP_VDUP2: 6951 case OP_VDUP3: 6952 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6953 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6954 case OP_VEXT1: 6955 case OP_VEXT2: 6956 case OP_VEXT3: 6957 return DAG.getNode(ARMISD::VEXT, dl, VT, 6958 OpLHS, OpRHS, 6959 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6960 case OP_VUZPL: 6961 case OP_VUZPR: 6962 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6963 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6964 case OP_VZIPL: 6965 case OP_VZIPR: 6966 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6967 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6968 case OP_VTRNL: 6969 case OP_VTRNR: 6970 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6971 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6972 } 6973 } 6974 6975 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6976 ArrayRef<int> ShuffleMask, 6977 SelectionDAG &DAG) { 6978 // Check to see if we can use the VTBL instruction. 6979 SDValue V1 = Op.getOperand(0); 6980 SDValue V2 = Op.getOperand(1); 6981 SDLoc DL(Op); 6982 6983 SmallVector<SDValue, 8> VTBLMask; 6984 for (ArrayRef<int>::iterator 6985 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6986 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6987 6988 if (V2.getNode()->isUndef()) 6989 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6990 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6991 6992 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6993 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6994 } 6995 6996 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6997 SelectionDAG &DAG) { 6998 SDLoc DL(Op); 6999 SDValue OpLHS = Op.getOperand(0); 7000 EVT VT = OpLHS.getValueType(); 7001 7002 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 7003 "Expect an v8i16/v16i8 type"); 7004 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 7005 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 7006 // extract the first 8 bytes into the top double word and the last 8 bytes 7007 // into the bottom double word. The v8i16 case is similar. 7008 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 7009 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 7010 DAG.getConstant(ExtractNum, DL, MVT::i32)); 7011 } 7012 7013 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 7014 SDValue V1 = Op.getOperand(0); 7015 SDValue V2 = Op.getOperand(1); 7016 SDLoc dl(Op); 7017 EVT VT = Op.getValueType(); 7018 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7019 7020 // Convert shuffles that are directly supported on NEON to target-specific 7021 // DAG nodes, instead of keeping them as shuffles and matching them again 7022 // during code selection. This is more efficient and avoids the possibility 7023 // of inconsistencies between legalization and selection. 7024 // FIXME: floating-point vectors should be canonicalized to integer vectors 7025 // of the same time so that they get CSEd properly. 7026 ArrayRef<int> ShuffleMask = SVN->getMask(); 7027 7028 unsigned EltSize = VT.getScalarSizeInBits(); 7029 if (EltSize <= 32) { 7030 if (SVN->isSplat()) { 7031 int Lane = SVN->getSplatIndex(); 7032 // If this is undef splat, generate it via "just" vdup, if possible. 7033 if (Lane == -1) Lane = 0; 7034 7035 // Test if V1 is a SCALAR_TO_VECTOR. 7036 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7037 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7038 } 7039 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7040 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 7041 // reaches it). 7042 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 7043 !isa<ConstantSDNode>(V1.getOperand(0))) { 7044 bool IsScalarToVector = true; 7045 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 7046 if (!V1.getOperand(i).isUndef()) { 7047 IsScalarToVector = false; 7048 break; 7049 } 7050 if (IsScalarToVector) 7051 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7052 } 7053 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7054 DAG.getConstant(Lane, dl, MVT::i32)); 7055 } 7056 7057 bool ReverseVEXT; 7058 unsigned Imm; 7059 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7060 if (ReverseVEXT) 7061 std::swap(V1, V2); 7062 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7063 DAG.getConstant(Imm, dl, MVT::i32)); 7064 } 7065 7066 if (isVREVMask(ShuffleMask, VT, 64)) 7067 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7068 if (isVREVMask(ShuffleMask, VT, 32)) 7069 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7070 if (isVREVMask(ShuffleMask, VT, 16)) 7071 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7072 7073 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7074 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7075 DAG.getConstant(Imm, dl, MVT::i32)); 7076 } 7077 7078 // Check for Neon shuffles that modify both input vectors in place. 7079 // If both results are used, i.e., if there are two shuffles with the same 7080 // source operands and with masks corresponding to both results of one of 7081 // these operations, DAG memoization will ensure that a single node is 7082 // used for both shuffles. 7083 unsigned WhichResult; 7084 bool isV_UNDEF; 7085 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7086 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7087 if (isV_UNDEF) 7088 V2 = V1; 7089 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7090 .getValue(WhichResult); 7091 } 7092 7093 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7094 // shuffles that produce a result larger than their operands with: 7095 // shuffle(concat(v1, undef), concat(v2, undef)) 7096 // -> 7097 // shuffle(concat(v1, v2), undef) 7098 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7099 // 7100 // This is useful in the general case, but there are special cases where 7101 // native shuffles produce larger results: the two-result ops. 7102 // 7103 // Look through the concat when lowering them: 7104 // shuffle(concat(v1, v2), undef) 7105 // -> 7106 // concat(VZIP(v1, v2):0, :1) 7107 // 7108 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7109 SDValue SubV1 = V1->getOperand(0); 7110 SDValue SubV2 = V1->getOperand(1); 7111 EVT SubVT = SubV1.getValueType(); 7112 7113 // We expect these to have been canonicalized to -1. 7114 assert(llvm::all_of(ShuffleMask, [&](int i) { 7115 return i < (int)VT.getVectorNumElements(); 7116 }) && "Unexpected shuffle index into UNDEF operand!"); 7117 7118 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7119 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7120 if (isV_UNDEF) 7121 SubV2 = SubV1; 7122 assert((WhichResult == 0) && 7123 "In-place shuffle of concat can only have one result!"); 7124 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7125 SubV1, SubV2); 7126 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7127 Res.getValue(1)); 7128 } 7129 } 7130 } 7131 7132 // If the shuffle is not directly supported and it has 4 elements, use 7133 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7134 unsigned NumElts = VT.getVectorNumElements(); 7135 if (NumElts == 4) { 7136 unsigned PFIndexes[4]; 7137 for (unsigned i = 0; i != 4; ++i) { 7138 if (ShuffleMask[i] < 0) 7139 PFIndexes[i] = 8; 7140 else 7141 PFIndexes[i] = ShuffleMask[i]; 7142 } 7143 7144 // Compute the index in the perfect shuffle table. 7145 unsigned PFTableIndex = 7146 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7147 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7148 unsigned Cost = (PFEntry >> 30); 7149 7150 if (Cost <= 4) 7151 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7152 } 7153 7154 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7155 if (EltSize >= 32) { 7156 // Do the expansion with floating-point types, since that is what the VFP 7157 // registers are defined to use, and since i64 is not legal. 7158 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7159 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7160 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7161 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7162 SmallVector<SDValue, 8> Ops; 7163 for (unsigned i = 0; i < NumElts; ++i) { 7164 if (ShuffleMask[i] < 0) 7165 Ops.push_back(DAG.getUNDEF(EltVT)); 7166 else 7167 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7168 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7169 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7170 dl, MVT::i32))); 7171 } 7172 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7173 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7174 } 7175 7176 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7177 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7178 7179 if (VT == MVT::v8i8) 7180 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7181 return NewOp; 7182 7183 return SDValue(); 7184 } 7185 7186 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7187 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7188 SDValue Lane = Op.getOperand(2); 7189 if (!isa<ConstantSDNode>(Lane)) 7190 return SDValue(); 7191 7192 return Op; 7193 } 7194 7195 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7196 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7197 SDValue Lane = Op.getOperand(1); 7198 if (!isa<ConstantSDNode>(Lane)) 7199 return SDValue(); 7200 7201 SDValue Vec = Op.getOperand(0); 7202 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7203 SDLoc dl(Op); 7204 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7205 } 7206 7207 return Op; 7208 } 7209 7210 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 7211 // The only time a CONCAT_VECTORS operation can have legal types is when 7212 // two 64-bit vectors are concatenated to a 128-bit vector. 7213 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7214 "unexpected CONCAT_VECTORS"); 7215 SDLoc dl(Op); 7216 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7217 SDValue Op0 = Op.getOperand(0); 7218 SDValue Op1 = Op.getOperand(1); 7219 if (!Op0.isUndef()) 7220 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7221 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7222 DAG.getIntPtrConstant(0, dl)); 7223 if (!Op1.isUndef()) 7224 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7225 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7226 DAG.getIntPtrConstant(1, dl)); 7227 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7228 } 7229 7230 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7231 /// element has been zero/sign-extended, depending on the isSigned parameter, 7232 /// from an integer type half its size. 7233 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7234 bool isSigned) { 7235 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7236 EVT VT = N->getValueType(0); 7237 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7238 SDNode *BVN = N->getOperand(0).getNode(); 7239 if (BVN->getValueType(0) != MVT::v4i32 || 7240 BVN->getOpcode() != ISD::BUILD_VECTOR) 7241 return false; 7242 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7243 unsigned HiElt = 1 - LoElt; 7244 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7245 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7246 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7247 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7248 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7249 return false; 7250 if (isSigned) { 7251 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7252 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7253 return true; 7254 } else { 7255 if (Hi0->isNullValue() && Hi1->isNullValue()) 7256 return true; 7257 } 7258 return false; 7259 } 7260 7261 if (N->getOpcode() != ISD::BUILD_VECTOR) 7262 return false; 7263 7264 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7265 SDNode *Elt = N->getOperand(i).getNode(); 7266 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 7267 unsigned EltSize = VT.getScalarSizeInBits(); 7268 unsigned HalfSize = EltSize / 2; 7269 if (isSigned) { 7270 if (!isIntN(HalfSize, C->getSExtValue())) 7271 return false; 7272 } else { 7273 if (!isUIntN(HalfSize, C->getZExtValue())) 7274 return false; 7275 } 7276 continue; 7277 } 7278 return false; 7279 } 7280 7281 return true; 7282 } 7283 7284 /// isSignExtended - Check if a node is a vector value that is sign-extended 7285 /// or a constant BUILD_VECTOR with sign-extended elements. 7286 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7287 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7288 return true; 7289 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7290 return true; 7291 return false; 7292 } 7293 7294 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7295 /// or a constant BUILD_VECTOR with zero-extended elements. 7296 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7297 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7298 return true; 7299 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7300 return true; 7301 return false; 7302 } 7303 7304 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7305 if (OrigVT.getSizeInBits() >= 64) 7306 return OrigVT; 7307 7308 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7309 7310 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7311 switch (OrigSimpleTy) { 7312 default: llvm_unreachable("Unexpected Vector Type"); 7313 case MVT::v2i8: 7314 case MVT::v2i16: 7315 return MVT::v2i32; 7316 case MVT::v4i8: 7317 return MVT::v4i16; 7318 } 7319 } 7320 7321 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7322 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7323 /// We insert the required extension here to get the vector to fill a D register. 7324 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7325 const EVT &OrigTy, 7326 const EVT &ExtTy, 7327 unsigned ExtOpcode) { 7328 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7329 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7330 // 64-bits we need to insert a new extension so that it will be 64-bits. 7331 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7332 if (OrigTy.getSizeInBits() >= 64) 7333 return N; 7334 7335 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7336 EVT NewVT = getExtensionTo64Bits(OrigTy); 7337 7338 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7339 } 7340 7341 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7342 /// does not do any sign/zero extension. If the original vector is less 7343 /// than 64 bits, an appropriate extension will be added after the load to 7344 /// reach a total size of 64 bits. We have to add the extension separately 7345 /// because ARM does not have a sign/zero extending load for vectors. 7346 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7347 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7348 7349 // The load already has the right type. 7350 if (ExtendedTy == LD->getMemoryVT()) 7351 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7352 LD->getBasePtr(), LD->getPointerInfo(), 7353 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7354 7355 // We need to create a zextload/sextload. We cannot just create a load 7356 // followed by a zext/zext node because LowerMUL is also run during normal 7357 // operation legalization where we can't create illegal types. 7358 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7359 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7360 LD->getMemoryVT(), LD->getAlignment(), 7361 LD->getMemOperand()->getFlags()); 7362 } 7363 7364 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7365 /// extending load, or BUILD_VECTOR with extended elements, return the 7366 /// unextended value. The unextended vector should be 64 bits so that it can 7367 /// be used as an operand to a VMULL instruction. If the original vector size 7368 /// before extension is less than 64 bits we add a an extension to resize 7369 /// the vector to 64 bits. 7370 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7371 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7372 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7373 N->getOperand(0)->getValueType(0), 7374 N->getValueType(0), 7375 N->getOpcode()); 7376 7377 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7378 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7379 "Expected extending load"); 7380 7381 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7382 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7383 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7384 SDValue extLoad = 7385 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7386 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7387 7388 return newLoad; 7389 } 7390 7391 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7392 // have been legalized as a BITCAST from v4i32. 7393 if (N->getOpcode() == ISD::BITCAST) { 7394 SDNode *BVN = N->getOperand(0).getNode(); 7395 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7396 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7397 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7398 return DAG.getBuildVector( 7399 MVT::v2i32, SDLoc(N), 7400 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7401 } 7402 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7403 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7404 EVT VT = N->getValueType(0); 7405 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7406 unsigned NumElts = VT.getVectorNumElements(); 7407 MVT TruncVT = MVT::getIntegerVT(EltSize); 7408 SmallVector<SDValue, 8> Ops; 7409 SDLoc dl(N); 7410 for (unsigned i = 0; i != NumElts; ++i) { 7411 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7412 const APInt &CInt = C->getAPIntValue(); 7413 // Element types smaller than 32 bits are not legal, so use i32 elements. 7414 // The values are implicitly truncated so sext vs. zext doesn't matter. 7415 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7416 } 7417 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7418 } 7419 7420 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7421 unsigned Opcode = N->getOpcode(); 7422 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7423 SDNode *N0 = N->getOperand(0).getNode(); 7424 SDNode *N1 = N->getOperand(1).getNode(); 7425 return N0->hasOneUse() && N1->hasOneUse() && 7426 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7427 } 7428 return false; 7429 } 7430 7431 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7432 unsigned Opcode = N->getOpcode(); 7433 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7434 SDNode *N0 = N->getOperand(0).getNode(); 7435 SDNode *N1 = N->getOperand(1).getNode(); 7436 return N0->hasOneUse() && N1->hasOneUse() && 7437 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7438 } 7439 return false; 7440 } 7441 7442 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7443 // Multiplications are only custom-lowered for 128-bit vectors so that 7444 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7445 EVT VT = Op.getValueType(); 7446 assert(VT.is128BitVector() && VT.isInteger() && 7447 "unexpected type for custom-lowering ISD::MUL"); 7448 SDNode *N0 = Op.getOperand(0).getNode(); 7449 SDNode *N1 = Op.getOperand(1).getNode(); 7450 unsigned NewOpc = 0; 7451 bool isMLA = false; 7452 bool isN0SExt = isSignExtended(N0, DAG); 7453 bool isN1SExt = isSignExtended(N1, DAG); 7454 if (isN0SExt && isN1SExt) 7455 NewOpc = ARMISD::VMULLs; 7456 else { 7457 bool isN0ZExt = isZeroExtended(N0, DAG); 7458 bool isN1ZExt = isZeroExtended(N1, DAG); 7459 if (isN0ZExt && isN1ZExt) 7460 NewOpc = ARMISD::VMULLu; 7461 else if (isN1SExt || isN1ZExt) { 7462 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7463 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7464 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7465 NewOpc = ARMISD::VMULLs; 7466 isMLA = true; 7467 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7468 NewOpc = ARMISD::VMULLu; 7469 isMLA = true; 7470 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7471 std::swap(N0, N1); 7472 NewOpc = ARMISD::VMULLu; 7473 isMLA = true; 7474 } 7475 } 7476 7477 if (!NewOpc) { 7478 if (VT == MVT::v2i64) 7479 // Fall through to expand this. It is not legal. 7480 return SDValue(); 7481 else 7482 // Other vector multiplications are legal. 7483 return Op; 7484 } 7485 } 7486 7487 // Legalize to a VMULL instruction. 7488 SDLoc DL(Op); 7489 SDValue Op0; 7490 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7491 if (!isMLA) { 7492 Op0 = SkipExtensionForVMULL(N0, DAG); 7493 assert(Op0.getValueType().is64BitVector() && 7494 Op1.getValueType().is64BitVector() && 7495 "unexpected types for extended operands to VMULL"); 7496 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7497 } 7498 7499 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7500 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7501 // vmull q0, d4, d6 7502 // vmlal q0, d5, d6 7503 // is faster than 7504 // vaddl q0, d4, d5 7505 // vmovl q1, d6 7506 // vmul q0, q0, q1 7507 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7508 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7509 EVT Op1VT = Op1.getValueType(); 7510 return DAG.getNode(N0->getOpcode(), DL, VT, 7511 DAG.getNode(NewOpc, DL, VT, 7512 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7513 DAG.getNode(NewOpc, DL, VT, 7514 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7515 } 7516 7517 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7518 SelectionDAG &DAG) { 7519 // TODO: Should this propagate fast-math-flags? 7520 7521 // Convert to float 7522 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7523 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7524 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7525 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7526 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7527 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7528 // Get reciprocal estimate. 7529 // float4 recip = vrecpeq_f32(yf); 7530 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7531 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7532 Y); 7533 // Because char has a smaller range than uchar, we can actually get away 7534 // without any newton steps. This requires that we use a weird bias 7535 // of 0xb000, however (again, this has been exhaustively tested). 7536 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7537 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7538 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7539 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7540 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7541 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7542 // Convert back to short. 7543 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7544 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7545 return X; 7546 } 7547 7548 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7549 SelectionDAG &DAG) { 7550 // TODO: Should this propagate fast-math-flags? 7551 7552 SDValue N2; 7553 // Convert to float. 7554 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7555 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7556 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7557 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7558 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7559 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7560 7561 // Use reciprocal estimate and one refinement step. 7562 // float4 recip = vrecpeq_f32(yf); 7563 // recip *= vrecpsq_f32(yf, recip); 7564 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7565 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7566 N1); 7567 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7568 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7569 N1, N2); 7570 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7571 // Because short has a smaller range than ushort, we can actually get away 7572 // with only a single newton step. This requires that we use a weird bias 7573 // of 89, however (again, this has been exhaustively tested). 7574 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7575 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7576 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7577 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7578 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7579 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7580 // Convert back to integer and return. 7581 // return vmovn_s32(vcvt_s32_f32(result)); 7582 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7583 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7584 return N0; 7585 } 7586 7587 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7588 EVT VT = Op.getValueType(); 7589 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7590 "unexpected type for custom-lowering ISD::SDIV"); 7591 7592 SDLoc dl(Op); 7593 SDValue N0 = Op.getOperand(0); 7594 SDValue N1 = Op.getOperand(1); 7595 SDValue N2, N3; 7596 7597 if (VT == MVT::v8i8) { 7598 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7599 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7600 7601 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7602 DAG.getIntPtrConstant(4, dl)); 7603 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7604 DAG.getIntPtrConstant(4, dl)); 7605 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7606 DAG.getIntPtrConstant(0, dl)); 7607 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7608 DAG.getIntPtrConstant(0, dl)); 7609 7610 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7611 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7612 7613 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7614 N0 = LowerCONCAT_VECTORS(N0, DAG); 7615 7616 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7617 return N0; 7618 } 7619 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7620 } 7621 7622 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7623 // TODO: Should this propagate fast-math-flags? 7624 EVT VT = Op.getValueType(); 7625 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7626 "unexpected type for custom-lowering ISD::UDIV"); 7627 7628 SDLoc dl(Op); 7629 SDValue N0 = Op.getOperand(0); 7630 SDValue N1 = Op.getOperand(1); 7631 SDValue N2, N3; 7632 7633 if (VT == MVT::v8i8) { 7634 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7635 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7636 7637 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7638 DAG.getIntPtrConstant(4, dl)); 7639 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7640 DAG.getIntPtrConstant(4, dl)); 7641 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7642 DAG.getIntPtrConstant(0, dl)); 7643 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7644 DAG.getIntPtrConstant(0, dl)); 7645 7646 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7647 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7648 7649 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7650 N0 = LowerCONCAT_VECTORS(N0, DAG); 7651 7652 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7653 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7654 MVT::i32), 7655 N0); 7656 return N0; 7657 } 7658 7659 // v4i16 sdiv ... Convert to float. 7660 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7661 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7662 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7663 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7664 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7665 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7666 7667 // Use reciprocal estimate and two refinement steps. 7668 // float4 recip = vrecpeq_f32(yf); 7669 // recip *= vrecpsq_f32(yf, recip); 7670 // recip *= vrecpsq_f32(yf, recip); 7671 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7672 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7673 BN1); 7674 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7675 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7676 BN1, N2); 7677 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7678 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7679 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7680 BN1, N2); 7681 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7682 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7683 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7684 // and that it will never cause us to return an answer too large). 7685 // float4 result = as_float4(as_int4(xf*recip) + 2); 7686 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7687 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7688 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7689 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7690 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7691 // Convert back to integer and return. 7692 // return vmovn_u32(vcvt_s32_f32(result)); 7693 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7694 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7695 return N0; 7696 } 7697 7698 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7699 EVT VT = Op.getNode()->getValueType(0); 7700 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7701 7702 unsigned Opc; 7703 bool ExtraOp = false; 7704 switch (Op.getOpcode()) { 7705 default: llvm_unreachable("Invalid code"); 7706 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7707 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7708 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7709 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7710 } 7711 7712 if (!ExtraOp) 7713 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7714 Op.getOperand(1)); 7715 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7716 Op.getOperand(1), Op.getOperand(2)); 7717 } 7718 7719 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 7720 SDNode *N = Op.getNode(); 7721 EVT VT = N->getValueType(0); 7722 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7723 7724 SDValue Carry = Op.getOperand(2); 7725 7726 SDLoc DL(Op); 7727 7728 SDValue Result; 7729 if (Op.getOpcode() == ISD::ADDCARRY) { 7730 // This converts the boolean value carry into the carry flag. 7731 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7732 7733 // Do the addition proper using the carry flag we wanted. 7734 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 7735 Op.getOperand(1), Carry.getValue(1)); 7736 7737 // Now convert the carry flag into a boolean value. 7738 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7739 } else { 7740 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 7741 // have to invert the carry first. 7742 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7743 DAG.getConstant(1, DL, MVT::i32), Carry); 7744 // This converts the boolean value carry into the carry flag. 7745 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7746 7747 // Do the subtraction proper using the carry flag we wanted. 7748 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 7749 Op.getOperand(1), Carry.getValue(1)); 7750 7751 // Now convert the carry flag into a boolean value. 7752 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7753 // But the carry returned by ARMISD::SUBE is not a borrow as expected 7754 // by ISD::SUBCARRY, so compute 1 - C. 7755 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7756 DAG.getConstant(1, DL, MVT::i32), Carry); 7757 } 7758 7759 // Return both values. 7760 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 7761 } 7762 7763 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7764 assert(Subtarget->isTargetDarwin()); 7765 7766 // For iOS, we want to call an alternative entry point: __sincos_stret, 7767 // return values are passed via sret. 7768 SDLoc dl(Op); 7769 SDValue Arg = Op.getOperand(0); 7770 EVT ArgVT = Arg.getValueType(); 7771 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7772 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7773 7774 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7775 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7776 7777 // Pair of floats / doubles used to pass the result. 7778 Type *RetTy = StructType::get(ArgTy, ArgTy); 7779 auto &DL = DAG.getDataLayout(); 7780 7781 ArgListTy Args; 7782 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7783 SDValue SRet; 7784 if (ShouldUseSRet) { 7785 // Create stack object for sret. 7786 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7787 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7788 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7789 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7790 7791 ArgListEntry Entry; 7792 Entry.Node = SRet; 7793 Entry.Ty = RetTy->getPointerTo(); 7794 Entry.IsSExt = false; 7795 Entry.IsZExt = false; 7796 Entry.IsSRet = true; 7797 Args.push_back(Entry); 7798 RetTy = Type::getVoidTy(*DAG.getContext()); 7799 } 7800 7801 ArgListEntry Entry; 7802 Entry.Node = Arg; 7803 Entry.Ty = ArgTy; 7804 Entry.IsSExt = false; 7805 Entry.IsZExt = false; 7806 Args.push_back(Entry); 7807 7808 RTLIB::Libcall LC = 7809 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 7810 const char *LibcallName = getLibcallName(LC); 7811 CallingConv::ID CC = getLibcallCallingConv(LC); 7812 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7813 7814 TargetLowering::CallLoweringInfo CLI(DAG); 7815 CLI.setDebugLoc(dl) 7816 .setChain(DAG.getEntryNode()) 7817 .setCallee(CC, RetTy, Callee, std::move(Args)) 7818 .setDiscardResult(ShouldUseSRet); 7819 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7820 7821 if (!ShouldUseSRet) 7822 return CallResult.first; 7823 7824 SDValue LoadSin = 7825 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7826 7827 // Address of cos field. 7828 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7829 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7830 SDValue LoadCos = 7831 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7832 7833 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7834 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7835 LoadSin.getValue(0), LoadCos.getValue(0)); 7836 } 7837 7838 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7839 bool Signed, 7840 SDValue &Chain) const { 7841 EVT VT = Op.getValueType(); 7842 assert((VT == MVT::i32 || VT == MVT::i64) && 7843 "unexpected type for custom lowering DIV"); 7844 SDLoc dl(Op); 7845 7846 const auto &DL = DAG.getDataLayout(); 7847 const auto &TLI = DAG.getTargetLoweringInfo(); 7848 7849 const char *Name = nullptr; 7850 if (Signed) 7851 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7852 else 7853 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7854 7855 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7856 7857 ARMTargetLowering::ArgListTy Args; 7858 7859 for (auto AI : {1, 0}) { 7860 ArgListEntry Arg; 7861 Arg.Node = Op.getOperand(AI); 7862 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7863 Args.push_back(Arg); 7864 } 7865 7866 CallLoweringInfo CLI(DAG); 7867 CLI.setDebugLoc(dl) 7868 .setChain(Chain) 7869 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7870 ES, std::move(Args)); 7871 7872 return LowerCallTo(CLI).first; 7873 } 7874 7875 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7876 bool Signed) const { 7877 assert(Op.getValueType() == MVT::i32 && 7878 "unexpected type for custom lowering DIV"); 7879 SDLoc dl(Op); 7880 7881 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7882 DAG.getEntryNode(), Op.getOperand(1)); 7883 7884 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7885 } 7886 7887 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7888 SDLoc DL(N); 7889 SDValue Op = N->getOperand(1); 7890 if (N->getValueType(0) == MVT::i32) 7891 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7892 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7893 DAG.getConstant(0, DL, MVT::i32)); 7894 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7895 DAG.getConstant(1, DL, MVT::i32)); 7896 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7897 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7898 } 7899 7900 void ARMTargetLowering::ExpandDIV_Windows( 7901 SDValue Op, SelectionDAG &DAG, bool Signed, 7902 SmallVectorImpl<SDValue> &Results) const { 7903 const auto &DL = DAG.getDataLayout(); 7904 const auto &TLI = DAG.getTargetLoweringInfo(); 7905 7906 assert(Op.getValueType() == MVT::i64 && 7907 "unexpected type for custom lowering DIV"); 7908 SDLoc dl(Op); 7909 7910 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7911 7912 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7913 7914 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7915 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7916 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7917 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7918 7919 Results.push_back(Lower); 7920 Results.push_back(Upper); 7921 } 7922 7923 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7924 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7925 // Acquire/Release load/store is not legal for targets without a dmb or 7926 // equivalent available. 7927 return SDValue(); 7928 7929 // Monotonic load/store is legal for all targets. 7930 return Op; 7931 } 7932 7933 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7934 SmallVectorImpl<SDValue> &Results, 7935 SelectionDAG &DAG, 7936 const ARMSubtarget *Subtarget) { 7937 SDLoc DL(N); 7938 // Under Power Management extensions, the cycle-count is: 7939 // mrc p15, #0, <Rt>, c9, c13, #0 7940 SDValue Ops[] = { N->getOperand(0), // Chain 7941 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7942 DAG.getConstant(15, DL, MVT::i32), 7943 DAG.getConstant(0, DL, MVT::i32), 7944 DAG.getConstant(9, DL, MVT::i32), 7945 DAG.getConstant(13, DL, MVT::i32), 7946 DAG.getConstant(0, DL, MVT::i32) 7947 }; 7948 7949 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7950 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7951 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7952 DAG.getConstant(0, DL, MVT::i32))); 7953 Results.push_back(Cycles32.getValue(1)); 7954 } 7955 7956 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7957 SDLoc dl(V.getNode()); 7958 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7959 SDValue VHi = DAG.getAnyExtOrTrunc( 7960 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7961 dl, MVT::i32); 7962 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7963 if (isBigEndian) 7964 std::swap (VLo, VHi); 7965 SDValue RegClass = 7966 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7967 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7968 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7969 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7970 return SDValue( 7971 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7972 } 7973 7974 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7975 SmallVectorImpl<SDValue> & Results, 7976 SelectionDAG &DAG) { 7977 assert(N->getValueType(0) == MVT::i64 && 7978 "AtomicCmpSwap on types less than 64 should be legal"); 7979 SDValue Ops[] = {N->getOperand(1), 7980 createGPRPairNode(DAG, N->getOperand(2)), 7981 createGPRPairNode(DAG, N->getOperand(3)), 7982 N->getOperand(0)}; 7983 SDNode *CmpSwap = DAG.getMachineNode( 7984 ARM::CMP_SWAP_64, SDLoc(N), 7985 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7986 7987 MachineFunction &MF = DAG.getMachineFunction(); 7988 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7989 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7990 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7991 7992 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7993 7994 Results.push_back( 7995 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 7996 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7997 Results.push_back( 7998 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 7999 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8000 Results.push_back(SDValue(CmpSwap, 2)); 8001 } 8002 8003 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 8004 SelectionDAG &DAG) { 8005 const auto &TLI = DAG.getTargetLoweringInfo(); 8006 8007 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 8008 "Custom lowering is MSVCRT specific!"); 8009 8010 SDLoc dl(Op); 8011 SDValue Val = Op.getOperand(0); 8012 MVT Ty = Val->getSimpleValueType(0); 8013 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 8014 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 8015 TLI.getPointerTy(DAG.getDataLayout())); 8016 8017 TargetLowering::ArgListTy Args; 8018 TargetLowering::ArgListEntry Entry; 8019 8020 Entry.Node = Val; 8021 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8022 Entry.IsZExt = true; 8023 Args.push_back(Entry); 8024 8025 Entry.Node = Exponent; 8026 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 8027 Entry.IsZExt = true; 8028 Args.push_back(Entry); 8029 8030 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8031 8032 // In the in-chain to the call is the entry node If we are emitting a 8033 // tailcall, the chain will be mutated if the node has a non-entry input 8034 // chain. 8035 SDValue InChain = DAG.getEntryNode(); 8036 SDValue TCChain = InChain; 8037 8038 const Function &F = DAG.getMachineFunction().getFunction(); 8039 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8040 F.getReturnType() == LCRTy; 8041 if (IsTC) 8042 InChain = TCChain; 8043 8044 TargetLowering::CallLoweringInfo CLI(DAG); 8045 CLI.setDebugLoc(dl) 8046 .setChain(InChain) 8047 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8048 .setTailCall(IsTC); 8049 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8050 8051 // Return the chain (the DAG root) if it is a tail call 8052 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8053 } 8054 8055 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8056 DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8057 switch (Op.getOpcode()) { 8058 default: llvm_unreachable("Don't know how to custom lower this!"); 8059 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8060 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8061 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8062 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8063 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8064 case ISD::SELECT: return LowerSELECT(Op, DAG); 8065 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8066 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8067 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8068 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8069 case ISD::VASTART: return LowerVASTART(Op, DAG); 8070 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8071 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8072 case ISD::SINT_TO_FP: 8073 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8074 case ISD::FP_TO_SINT: 8075 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8076 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8077 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8078 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8079 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8080 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8081 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8082 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8083 Subtarget); 8084 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8085 case ISD::SHL: 8086 case ISD::SRL: 8087 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8088 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8089 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8090 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8091 case ISD::SRL_PARTS: 8092 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8093 case ISD::CTTZ: 8094 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8095 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8096 case ISD::SETCC: return LowerVSETCC(Op, DAG); 8097 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 8098 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8099 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8100 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 8101 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8102 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 8103 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 8104 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8105 case ISD::MUL: return LowerMUL(Op, DAG); 8106 case ISD::SDIV: 8107 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8108 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8109 return LowerSDIV(Op, DAG); 8110 case ISD::UDIV: 8111 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8112 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8113 return LowerUDIV(Op, DAG); 8114 case ISD::ADDC: 8115 case ISD::ADDE: 8116 case ISD::SUBC: 8117 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 8118 case ISD::ADDCARRY: 8119 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8120 case ISD::SADDO: 8121 case ISD::SSUBO: 8122 return LowerSignedALUO(Op, DAG); 8123 case ISD::UADDO: 8124 case ISD::USUBO: 8125 return LowerUnsignedALUO(Op, DAG); 8126 case ISD::ATOMIC_LOAD: 8127 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8128 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8129 case ISD::SDIVREM: 8130 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8131 case ISD::DYNAMIC_STACKALLOC: 8132 if (Subtarget->isTargetWindows()) 8133 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8134 llvm_unreachable("Don't know how to custom lower this!"); 8135 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8136 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8137 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8138 case ARMISD::WIN__DBZCHK: return SDValue(); 8139 } 8140 } 8141 8142 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8143 SelectionDAG &DAG) { 8144 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8145 unsigned Opc = 0; 8146 if (IntNo == Intrinsic::arm_smlald) 8147 Opc = ARMISD::SMLALD; 8148 else if (IntNo == Intrinsic::arm_smlaldx) 8149 Opc = ARMISD::SMLALDX; 8150 else if (IntNo == Intrinsic::arm_smlsld) 8151 Opc = ARMISD::SMLSLD; 8152 else if (IntNo == Intrinsic::arm_smlsldx) 8153 Opc = ARMISD::SMLSLDX; 8154 else 8155 return; 8156 8157 SDLoc dl(N); 8158 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8159 N->getOperand(3), 8160 DAG.getConstant(0, dl, MVT::i32)); 8161 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8162 N->getOperand(3), 8163 DAG.getConstant(1, dl, MVT::i32)); 8164 8165 SDValue LongMul = DAG.getNode(Opc, dl, 8166 DAG.getVTList(MVT::i32, MVT::i32), 8167 N->getOperand(1), N->getOperand(2), 8168 Lo, Hi); 8169 Results.push_back(LongMul.getValue(0)); 8170 Results.push_back(LongMul.getValue(1)); 8171 } 8172 8173 /// ReplaceNodeResults - Replace the results of node with an illegal result 8174 /// type with new values built out of custom code. 8175 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8176 SmallVectorImpl<SDValue> &Results, 8177 SelectionDAG &DAG) const { 8178 SDValue Res; 8179 switch (N->getOpcode()) { 8180 default: 8181 llvm_unreachable("Don't know how to custom expand this!"); 8182 case ISD::READ_REGISTER: 8183 ExpandREAD_REGISTER(N, Results, DAG); 8184 break; 8185 case ISD::BITCAST: 8186 Res = ExpandBITCAST(N, DAG, Subtarget); 8187 break; 8188 case ISD::SRL: 8189 case ISD::SRA: 8190 Res = Expand64BitShift(N, DAG, Subtarget); 8191 break; 8192 case ISD::SREM: 8193 case ISD::UREM: 8194 Res = LowerREM(N, DAG); 8195 break; 8196 case ISD::SDIVREM: 8197 case ISD::UDIVREM: 8198 Res = LowerDivRem(SDValue(N, 0), DAG); 8199 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 8200 Results.push_back(Res.getValue(0)); 8201 Results.push_back(Res.getValue(1)); 8202 return; 8203 case ISD::READCYCLECOUNTER: 8204 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8205 return; 8206 case ISD::UDIV: 8207 case ISD::SDIV: 8208 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8209 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8210 Results); 8211 case ISD::ATOMIC_CMP_SWAP: 8212 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8213 return; 8214 case ISD::INTRINSIC_WO_CHAIN: 8215 return ReplaceLongIntrinsic(N, Results, DAG); 8216 } 8217 if (Res.getNode()) 8218 Results.push_back(Res); 8219 } 8220 8221 //===----------------------------------------------------------------------===// 8222 // ARM Scheduler Hooks 8223 //===----------------------------------------------------------------------===// 8224 8225 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8226 /// registers the function context. 8227 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8228 MachineBasicBlock *MBB, 8229 MachineBasicBlock *DispatchBB, 8230 int FI) const { 8231 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8232 "ROPI/RWPI not currently supported with SjLj"); 8233 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8234 DebugLoc dl = MI.getDebugLoc(); 8235 MachineFunction *MF = MBB->getParent(); 8236 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8237 MachineConstantPool *MCP = MF->getConstantPool(); 8238 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8239 const Function &F = MF->getFunction(); 8240 8241 bool isThumb = Subtarget->isThumb(); 8242 bool isThumb2 = Subtarget->isThumb2(); 8243 8244 unsigned PCLabelId = AFI->createPICLabelUId(); 8245 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 8246 ARMConstantPoolValue *CPV = 8247 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 8248 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 8249 8250 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 8251 : &ARM::GPRRegClass; 8252 8253 // Grab constant pool and fixed stack memory operands. 8254 MachineMemOperand *CPMMO = 8255 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 8256 MachineMemOperand::MOLoad, 4, 4); 8257 8258 MachineMemOperand *FIMMOSt = 8259 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 8260 MachineMemOperand::MOStore, 4, 4); 8261 8262 // Load the address of the dispatch MBB into the jump buffer. 8263 if (isThumb2) { 8264 // Incoming value: jbuf 8265 // ldr.n r5, LCPI1_1 8266 // orr r5, r5, #1 8267 // add r5, pc 8268 // str r5, [$jbuf, #+4] ; &jbuf[1] 8269 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8270 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 8271 .addConstantPoolIndex(CPI) 8272 .addMemOperand(CPMMO) 8273 .add(predOps(ARMCC::AL)); 8274 // Set the low bit because of thumb mode. 8275 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8276 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 8277 .addReg(NewVReg1, RegState::Kill) 8278 .addImm(0x01) 8279 .add(predOps(ARMCC::AL)) 8280 .add(condCodeOp()); 8281 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8282 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8283 .addReg(NewVReg2, RegState::Kill) 8284 .addImm(PCLabelId); 8285 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8286 .addReg(NewVReg3, RegState::Kill) 8287 .addFrameIndex(FI) 8288 .addImm(36) // &jbuf[1] :: pc 8289 .addMemOperand(FIMMOSt) 8290 .add(predOps(ARMCC::AL)); 8291 } else if (isThumb) { 8292 // Incoming value: jbuf 8293 // ldr.n r1, LCPI1_4 8294 // add r1, pc 8295 // mov r2, #1 8296 // orrs r1, r2 8297 // add r2, $jbuf, #+4 ; &jbuf[1] 8298 // str r1, [r2] 8299 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8300 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8301 .addConstantPoolIndex(CPI) 8302 .addMemOperand(CPMMO) 8303 .add(predOps(ARMCC::AL)); 8304 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8305 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8306 .addReg(NewVReg1, RegState::Kill) 8307 .addImm(PCLabelId); 8308 // Set the low bit because of thumb mode. 8309 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8310 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8311 .addReg(ARM::CPSR, RegState::Define) 8312 .addImm(1) 8313 .add(predOps(ARMCC::AL)); 8314 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8315 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8316 .addReg(ARM::CPSR, RegState::Define) 8317 .addReg(NewVReg2, RegState::Kill) 8318 .addReg(NewVReg3, RegState::Kill) 8319 .add(predOps(ARMCC::AL)); 8320 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8321 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8322 .addFrameIndex(FI) 8323 .addImm(36); // &jbuf[1] :: pc 8324 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8325 .addReg(NewVReg4, RegState::Kill) 8326 .addReg(NewVReg5, RegState::Kill) 8327 .addImm(0) 8328 .addMemOperand(FIMMOSt) 8329 .add(predOps(ARMCC::AL)); 8330 } else { 8331 // Incoming value: jbuf 8332 // ldr r1, LCPI1_1 8333 // add r1, pc, r1 8334 // str r1, [$jbuf, #+4] ; &jbuf[1] 8335 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8336 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8337 .addConstantPoolIndex(CPI) 8338 .addImm(0) 8339 .addMemOperand(CPMMO) 8340 .add(predOps(ARMCC::AL)); 8341 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8342 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8343 .addReg(NewVReg1, RegState::Kill) 8344 .addImm(PCLabelId) 8345 .add(predOps(ARMCC::AL)); 8346 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8347 .addReg(NewVReg2, RegState::Kill) 8348 .addFrameIndex(FI) 8349 .addImm(36) // &jbuf[1] :: pc 8350 .addMemOperand(FIMMOSt) 8351 .add(predOps(ARMCC::AL)); 8352 } 8353 } 8354 8355 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8356 MachineBasicBlock *MBB) const { 8357 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8358 DebugLoc dl = MI.getDebugLoc(); 8359 MachineFunction *MF = MBB->getParent(); 8360 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8361 MachineFrameInfo &MFI = MF->getFrameInfo(); 8362 int FI = MFI.getFunctionContextIndex(); 8363 8364 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8365 : &ARM::GPRnopcRegClass; 8366 8367 // Get a mapping of the call site numbers to all of the landing pads they're 8368 // associated with. 8369 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8370 unsigned MaxCSNum = 0; 8371 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8372 ++BB) { 8373 if (!BB->isEHPad()) continue; 8374 8375 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8376 // pad. 8377 for (MachineBasicBlock::iterator 8378 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8379 if (!II->isEHLabel()) continue; 8380 8381 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8382 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8383 8384 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8385 for (SmallVectorImpl<unsigned>::iterator 8386 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8387 CSI != CSE; ++CSI) { 8388 CallSiteNumToLPad[*CSI].push_back(&*BB); 8389 MaxCSNum = std::max(MaxCSNum, *CSI); 8390 } 8391 break; 8392 } 8393 } 8394 8395 // Get an ordered list of the machine basic blocks for the jump table. 8396 std::vector<MachineBasicBlock*> LPadList; 8397 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8398 LPadList.reserve(CallSiteNumToLPad.size()); 8399 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8400 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8401 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8402 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8403 LPadList.push_back(*II); 8404 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8405 } 8406 } 8407 8408 assert(!LPadList.empty() && 8409 "No landing pad destinations for the dispatch jump table!"); 8410 8411 // Create the jump table and associated information. 8412 MachineJumpTableInfo *JTI = 8413 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8414 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8415 8416 // Create the MBBs for the dispatch code. 8417 8418 // Shove the dispatch's address into the return slot in the function context. 8419 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8420 DispatchBB->setIsEHPad(); 8421 8422 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8423 unsigned trap_opcode; 8424 if (Subtarget->isThumb()) 8425 trap_opcode = ARM::tTRAP; 8426 else 8427 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8428 8429 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8430 DispatchBB->addSuccessor(TrapBB); 8431 8432 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8433 DispatchBB->addSuccessor(DispContBB); 8434 8435 // Insert and MBBs. 8436 MF->insert(MF->end(), DispatchBB); 8437 MF->insert(MF->end(), DispContBB); 8438 MF->insert(MF->end(), TrapBB); 8439 8440 // Insert code into the entry block that creates and registers the function 8441 // context. 8442 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8443 8444 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8445 MachinePointerInfo::getFixedStack(*MF, FI), 8446 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8447 8448 MachineInstrBuilder MIB; 8449 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8450 8451 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8452 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8453 8454 // Add a register mask with no preserved registers. This results in all 8455 // registers being marked as clobbered. This can't work if the dispatch block 8456 // is in a Thumb1 function and is linked with ARM code which uses the FP 8457 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8458 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8459 8460 bool IsPositionIndependent = isPositionIndependent(); 8461 unsigned NumLPads = LPadList.size(); 8462 if (Subtarget->isThumb2()) { 8463 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8464 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8465 .addFrameIndex(FI) 8466 .addImm(4) 8467 .addMemOperand(FIMMOLd) 8468 .add(predOps(ARMCC::AL)); 8469 8470 if (NumLPads < 256) { 8471 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8472 .addReg(NewVReg1) 8473 .addImm(LPadList.size()) 8474 .add(predOps(ARMCC::AL)); 8475 } else { 8476 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8477 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8478 .addImm(NumLPads & 0xFFFF) 8479 .add(predOps(ARMCC::AL)); 8480 8481 unsigned VReg2 = VReg1; 8482 if ((NumLPads & 0xFFFF0000) != 0) { 8483 VReg2 = MRI->createVirtualRegister(TRC); 8484 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8485 .addReg(VReg1) 8486 .addImm(NumLPads >> 16) 8487 .add(predOps(ARMCC::AL)); 8488 } 8489 8490 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8491 .addReg(NewVReg1) 8492 .addReg(VReg2) 8493 .add(predOps(ARMCC::AL)); 8494 } 8495 8496 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8497 .addMBB(TrapBB) 8498 .addImm(ARMCC::HI) 8499 .addReg(ARM::CPSR); 8500 8501 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8502 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8503 .addJumpTableIndex(MJTI) 8504 .add(predOps(ARMCC::AL)); 8505 8506 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8507 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8508 .addReg(NewVReg3, RegState::Kill) 8509 .addReg(NewVReg1) 8510 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8511 .add(predOps(ARMCC::AL)) 8512 .add(condCodeOp()); 8513 8514 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8515 .addReg(NewVReg4, RegState::Kill) 8516 .addReg(NewVReg1) 8517 .addJumpTableIndex(MJTI); 8518 } else if (Subtarget->isThumb()) { 8519 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8520 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8521 .addFrameIndex(FI) 8522 .addImm(1) 8523 .addMemOperand(FIMMOLd) 8524 .add(predOps(ARMCC::AL)); 8525 8526 if (NumLPads < 256) { 8527 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8528 .addReg(NewVReg1) 8529 .addImm(NumLPads) 8530 .add(predOps(ARMCC::AL)); 8531 } else { 8532 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8533 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8534 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8535 8536 // MachineConstantPool wants an explicit alignment. 8537 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8538 if (Align == 0) 8539 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8540 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8541 8542 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8543 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8544 .addReg(VReg1, RegState::Define) 8545 .addConstantPoolIndex(Idx) 8546 .add(predOps(ARMCC::AL)); 8547 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8548 .addReg(NewVReg1) 8549 .addReg(VReg1) 8550 .add(predOps(ARMCC::AL)); 8551 } 8552 8553 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8554 .addMBB(TrapBB) 8555 .addImm(ARMCC::HI) 8556 .addReg(ARM::CPSR); 8557 8558 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8559 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8560 .addReg(ARM::CPSR, RegState::Define) 8561 .addReg(NewVReg1) 8562 .addImm(2) 8563 .add(predOps(ARMCC::AL)); 8564 8565 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8566 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8567 .addJumpTableIndex(MJTI) 8568 .add(predOps(ARMCC::AL)); 8569 8570 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8571 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8572 .addReg(ARM::CPSR, RegState::Define) 8573 .addReg(NewVReg2, RegState::Kill) 8574 .addReg(NewVReg3) 8575 .add(predOps(ARMCC::AL)); 8576 8577 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8578 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8579 8580 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8581 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8582 .addReg(NewVReg4, RegState::Kill) 8583 .addImm(0) 8584 .addMemOperand(JTMMOLd) 8585 .add(predOps(ARMCC::AL)); 8586 8587 unsigned NewVReg6 = NewVReg5; 8588 if (IsPositionIndependent) { 8589 NewVReg6 = MRI->createVirtualRegister(TRC); 8590 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8591 .addReg(ARM::CPSR, RegState::Define) 8592 .addReg(NewVReg5, RegState::Kill) 8593 .addReg(NewVReg3) 8594 .add(predOps(ARMCC::AL)); 8595 } 8596 8597 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8598 .addReg(NewVReg6, RegState::Kill) 8599 .addJumpTableIndex(MJTI); 8600 } else { 8601 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8602 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8603 .addFrameIndex(FI) 8604 .addImm(4) 8605 .addMemOperand(FIMMOLd) 8606 .add(predOps(ARMCC::AL)); 8607 8608 if (NumLPads < 256) { 8609 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8610 .addReg(NewVReg1) 8611 .addImm(NumLPads) 8612 .add(predOps(ARMCC::AL)); 8613 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8614 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8615 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8616 .addImm(NumLPads & 0xFFFF) 8617 .add(predOps(ARMCC::AL)); 8618 8619 unsigned VReg2 = VReg1; 8620 if ((NumLPads & 0xFFFF0000) != 0) { 8621 VReg2 = MRI->createVirtualRegister(TRC); 8622 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8623 .addReg(VReg1) 8624 .addImm(NumLPads >> 16) 8625 .add(predOps(ARMCC::AL)); 8626 } 8627 8628 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8629 .addReg(NewVReg1) 8630 .addReg(VReg2) 8631 .add(predOps(ARMCC::AL)); 8632 } else { 8633 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8634 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8635 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8636 8637 // MachineConstantPool wants an explicit alignment. 8638 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8639 if (Align == 0) 8640 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8641 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8642 8643 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8644 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8645 .addReg(VReg1, RegState::Define) 8646 .addConstantPoolIndex(Idx) 8647 .addImm(0) 8648 .add(predOps(ARMCC::AL)); 8649 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8650 .addReg(NewVReg1) 8651 .addReg(VReg1, RegState::Kill) 8652 .add(predOps(ARMCC::AL)); 8653 } 8654 8655 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8656 .addMBB(TrapBB) 8657 .addImm(ARMCC::HI) 8658 .addReg(ARM::CPSR); 8659 8660 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8661 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8662 .addReg(NewVReg1) 8663 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8664 .add(predOps(ARMCC::AL)) 8665 .add(condCodeOp()); 8666 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8667 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8668 .addJumpTableIndex(MJTI) 8669 .add(predOps(ARMCC::AL)); 8670 8671 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8672 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8673 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8674 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8675 .addReg(NewVReg3, RegState::Kill) 8676 .addReg(NewVReg4) 8677 .addImm(0) 8678 .addMemOperand(JTMMOLd) 8679 .add(predOps(ARMCC::AL)); 8680 8681 if (IsPositionIndependent) { 8682 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8683 .addReg(NewVReg5, RegState::Kill) 8684 .addReg(NewVReg4) 8685 .addJumpTableIndex(MJTI); 8686 } else { 8687 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8688 .addReg(NewVReg5, RegState::Kill) 8689 .addJumpTableIndex(MJTI); 8690 } 8691 } 8692 8693 // Add the jump table entries as successors to the MBB. 8694 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8695 for (std::vector<MachineBasicBlock*>::iterator 8696 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8697 MachineBasicBlock *CurMBB = *I; 8698 if (SeenMBBs.insert(CurMBB).second) 8699 DispContBB->addSuccessor(CurMBB); 8700 } 8701 8702 // N.B. the order the invoke BBs are processed in doesn't matter here. 8703 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8704 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8705 for (MachineBasicBlock *BB : InvokeBBs) { 8706 8707 // Remove the landing pad successor from the invoke block and replace it 8708 // with the new dispatch block. 8709 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8710 BB->succ_end()); 8711 while (!Successors.empty()) { 8712 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8713 if (SMBB->isEHPad()) { 8714 BB->removeSuccessor(SMBB); 8715 MBBLPads.push_back(SMBB); 8716 } 8717 } 8718 8719 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8720 BB->normalizeSuccProbs(); 8721 8722 // Find the invoke call and mark all of the callee-saved registers as 8723 // 'implicit defined' so that they're spilled. This prevents code from 8724 // moving instructions to before the EH block, where they will never be 8725 // executed. 8726 for (MachineBasicBlock::reverse_iterator 8727 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8728 if (!II->isCall()) continue; 8729 8730 DenseMap<unsigned, bool> DefRegs; 8731 for (MachineInstr::mop_iterator 8732 OI = II->operands_begin(), OE = II->operands_end(); 8733 OI != OE; ++OI) { 8734 if (!OI->isReg()) continue; 8735 DefRegs[OI->getReg()] = true; 8736 } 8737 8738 MachineInstrBuilder MIB(*MF, &*II); 8739 8740 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8741 unsigned Reg = SavedRegs[i]; 8742 if (Subtarget->isThumb2() && 8743 !ARM::tGPRRegClass.contains(Reg) && 8744 !ARM::hGPRRegClass.contains(Reg)) 8745 continue; 8746 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8747 continue; 8748 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8749 continue; 8750 if (!DefRegs[Reg]) 8751 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8752 } 8753 8754 break; 8755 } 8756 } 8757 8758 // Mark all former landing pads as non-landing pads. The dispatch is the only 8759 // landing pad now. 8760 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8761 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8762 (*I)->setIsEHPad(false); 8763 8764 // The instruction is gone now. 8765 MI.eraseFromParent(); 8766 } 8767 8768 static 8769 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8770 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8771 E = MBB->succ_end(); I != E; ++I) 8772 if (*I != Succ) 8773 return *I; 8774 llvm_unreachable("Expecting a BB with two successors!"); 8775 } 8776 8777 /// Return the load opcode for a given load size. If load size >= 8, 8778 /// neon opcode will be returned. 8779 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8780 if (LdSize >= 8) 8781 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8782 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8783 if (IsThumb1) 8784 return LdSize == 4 ? ARM::tLDRi 8785 : LdSize == 2 ? ARM::tLDRHi 8786 : LdSize == 1 ? ARM::tLDRBi : 0; 8787 if (IsThumb2) 8788 return LdSize == 4 ? ARM::t2LDR_POST 8789 : LdSize == 2 ? ARM::t2LDRH_POST 8790 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8791 return LdSize == 4 ? ARM::LDR_POST_IMM 8792 : LdSize == 2 ? ARM::LDRH_POST 8793 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8794 } 8795 8796 /// Return the store opcode for a given store size. If store size >= 8, 8797 /// neon opcode will be returned. 8798 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8799 if (StSize >= 8) 8800 return StSize == 16 ? ARM::VST1q32wb_fixed 8801 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8802 if (IsThumb1) 8803 return StSize == 4 ? ARM::tSTRi 8804 : StSize == 2 ? ARM::tSTRHi 8805 : StSize == 1 ? ARM::tSTRBi : 0; 8806 if (IsThumb2) 8807 return StSize == 4 ? ARM::t2STR_POST 8808 : StSize == 2 ? ARM::t2STRH_POST 8809 : StSize == 1 ? ARM::t2STRB_POST : 0; 8810 return StSize == 4 ? ARM::STR_POST_IMM 8811 : StSize == 2 ? ARM::STRH_POST 8812 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8813 } 8814 8815 /// Emit a post-increment load operation with given size. The instructions 8816 /// will be added to BB at Pos. 8817 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8818 const TargetInstrInfo *TII, const DebugLoc &dl, 8819 unsigned LdSize, unsigned Data, unsigned AddrIn, 8820 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8821 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8822 assert(LdOpc != 0 && "Should have a load opcode"); 8823 if (LdSize >= 8) { 8824 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8825 .addReg(AddrOut, RegState::Define) 8826 .addReg(AddrIn) 8827 .addImm(0) 8828 .add(predOps(ARMCC::AL)); 8829 } else if (IsThumb1) { 8830 // load + update AddrIn 8831 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8832 .addReg(AddrIn) 8833 .addImm(0) 8834 .add(predOps(ARMCC::AL)); 8835 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8836 .add(t1CondCodeOp()) 8837 .addReg(AddrIn) 8838 .addImm(LdSize) 8839 .add(predOps(ARMCC::AL)); 8840 } else if (IsThumb2) { 8841 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8842 .addReg(AddrOut, RegState::Define) 8843 .addReg(AddrIn) 8844 .addImm(LdSize) 8845 .add(predOps(ARMCC::AL)); 8846 } else { // arm 8847 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8848 .addReg(AddrOut, RegState::Define) 8849 .addReg(AddrIn) 8850 .addReg(0) 8851 .addImm(LdSize) 8852 .add(predOps(ARMCC::AL)); 8853 } 8854 } 8855 8856 /// Emit a post-increment store operation with given size. The instructions 8857 /// will be added to BB at Pos. 8858 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8859 const TargetInstrInfo *TII, const DebugLoc &dl, 8860 unsigned StSize, unsigned Data, unsigned AddrIn, 8861 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8862 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8863 assert(StOpc != 0 && "Should have a store opcode"); 8864 if (StSize >= 8) { 8865 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8866 .addReg(AddrIn) 8867 .addImm(0) 8868 .addReg(Data) 8869 .add(predOps(ARMCC::AL)); 8870 } else if (IsThumb1) { 8871 // store + update AddrIn 8872 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8873 .addReg(Data) 8874 .addReg(AddrIn) 8875 .addImm(0) 8876 .add(predOps(ARMCC::AL)); 8877 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8878 .add(t1CondCodeOp()) 8879 .addReg(AddrIn) 8880 .addImm(StSize) 8881 .add(predOps(ARMCC::AL)); 8882 } else if (IsThumb2) { 8883 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8884 .addReg(Data) 8885 .addReg(AddrIn) 8886 .addImm(StSize) 8887 .add(predOps(ARMCC::AL)); 8888 } else { // arm 8889 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8890 .addReg(Data) 8891 .addReg(AddrIn) 8892 .addReg(0) 8893 .addImm(StSize) 8894 .add(predOps(ARMCC::AL)); 8895 } 8896 } 8897 8898 MachineBasicBlock * 8899 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8900 MachineBasicBlock *BB) const { 8901 // This pseudo instruction has 3 operands: dst, src, size 8902 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8903 // Otherwise, we will generate unrolled scalar copies. 8904 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8905 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8906 MachineFunction::iterator It = ++BB->getIterator(); 8907 8908 unsigned dest = MI.getOperand(0).getReg(); 8909 unsigned src = MI.getOperand(1).getReg(); 8910 unsigned SizeVal = MI.getOperand(2).getImm(); 8911 unsigned Align = MI.getOperand(3).getImm(); 8912 DebugLoc dl = MI.getDebugLoc(); 8913 8914 MachineFunction *MF = BB->getParent(); 8915 MachineRegisterInfo &MRI = MF->getRegInfo(); 8916 unsigned UnitSize = 0; 8917 const TargetRegisterClass *TRC = nullptr; 8918 const TargetRegisterClass *VecTRC = nullptr; 8919 8920 bool IsThumb1 = Subtarget->isThumb1Only(); 8921 bool IsThumb2 = Subtarget->isThumb2(); 8922 bool IsThumb = Subtarget->isThumb(); 8923 8924 if (Align & 1) { 8925 UnitSize = 1; 8926 } else if (Align & 2) { 8927 UnitSize = 2; 8928 } else { 8929 // Check whether we can use NEON instructions. 8930 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 8931 Subtarget->hasNEON()) { 8932 if ((Align % 16 == 0) && SizeVal >= 16) 8933 UnitSize = 16; 8934 else if ((Align % 8 == 0) && SizeVal >= 8) 8935 UnitSize = 8; 8936 } 8937 // Can't use NEON instructions. 8938 if (UnitSize == 0) 8939 UnitSize = 4; 8940 } 8941 8942 // Select the correct opcode and register class for unit size load/store 8943 bool IsNeon = UnitSize >= 8; 8944 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8945 if (IsNeon) 8946 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8947 : UnitSize == 8 ? &ARM::DPRRegClass 8948 : nullptr; 8949 8950 unsigned BytesLeft = SizeVal % UnitSize; 8951 unsigned LoopSize = SizeVal - BytesLeft; 8952 8953 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8954 // Use LDR and STR to copy. 8955 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8956 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8957 unsigned srcIn = src; 8958 unsigned destIn = dest; 8959 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8960 unsigned srcOut = MRI.createVirtualRegister(TRC); 8961 unsigned destOut = MRI.createVirtualRegister(TRC); 8962 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8963 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8964 IsThumb1, IsThumb2); 8965 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8966 IsThumb1, IsThumb2); 8967 srcIn = srcOut; 8968 destIn = destOut; 8969 } 8970 8971 // Handle the leftover bytes with LDRB and STRB. 8972 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8973 // [destOut] = STRB_POST(scratch, destIn, 1) 8974 for (unsigned i = 0; i < BytesLeft; i++) { 8975 unsigned srcOut = MRI.createVirtualRegister(TRC); 8976 unsigned destOut = MRI.createVirtualRegister(TRC); 8977 unsigned scratch = MRI.createVirtualRegister(TRC); 8978 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8979 IsThumb1, IsThumb2); 8980 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8981 IsThumb1, IsThumb2); 8982 srcIn = srcOut; 8983 destIn = destOut; 8984 } 8985 MI.eraseFromParent(); // The instruction is gone now. 8986 return BB; 8987 } 8988 8989 // Expand the pseudo op to a loop. 8990 // thisMBB: 8991 // ... 8992 // movw varEnd, # --> with thumb2 8993 // movt varEnd, # 8994 // ldrcp varEnd, idx --> without thumb2 8995 // fallthrough --> loopMBB 8996 // loopMBB: 8997 // PHI varPhi, varEnd, varLoop 8998 // PHI srcPhi, src, srcLoop 8999 // PHI destPhi, dst, destLoop 9000 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9001 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 9002 // subs varLoop, varPhi, #UnitSize 9003 // bne loopMBB 9004 // fallthrough --> exitMBB 9005 // exitMBB: 9006 // epilogue to handle left-over bytes 9007 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9008 // [destOut] = STRB_POST(scratch, destLoop, 1) 9009 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9010 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9011 MF->insert(It, loopMBB); 9012 MF->insert(It, exitMBB); 9013 9014 // Transfer the remainder of BB and its successor edges to exitMBB. 9015 exitMBB->splice(exitMBB->begin(), BB, 9016 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9017 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9018 9019 // Load an immediate to varEnd. 9020 unsigned varEnd = MRI.createVirtualRegister(TRC); 9021 if (Subtarget->useMovt(*MF)) { 9022 unsigned Vtmp = varEnd; 9023 if ((LoopSize & 0xFFFF0000) != 0) 9024 Vtmp = MRI.createVirtualRegister(TRC); 9025 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 9026 .addImm(LoopSize & 0xFFFF) 9027 .add(predOps(ARMCC::AL)); 9028 9029 if ((LoopSize & 0xFFFF0000) != 0) 9030 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 9031 .addReg(Vtmp) 9032 .addImm(LoopSize >> 16) 9033 .add(predOps(ARMCC::AL)); 9034 } else { 9035 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9036 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9037 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 9038 9039 // MachineConstantPool wants an explicit alignment. 9040 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9041 if (Align == 0) 9042 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9043 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9044 9045 if (IsThumb) 9046 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9047 .addReg(varEnd, RegState::Define) 9048 .addConstantPoolIndex(Idx) 9049 .add(predOps(ARMCC::AL)); 9050 else 9051 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9052 .addReg(varEnd, RegState::Define) 9053 .addConstantPoolIndex(Idx) 9054 .addImm(0) 9055 .add(predOps(ARMCC::AL)); 9056 } 9057 BB->addSuccessor(loopMBB); 9058 9059 // Generate the loop body: 9060 // varPhi = PHI(varLoop, varEnd) 9061 // srcPhi = PHI(srcLoop, src) 9062 // destPhi = PHI(destLoop, dst) 9063 MachineBasicBlock *entryBB = BB; 9064 BB = loopMBB; 9065 unsigned varLoop = MRI.createVirtualRegister(TRC); 9066 unsigned varPhi = MRI.createVirtualRegister(TRC); 9067 unsigned srcLoop = MRI.createVirtualRegister(TRC); 9068 unsigned srcPhi = MRI.createVirtualRegister(TRC); 9069 unsigned destLoop = MRI.createVirtualRegister(TRC); 9070 unsigned destPhi = MRI.createVirtualRegister(TRC); 9071 9072 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9073 .addReg(varLoop).addMBB(loopMBB) 9074 .addReg(varEnd).addMBB(entryBB); 9075 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9076 .addReg(srcLoop).addMBB(loopMBB) 9077 .addReg(src).addMBB(entryBB); 9078 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9079 .addReg(destLoop).addMBB(loopMBB) 9080 .addReg(dest).addMBB(entryBB); 9081 9082 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9083 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9084 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9085 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9086 IsThumb1, IsThumb2); 9087 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9088 IsThumb1, IsThumb2); 9089 9090 // Decrement loop variable by UnitSize. 9091 if (IsThumb1) { 9092 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9093 .add(t1CondCodeOp()) 9094 .addReg(varPhi) 9095 .addImm(UnitSize) 9096 .add(predOps(ARMCC::AL)); 9097 } else { 9098 MachineInstrBuilder MIB = 9099 BuildMI(*BB, BB->end(), dl, 9100 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9101 MIB.addReg(varPhi) 9102 .addImm(UnitSize) 9103 .add(predOps(ARMCC::AL)) 9104 .add(condCodeOp()); 9105 MIB->getOperand(5).setReg(ARM::CPSR); 9106 MIB->getOperand(5).setIsDef(true); 9107 } 9108 BuildMI(*BB, BB->end(), dl, 9109 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9110 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9111 9112 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9113 BB->addSuccessor(loopMBB); 9114 BB->addSuccessor(exitMBB); 9115 9116 // Add epilogue to handle BytesLeft. 9117 BB = exitMBB; 9118 auto StartOfExit = exitMBB->begin(); 9119 9120 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9121 // [destOut] = STRB_POST(scratch, destLoop, 1) 9122 unsigned srcIn = srcLoop; 9123 unsigned destIn = destLoop; 9124 for (unsigned i = 0; i < BytesLeft; i++) { 9125 unsigned srcOut = MRI.createVirtualRegister(TRC); 9126 unsigned destOut = MRI.createVirtualRegister(TRC); 9127 unsigned scratch = MRI.createVirtualRegister(TRC); 9128 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9129 IsThumb1, IsThumb2); 9130 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9131 IsThumb1, IsThumb2); 9132 srcIn = srcOut; 9133 destIn = destOut; 9134 } 9135 9136 MI.eraseFromParent(); // The instruction is gone now. 9137 return BB; 9138 } 9139 9140 MachineBasicBlock * 9141 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9142 MachineBasicBlock *MBB) const { 9143 const TargetMachine &TM = getTargetMachine(); 9144 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9145 DebugLoc DL = MI.getDebugLoc(); 9146 9147 assert(Subtarget->isTargetWindows() && 9148 "__chkstk is only supported on Windows"); 9149 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9150 9151 // __chkstk takes the number of words to allocate on the stack in R4, and 9152 // returns the stack adjustment in number of bytes in R4. This will not 9153 // clober any other registers (other than the obvious lr). 9154 // 9155 // Although, technically, IP should be considered a register which may be 9156 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9157 // thumb-2 environment, so there is no interworking required. As a result, we 9158 // do not expect a veneer to be emitted by the linker, clobbering IP. 9159 // 9160 // Each module receives its own copy of __chkstk, so no import thunk is 9161 // required, again, ensuring that IP is not clobbered. 9162 // 9163 // Finally, although some linkers may theoretically provide a trampoline for 9164 // out of range calls (which is quite common due to a 32M range limitation of 9165 // branches for Thumb), we can generate the long-call version via 9166 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9167 // IP. 9168 9169 switch (TM.getCodeModel()) { 9170 case CodeModel::Small: 9171 case CodeModel::Medium: 9172 case CodeModel::Kernel: 9173 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9174 .add(predOps(ARMCC::AL)) 9175 .addExternalSymbol("__chkstk") 9176 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9177 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9178 .addReg(ARM::R12, 9179 RegState::Implicit | RegState::Define | RegState::Dead) 9180 .addReg(ARM::CPSR, 9181 RegState::Implicit | RegState::Define | RegState::Dead); 9182 break; 9183 case CodeModel::Large: { 9184 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9185 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9186 9187 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 9188 .addExternalSymbol("__chkstk"); 9189 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 9190 .add(predOps(ARMCC::AL)) 9191 .addReg(Reg, RegState::Kill) 9192 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9193 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9194 .addReg(ARM::R12, 9195 RegState::Implicit | RegState::Define | RegState::Dead) 9196 .addReg(ARM::CPSR, 9197 RegState::Implicit | RegState::Define | RegState::Dead); 9198 break; 9199 } 9200 } 9201 9202 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9203 .addReg(ARM::SP, RegState::Kill) 9204 .addReg(ARM::R4, RegState::Kill) 9205 .setMIFlags(MachineInstr::FrameSetup) 9206 .add(predOps(ARMCC::AL)) 9207 .add(condCodeOp()); 9208 9209 MI.eraseFromParent(); 9210 return MBB; 9211 } 9212 9213 MachineBasicBlock * 9214 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9215 MachineBasicBlock *MBB) const { 9216 DebugLoc DL = MI.getDebugLoc(); 9217 MachineFunction *MF = MBB->getParent(); 9218 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9219 9220 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9221 MF->insert(++MBB->getIterator(), ContBB); 9222 ContBB->splice(ContBB->begin(), MBB, 9223 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9224 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9225 MBB->addSuccessor(ContBB); 9226 9227 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9228 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9229 MF->push_back(TrapBB); 9230 MBB->addSuccessor(TrapBB); 9231 9232 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9233 .addReg(MI.getOperand(0).getReg()) 9234 .addImm(0) 9235 .add(predOps(ARMCC::AL)); 9236 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 9237 .addMBB(TrapBB) 9238 .addImm(ARMCC::EQ) 9239 .addReg(ARM::CPSR); 9240 9241 MI.eraseFromParent(); 9242 return ContBB; 9243 } 9244 9245 MachineBasicBlock * 9246 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9247 MachineBasicBlock *BB) const { 9248 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9249 DebugLoc dl = MI.getDebugLoc(); 9250 bool isThumb2 = Subtarget->isThumb2(); 9251 switch (MI.getOpcode()) { 9252 default: { 9253 MI.print(errs()); 9254 llvm_unreachable("Unexpected instr type to insert"); 9255 } 9256 9257 // Thumb1 post-indexed loads are really just single-register LDMs. 9258 case ARM::tLDR_postidx: { 9259 MachineOperand Def(MI.getOperand(1)); 9260 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 9261 .add(Def) // Rn_wb 9262 .add(MI.getOperand(2)) // Rn 9263 .add(MI.getOperand(3)) // PredImm 9264 .add(MI.getOperand(4)) // PredReg 9265 .add(MI.getOperand(0)); // Rt 9266 MI.eraseFromParent(); 9267 return BB; 9268 } 9269 9270 // The Thumb2 pre-indexed stores have the same MI operands, they just 9271 // define them differently in the .td files from the isel patterns, so 9272 // they need pseudos. 9273 case ARM::t2STR_preidx: 9274 MI.setDesc(TII->get(ARM::t2STR_PRE)); 9275 return BB; 9276 case ARM::t2STRB_preidx: 9277 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 9278 return BB; 9279 case ARM::t2STRH_preidx: 9280 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9281 return BB; 9282 9283 case ARM::STRi_preidx: 9284 case ARM::STRBi_preidx: { 9285 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9286 : ARM::STRB_PRE_IMM; 9287 // Decode the offset. 9288 unsigned Offset = MI.getOperand(4).getImm(); 9289 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9290 Offset = ARM_AM::getAM2Offset(Offset); 9291 if (isSub) 9292 Offset = -Offset; 9293 9294 MachineMemOperand *MMO = *MI.memoperands_begin(); 9295 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9296 .add(MI.getOperand(0)) // Rn_wb 9297 .add(MI.getOperand(1)) // Rt 9298 .add(MI.getOperand(2)) // Rn 9299 .addImm(Offset) // offset (skip GPR==zero_reg) 9300 .add(MI.getOperand(5)) // pred 9301 .add(MI.getOperand(6)) 9302 .addMemOperand(MMO); 9303 MI.eraseFromParent(); 9304 return BB; 9305 } 9306 case ARM::STRr_preidx: 9307 case ARM::STRBr_preidx: 9308 case ARM::STRH_preidx: { 9309 unsigned NewOpc; 9310 switch (MI.getOpcode()) { 9311 default: llvm_unreachable("unexpected opcode!"); 9312 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9313 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9314 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9315 } 9316 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9317 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9318 MIB.add(MI.getOperand(i)); 9319 MI.eraseFromParent(); 9320 return BB; 9321 } 9322 9323 case ARM::tMOVCCr_pseudo: { 9324 // To "insert" a SELECT_CC instruction, we actually have to insert the 9325 // diamond control-flow pattern. The incoming instruction knows the 9326 // destination vreg to set, the condition code register to branch on, the 9327 // true/false values to select between, and a branch opcode to use. 9328 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9329 MachineFunction::iterator It = ++BB->getIterator(); 9330 9331 // thisMBB: 9332 // ... 9333 // TrueVal = ... 9334 // cmpTY ccX, r1, r2 9335 // bCC copy1MBB 9336 // fallthrough --> copy0MBB 9337 MachineBasicBlock *thisMBB = BB; 9338 MachineFunction *F = BB->getParent(); 9339 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9340 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9341 F->insert(It, copy0MBB); 9342 F->insert(It, sinkMBB); 9343 9344 // Transfer the remainder of BB and its successor edges to sinkMBB. 9345 sinkMBB->splice(sinkMBB->begin(), BB, 9346 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9347 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9348 9349 BB->addSuccessor(copy0MBB); 9350 BB->addSuccessor(sinkMBB); 9351 9352 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9353 .addMBB(sinkMBB) 9354 .addImm(MI.getOperand(3).getImm()) 9355 .addReg(MI.getOperand(4).getReg()); 9356 9357 // copy0MBB: 9358 // %FalseValue = ... 9359 // # fallthrough to sinkMBB 9360 BB = copy0MBB; 9361 9362 // Update machine-CFG edges 9363 BB->addSuccessor(sinkMBB); 9364 9365 // sinkMBB: 9366 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9367 // ... 9368 BB = sinkMBB; 9369 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9370 .addReg(MI.getOperand(1).getReg()) 9371 .addMBB(copy0MBB) 9372 .addReg(MI.getOperand(2).getReg()) 9373 .addMBB(thisMBB); 9374 9375 MI.eraseFromParent(); // The pseudo instruction is gone now. 9376 return BB; 9377 } 9378 9379 case ARM::BCCi64: 9380 case ARM::BCCZi64: { 9381 // If there is an unconditional branch to the other successor, remove it. 9382 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9383 9384 // Compare both parts that make up the double comparison separately for 9385 // equality. 9386 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9387 9388 unsigned LHS1 = MI.getOperand(1).getReg(); 9389 unsigned LHS2 = MI.getOperand(2).getReg(); 9390 if (RHSisZero) { 9391 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9392 .addReg(LHS1) 9393 .addImm(0) 9394 .add(predOps(ARMCC::AL)); 9395 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9396 .addReg(LHS2).addImm(0) 9397 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9398 } else { 9399 unsigned RHS1 = MI.getOperand(3).getReg(); 9400 unsigned RHS2 = MI.getOperand(4).getReg(); 9401 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9402 .addReg(LHS1) 9403 .addReg(RHS1) 9404 .add(predOps(ARMCC::AL)); 9405 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9406 .addReg(LHS2).addReg(RHS2) 9407 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9408 } 9409 9410 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9411 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9412 if (MI.getOperand(0).getImm() == ARMCC::NE) 9413 std::swap(destMBB, exitMBB); 9414 9415 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9416 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9417 if (isThumb2) 9418 BuildMI(BB, dl, TII->get(ARM::t2B)) 9419 .addMBB(exitMBB) 9420 .add(predOps(ARMCC::AL)); 9421 else 9422 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9423 9424 MI.eraseFromParent(); // The pseudo instruction is gone now. 9425 return BB; 9426 } 9427 9428 case ARM::Int_eh_sjlj_setjmp: 9429 case ARM::Int_eh_sjlj_setjmp_nofp: 9430 case ARM::tInt_eh_sjlj_setjmp: 9431 case ARM::t2Int_eh_sjlj_setjmp: 9432 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9433 return BB; 9434 9435 case ARM::Int_eh_sjlj_setup_dispatch: 9436 EmitSjLjDispatchBlock(MI, BB); 9437 return BB; 9438 9439 case ARM::ABS: 9440 case ARM::t2ABS: { 9441 // To insert an ABS instruction, we have to insert the 9442 // diamond control-flow pattern. The incoming instruction knows the 9443 // source vreg to test against 0, the destination vreg to set, 9444 // the condition code register to branch on, the 9445 // true/false values to select between, and a branch opcode to use. 9446 // It transforms 9447 // V1 = ABS V0 9448 // into 9449 // V2 = MOVS V0 9450 // BCC (branch to SinkBB if V0 >= 0) 9451 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9452 // SinkBB: V1 = PHI(V2, V3) 9453 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9454 MachineFunction::iterator BBI = ++BB->getIterator(); 9455 MachineFunction *Fn = BB->getParent(); 9456 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9457 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9458 Fn->insert(BBI, RSBBB); 9459 Fn->insert(BBI, SinkBB); 9460 9461 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9462 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9463 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9464 bool isThumb2 = Subtarget->isThumb2(); 9465 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9466 // In Thumb mode S must not be specified if source register is the SP or 9467 // PC and if destination register is the SP, so restrict register class 9468 unsigned NewRsbDstReg = 9469 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9470 9471 // Transfer the remainder of BB and its successor edges to sinkMBB. 9472 SinkBB->splice(SinkBB->begin(), BB, 9473 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9474 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9475 9476 BB->addSuccessor(RSBBB); 9477 BB->addSuccessor(SinkBB); 9478 9479 // fall through to SinkMBB 9480 RSBBB->addSuccessor(SinkBB); 9481 9482 // insert a cmp at the end of BB 9483 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9484 .addReg(ABSSrcReg) 9485 .addImm(0) 9486 .add(predOps(ARMCC::AL)); 9487 9488 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9489 BuildMI(BB, dl, 9490 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9491 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9492 9493 // insert rsbri in RSBBB 9494 // Note: BCC and rsbri will be converted into predicated rsbmi 9495 // by if-conversion pass 9496 BuildMI(*RSBBB, RSBBB->begin(), dl, 9497 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9498 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9499 .addImm(0) 9500 .add(predOps(ARMCC::AL)) 9501 .add(condCodeOp()); 9502 9503 // insert PHI in SinkBB, 9504 // reuse ABSDstReg to not change uses of ABS instruction 9505 BuildMI(*SinkBB, SinkBB->begin(), dl, 9506 TII->get(ARM::PHI), ABSDstReg) 9507 .addReg(NewRsbDstReg).addMBB(RSBBB) 9508 .addReg(ABSSrcReg).addMBB(BB); 9509 9510 // remove ABS instruction 9511 MI.eraseFromParent(); 9512 9513 // return last added BB 9514 return SinkBB; 9515 } 9516 case ARM::COPY_STRUCT_BYVAL_I32: 9517 ++NumLoopByVals; 9518 return EmitStructByval(MI, BB); 9519 case ARM::WIN__CHKSTK: 9520 return EmitLowered__chkstk(MI, BB); 9521 case ARM::WIN__DBZCHK: 9522 return EmitLowered__dbzchk(MI, BB); 9523 } 9524 } 9525 9526 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 9527 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9528 /// instead of as a custom inserter because we need the use list from the SDNode. 9529 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9530 MachineInstr &MI, const SDNode *Node) { 9531 bool isThumb1 = Subtarget->isThumb1Only(); 9532 9533 DebugLoc DL = MI.getDebugLoc(); 9534 MachineFunction *MF = MI.getParent()->getParent(); 9535 MachineRegisterInfo &MRI = MF->getRegInfo(); 9536 MachineInstrBuilder MIB(*MF, MI); 9537 9538 // If the new dst/src is unused mark it as dead. 9539 if (!Node->hasAnyUseOfValue(0)) { 9540 MI.getOperand(0).setIsDead(true); 9541 } 9542 if (!Node->hasAnyUseOfValue(1)) { 9543 MI.getOperand(1).setIsDead(true); 9544 } 9545 9546 // The MEMCPY both defines and kills the scratch registers. 9547 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9548 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9549 : &ARM::GPRRegClass); 9550 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9551 } 9552 } 9553 9554 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9555 SDNode *Node) const { 9556 if (MI.getOpcode() == ARM::MEMCPY) { 9557 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9558 return; 9559 } 9560 9561 const MCInstrDesc *MCID = &MI.getDesc(); 9562 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9563 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9564 // operand is still set to noreg. If needed, set the optional operand's 9565 // register to CPSR, and remove the redundant implicit def. 9566 // 9567 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 9568 9569 // Rename pseudo opcodes. 9570 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9571 unsigned ccOutIdx; 9572 if (NewOpc) { 9573 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9574 MCID = &TII->get(NewOpc); 9575 9576 assert(MCID->getNumOperands() == 9577 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9578 && "converted opcode should be the same except for cc_out" 9579 " (and, on Thumb1, pred)"); 9580 9581 MI.setDesc(*MCID); 9582 9583 // Add the optional cc_out operand 9584 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9585 9586 // On Thumb1, move all input operands to the end, then add the predicate 9587 if (Subtarget->isThumb1Only()) { 9588 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9589 MI.addOperand(MI.getOperand(1)); 9590 MI.RemoveOperand(1); 9591 } 9592 9593 // Restore the ties 9594 for (unsigned i = MI.getNumOperands(); i--;) { 9595 const MachineOperand& op = MI.getOperand(i); 9596 if (op.isReg() && op.isUse()) { 9597 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9598 if (DefIdx != -1) 9599 MI.tieOperands(DefIdx, i); 9600 } 9601 } 9602 9603 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9604 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9605 ccOutIdx = 1; 9606 } else 9607 ccOutIdx = MCID->getNumOperands() - 1; 9608 } else 9609 ccOutIdx = MCID->getNumOperands() - 1; 9610 9611 // Any ARM instruction that sets the 's' bit should specify an optional 9612 // "cc_out" operand in the last operand position. 9613 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9614 assert(!NewOpc && "Optional cc_out operand required"); 9615 return; 9616 } 9617 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9618 // since we already have an optional CPSR def. 9619 bool definesCPSR = false; 9620 bool deadCPSR = false; 9621 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9622 ++i) { 9623 const MachineOperand &MO = MI.getOperand(i); 9624 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9625 definesCPSR = true; 9626 if (MO.isDead()) 9627 deadCPSR = true; 9628 MI.RemoveOperand(i); 9629 break; 9630 } 9631 } 9632 if (!definesCPSR) { 9633 assert(!NewOpc && "Optional cc_out operand required"); 9634 return; 9635 } 9636 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9637 if (deadCPSR) { 9638 assert(!MI.getOperand(ccOutIdx).getReg() && 9639 "expect uninitialized optional cc_out operand"); 9640 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9641 if (!Subtarget->isThumb1Only()) 9642 return; 9643 } 9644 9645 // If this instruction was defined with an optional CPSR def and its dag node 9646 // had a live implicit CPSR def, then activate the optional CPSR def. 9647 MachineOperand &MO = MI.getOperand(ccOutIdx); 9648 MO.setReg(ARM::CPSR); 9649 MO.setIsDef(true); 9650 } 9651 9652 //===----------------------------------------------------------------------===// 9653 // ARM Optimization Hooks 9654 //===----------------------------------------------------------------------===// 9655 9656 // Helper function that checks if N is a null or all ones constant. 9657 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9658 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9659 } 9660 9661 // Return true if N is conditionally 0 or all ones. 9662 // Detects these expressions where cc is an i1 value: 9663 // 9664 // (select cc 0, y) [AllOnes=0] 9665 // (select cc y, 0) [AllOnes=0] 9666 // (zext cc) [AllOnes=0] 9667 // (sext cc) [AllOnes=0/1] 9668 // (select cc -1, y) [AllOnes=1] 9669 // (select cc y, -1) [AllOnes=1] 9670 // 9671 // Invert is set when N is the null/all ones constant when CC is false. 9672 // OtherOp is set to the alternative value of N. 9673 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9674 SDValue &CC, bool &Invert, 9675 SDValue &OtherOp, 9676 SelectionDAG &DAG) { 9677 switch (N->getOpcode()) { 9678 default: return false; 9679 case ISD::SELECT: { 9680 CC = N->getOperand(0); 9681 SDValue N1 = N->getOperand(1); 9682 SDValue N2 = N->getOperand(2); 9683 if (isZeroOrAllOnes(N1, AllOnes)) { 9684 Invert = false; 9685 OtherOp = N2; 9686 return true; 9687 } 9688 if (isZeroOrAllOnes(N2, AllOnes)) { 9689 Invert = true; 9690 OtherOp = N1; 9691 return true; 9692 } 9693 return false; 9694 } 9695 case ISD::ZERO_EXTEND: 9696 // (zext cc) can never be the all ones value. 9697 if (AllOnes) 9698 return false; 9699 LLVM_FALLTHROUGH; 9700 case ISD::SIGN_EXTEND: { 9701 SDLoc dl(N); 9702 EVT VT = N->getValueType(0); 9703 CC = N->getOperand(0); 9704 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9705 return false; 9706 Invert = !AllOnes; 9707 if (AllOnes) 9708 // When looking for an AllOnes constant, N is an sext, and the 'other' 9709 // value is 0. 9710 OtherOp = DAG.getConstant(0, dl, VT); 9711 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9712 // When looking for a 0 constant, N can be zext or sext. 9713 OtherOp = DAG.getConstant(1, dl, VT); 9714 else 9715 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9716 VT); 9717 return true; 9718 } 9719 } 9720 } 9721 9722 // Combine a constant select operand into its use: 9723 // 9724 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9725 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9726 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9727 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9728 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9729 // 9730 // The transform is rejected if the select doesn't have a constant operand that 9731 // is null, or all ones when AllOnes is set. 9732 // 9733 // Also recognize sext/zext from i1: 9734 // 9735 // (add (zext cc), x) -> (select cc (add x, 1), x) 9736 // (add (sext cc), x) -> (select cc (add x, -1), x) 9737 // 9738 // These transformations eventually create predicated instructions. 9739 // 9740 // @param N The node to transform. 9741 // @param Slct The N operand that is a select. 9742 // @param OtherOp The other N operand (x above). 9743 // @param DCI Context. 9744 // @param AllOnes Require the select constant to be all ones instead of null. 9745 // @returns The new node, or SDValue() on failure. 9746 static 9747 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9748 TargetLowering::DAGCombinerInfo &DCI, 9749 bool AllOnes = false) { 9750 SelectionDAG &DAG = DCI.DAG; 9751 EVT VT = N->getValueType(0); 9752 SDValue NonConstantVal; 9753 SDValue CCOp; 9754 bool SwapSelectOps; 9755 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9756 NonConstantVal, DAG)) 9757 return SDValue(); 9758 9759 // Slct is now know to be the desired identity constant when CC is true. 9760 SDValue TrueVal = OtherOp; 9761 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9762 OtherOp, NonConstantVal); 9763 // Unless SwapSelectOps says CC should be false. 9764 if (SwapSelectOps) 9765 std::swap(TrueVal, FalseVal); 9766 9767 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9768 CCOp, TrueVal, FalseVal); 9769 } 9770 9771 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9772 static 9773 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9774 TargetLowering::DAGCombinerInfo &DCI) { 9775 SDValue N0 = N->getOperand(0); 9776 SDValue N1 = N->getOperand(1); 9777 if (N0.getNode()->hasOneUse()) 9778 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9779 return Result; 9780 if (N1.getNode()->hasOneUse()) 9781 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9782 return Result; 9783 return SDValue(); 9784 } 9785 9786 static bool IsVUZPShuffleNode(SDNode *N) { 9787 // VUZP shuffle node. 9788 if (N->getOpcode() == ARMISD::VUZP) 9789 return true; 9790 9791 // "VUZP" on i32 is an alias for VTRN. 9792 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9793 return true; 9794 9795 return false; 9796 } 9797 9798 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9799 TargetLowering::DAGCombinerInfo &DCI, 9800 const ARMSubtarget *Subtarget) { 9801 // Look for ADD(VUZP.0, VUZP.1). 9802 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9803 N0 == N1) 9804 return SDValue(); 9805 9806 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9807 if (!N->getValueType(0).is64BitVector()) 9808 return SDValue(); 9809 9810 // Generate vpadd. 9811 SelectionDAG &DAG = DCI.DAG; 9812 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9813 SDLoc dl(N); 9814 SDNode *Unzip = N0.getNode(); 9815 EVT VT = N->getValueType(0); 9816 9817 SmallVector<SDValue, 8> Ops; 9818 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9819 TLI.getPointerTy(DAG.getDataLayout()))); 9820 Ops.push_back(Unzip->getOperand(0)); 9821 Ops.push_back(Unzip->getOperand(1)); 9822 9823 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9824 } 9825 9826 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9827 TargetLowering::DAGCombinerInfo &DCI, 9828 const ARMSubtarget *Subtarget) { 9829 // Check for two extended operands. 9830 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9831 N1.getOpcode() == ISD::SIGN_EXTEND) && 9832 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9833 N1.getOpcode() == ISD::ZERO_EXTEND)) 9834 return SDValue(); 9835 9836 SDValue N00 = N0.getOperand(0); 9837 SDValue N10 = N1.getOperand(0); 9838 9839 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9840 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9841 N00 == N10) 9842 return SDValue(); 9843 9844 // We only recognize Q register paddl here; this can't be reached until 9845 // after type legalization. 9846 if (!N00.getValueType().is64BitVector() || 9847 !N0.getValueType().is128BitVector()) 9848 return SDValue(); 9849 9850 // Generate vpaddl. 9851 SelectionDAG &DAG = DCI.DAG; 9852 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9853 SDLoc dl(N); 9854 EVT VT = N->getValueType(0); 9855 9856 SmallVector<SDValue, 8> Ops; 9857 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9858 unsigned Opcode; 9859 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9860 Opcode = Intrinsic::arm_neon_vpaddls; 9861 else 9862 Opcode = Intrinsic::arm_neon_vpaddlu; 9863 Ops.push_back(DAG.getConstant(Opcode, dl, 9864 TLI.getPointerTy(DAG.getDataLayout()))); 9865 EVT ElemTy = N00.getValueType().getVectorElementType(); 9866 unsigned NumElts = VT.getVectorNumElements(); 9867 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9868 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9869 N00.getOperand(0), N00.getOperand(1)); 9870 Ops.push_back(Concat); 9871 9872 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9873 } 9874 9875 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9876 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9877 // much easier to match. 9878 static SDValue 9879 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9880 TargetLowering::DAGCombinerInfo &DCI, 9881 const ARMSubtarget *Subtarget) { 9882 // Only perform optimization if after legalize, and if NEON is available. We 9883 // also expected both operands to be BUILD_VECTORs. 9884 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9885 || N0.getOpcode() != ISD::BUILD_VECTOR 9886 || N1.getOpcode() != ISD::BUILD_VECTOR) 9887 return SDValue(); 9888 9889 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9890 EVT VT = N->getValueType(0); 9891 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9892 return SDValue(); 9893 9894 // Check that the vector operands are of the right form. 9895 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9896 // operands, where N is the size of the formed vector. 9897 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9898 // index such that we have a pair wise add pattern. 9899 9900 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9901 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9902 return SDValue(); 9903 SDValue Vec = N0->getOperand(0)->getOperand(0); 9904 SDNode *V = Vec.getNode(); 9905 unsigned nextIndex = 0; 9906 9907 // For each operands to the ADD which are BUILD_VECTORs, 9908 // check to see if each of their operands are an EXTRACT_VECTOR with 9909 // the same vector and appropriate index. 9910 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9911 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9912 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9913 9914 SDValue ExtVec0 = N0->getOperand(i); 9915 SDValue ExtVec1 = N1->getOperand(i); 9916 9917 // First operand is the vector, verify its the same. 9918 if (V != ExtVec0->getOperand(0).getNode() || 9919 V != ExtVec1->getOperand(0).getNode()) 9920 return SDValue(); 9921 9922 // Second is the constant, verify its correct. 9923 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9924 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9925 9926 // For the constant, we want to see all the even or all the odd. 9927 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9928 || C1->getZExtValue() != nextIndex+1) 9929 return SDValue(); 9930 9931 // Increment index. 9932 nextIndex+=2; 9933 } else 9934 return SDValue(); 9935 } 9936 9937 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 9938 // we're using the entire input vector, otherwise there's a size/legality 9939 // mismatch somewhere. 9940 if (nextIndex != Vec.getValueType().getVectorNumElements() || 9941 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9942 return SDValue(); 9943 9944 // Create VPADDL node. 9945 SelectionDAG &DAG = DCI.DAG; 9946 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9947 9948 SDLoc dl(N); 9949 9950 // Build operand list. 9951 SmallVector<SDValue, 8> Ops; 9952 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9953 TLI.getPointerTy(DAG.getDataLayout()))); 9954 9955 // Input is the vector. 9956 Ops.push_back(Vec); 9957 9958 // Get widened type and narrowed type. 9959 MVT widenType; 9960 unsigned numElem = VT.getVectorNumElements(); 9961 9962 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9963 switch (inputLaneType.getSimpleVT().SimpleTy) { 9964 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9965 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9966 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9967 default: 9968 llvm_unreachable("Invalid vector element type for padd optimization."); 9969 } 9970 9971 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9972 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9973 return DAG.getNode(ExtOp, dl, VT, tmp); 9974 } 9975 9976 static SDValue findMUL_LOHI(SDValue V) { 9977 if (V->getOpcode() == ISD::UMUL_LOHI || 9978 V->getOpcode() == ISD::SMUL_LOHI) 9979 return V; 9980 return SDValue(); 9981 } 9982 9983 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 9984 TargetLowering::DAGCombinerInfo &DCI, 9985 const ARMSubtarget *Subtarget) { 9986 if (Subtarget->isThumb()) { 9987 if (!Subtarget->hasDSP()) 9988 return SDValue(); 9989 } else if (!Subtarget->hasV5TEOps()) 9990 return SDValue(); 9991 9992 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 9993 // accumulates the product into a 64-bit value. The 16-bit values will 9994 // be sign extended somehow or SRA'd into 32-bit values 9995 // (addc (adde (mul 16bit, 16bit), lo), hi) 9996 SDValue Mul = AddcNode->getOperand(0); 9997 SDValue Lo = AddcNode->getOperand(1); 9998 if (Mul.getOpcode() != ISD::MUL) { 9999 Lo = AddcNode->getOperand(0); 10000 Mul = AddcNode->getOperand(1); 10001 if (Mul.getOpcode() != ISD::MUL) 10002 return SDValue(); 10003 } 10004 10005 SDValue SRA = AddeNode->getOperand(0); 10006 SDValue Hi = AddeNode->getOperand(1); 10007 if (SRA.getOpcode() != ISD::SRA) { 10008 SRA = AddeNode->getOperand(1); 10009 Hi = AddeNode->getOperand(0); 10010 if (SRA.getOpcode() != ISD::SRA) 10011 return SDValue(); 10012 } 10013 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 10014 if (Const->getZExtValue() != 31) 10015 return SDValue(); 10016 } else 10017 return SDValue(); 10018 10019 if (SRA.getOperand(0) != Mul) 10020 return SDValue(); 10021 10022 SelectionDAG &DAG = DCI.DAG; 10023 SDLoc dl(AddcNode); 10024 unsigned Opcode = 0; 10025 SDValue Op0; 10026 SDValue Op1; 10027 10028 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 10029 Opcode = ARMISD::SMLALBB; 10030 Op0 = Mul.getOperand(0); 10031 Op1 = Mul.getOperand(1); 10032 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 10033 Opcode = ARMISD::SMLALBT; 10034 Op0 = Mul.getOperand(0); 10035 Op1 = Mul.getOperand(1).getOperand(0); 10036 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10037 Opcode = ARMISD::SMLALTB; 10038 Op0 = Mul.getOperand(0).getOperand(0); 10039 Op1 = Mul.getOperand(1); 10040 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10041 Opcode = ARMISD::SMLALTT; 10042 Op0 = Mul->getOperand(0).getOperand(0); 10043 Op1 = Mul->getOperand(1).getOperand(0); 10044 } 10045 10046 if (!Op0 || !Op1) 10047 return SDValue(); 10048 10049 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10050 Op0, Op1, Lo, Hi); 10051 // Replace the ADDs' nodes uses by the MLA node's values. 10052 SDValue HiMLALResult(SMLAL.getNode(), 1); 10053 SDValue LoMLALResult(SMLAL.getNode(), 0); 10054 10055 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10056 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10057 10058 // Return original node to notify the driver to stop replacing. 10059 SDValue resNode(AddcNode, 0); 10060 return resNode; 10061 } 10062 10063 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10064 TargetLowering::DAGCombinerInfo &DCI, 10065 const ARMSubtarget *Subtarget) { 10066 // Look for multiply add opportunities. 10067 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10068 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10069 // a glue link from the first add to the second add. 10070 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10071 // a S/UMLAL instruction. 10072 // UMUL_LOHI 10073 // / :lo \ :hi 10074 // V \ [no multiline comment] 10075 // loAdd -> ADDC | 10076 // \ :carry / 10077 // V V 10078 // ADDE <- hiAdd 10079 // 10080 // In the special case where only the higher part of a signed result is used 10081 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10082 // a constant with the exact value of 0x80000000, we recognize we are dealing 10083 // with a "rounded multiply and add" (or subtract) and transform it into 10084 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10085 10086 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10087 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10088 "Expect an ADDE or SUBE"); 10089 10090 assert(AddeSubeNode->getNumOperands() == 3 && 10091 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10092 "ADDE node has the wrong inputs"); 10093 10094 // Check that we are chained to the right ADDC or SUBC node. 10095 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10096 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10097 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10098 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10099 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10100 return SDValue(); 10101 10102 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10103 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10104 10105 // Check if the two operands are from the same mul_lohi node. 10106 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10107 return SDValue(); 10108 10109 assert(AddcSubcNode->getNumValues() == 2 && 10110 AddcSubcNode->getValueType(0) == MVT::i32 && 10111 "Expect ADDC with two result values. First: i32"); 10112 10113 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10114 // maybe a SMLAL which multiplies two 16-bit values. 10115 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10116 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10117 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10118 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10119 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10120 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10121 10122 // Check for the triangle shape. 10123 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10124 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10125 10126 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10127 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10128 return SDValue(); 10129 10130 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10131 bool IsLeftOperandMUL = false; 10132 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10133 if (MULOp == SDValue()) 10134 MULOp = findMUL_LOHI(AddeSubeOp1); 10135 else 10136 IsLeftOperandMUL = true; 10137 if (MULOp == SDValue()) 10138 return SDValue(); 10139 10140 // Figure out the right opcode. 10141 unsigned Opc = MULOp->getOpcode(); 10142 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 10143 10144 // Figure out the high and low input values to the MLAL node. 10145 SDValue *HiAddSub = nullptr; 10146 SDValue *LoMul = nullptr; 10147 SDValue *LowAddSub = nullptr; 10148 10149 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 10150 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 10151 return SDValue(); 10152 10153 if (IsLeftOperandMUL) 10154 HiAddSub = &AddeSubeOp1; 10155 else 10156 HiAddSub = &AddeSubeOp0; 10157 10158 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 10159 // whose low result is fed to the ADDC/SUBC we are checking. 10160 10161 if (AddcSubcOp0 == MULOp.getValue(0)) { 10162 LoMul = &AddcSubcOp0; 10163 LowAddSub = &AddcSubcOp1; 10164 } 10165 if (AddcSubcOp1 == MULOp.getValue(0)) { 10166 LoMul = &AddcSubcOp1; 10167 LowAddSub = &AddcSubcOp0; 10168 } 10169 10170 if (!LoMul) 10171 return SDValue(); 10172 10173 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 10174 // the replacement below will create a cycle. 10175 if (AddcSubcNode == HiAddSub->getNode() || 10176 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 10177 return SDValue(); 10178 10179 // Create the merged node. 10180 SelectionDAG &DAG = DCI.DAG; 10181 10182 // Start building operand list. 10183 SmallVector<SDValue, 8> Ops; 10184 Ops.push_back(LoMul->getOperand(0)); 10185 Ops.push_back(LoMul->getOperand(1)); 10186 10187 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 10188 // the case, we must be doing signed multiplication and only use the higher 10189 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 10190 // addition or subtraction with the value of 0x800000. 10191 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 10192 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 10193 LowAddSub->getNode()->getOpcode() == ISD::Constant && 10194 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 10195 0x80000000) { 10196 Ops.push_back(*HiAddSub); 10197 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 10198 FinalOpc = ARMISD::SMMLSR; 10199 } else { 10200 FinalOpc = ARMISD::SMMLAR; 10201 } 10202 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 10203 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 10204 10205 return SDValue(AddeSubeNode, 0); 10206 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 10207 // SMMLS is generated during instruction selection and the rest of this 10208 // function can not handle the case where AddcSubcNode is a SUBC. 10209 return SDValue(); 10210 10211 // Finish building the operand list for {U/S}MLAL 10212 Ops.push_back(*LowAddSub); 10213 Ops.push_back(*HiAddSub); 10214 10215 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 10216 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10217 10218 // Replace the ADDs' nodes uses by the MLA node's values. 10219 SDValue HiMLALResult(MLALNode.getNode(), 1); 10220 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 10221 10222 SDValue LoMLALResult(MLALNode.getNode(), 0); 10223 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 10224 10225 // Return original node to notify the driver to stop replacing. 10226 return SDValue(AddeSubeNode, 0); 10227 } 10228 10229 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 10230 TargetLowering::DAGCombinerInfo &DCI, 10231 const ARMSubtarget *Subtarget) { 10232 // UMAAL is similar to UMLAL except that it adds two unsigned values. 10233 // While trying to combine for the other MLAL nodes, first search for the 10234 // chance to use UMAAL. Check if Addc uses a node which has already 10235 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 10236 // as the addend, and it's handled in PerformUMLALCombine. 10237 10238 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10239 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10240 10241 // Check that we have a glued ADDC node. 10242 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 10243 if (AddcNode->getOpcode() != ARMISD::ADDC) 10244 return SDValue(); 10245 10246 // Find the converted UMAAL or quit if it doesn't exist. 10247 SDNode *UmlalNode = nullptr; 10248 SDValue AddHi; 10249 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 10250 UmlalNode = AddcNode->getOperand(0).getNode(); 10251 AddHi = AddcNode->getOperand(1); 10252 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 10253 UmlalNode = AddcNode->getOperand(1).getNode(); 10254 AddHi = AddcNode->getOperand(0); 10255 } else { 10256 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10257 } 10258 10259 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 10260 // the ADDC as well as Zero. 10261 if (!isNullConstant(UmlalNode->getOperand(3))) 10262 return SDValue(); 10263 10264 if ((isNullConstant(AddeNode->getOperand(0)) && 10265 AddeNode->getOperand(1).getNode() == UmlalNode) || 10266 (AddeNode->getOperand(0).getNode() == UmlalNode && 10267 isNullConstant(AddeNode->getOperand(1)))) { 10268 SelectionDAG &DAG = DCI.DAG; 10269 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 10270 UmlalNode->getOperand(2), AddHi }; 10271 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 10272 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10273 10274 // Replace the ADDs' nodes uses by the UMAAL node's values. 10275 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 10276 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 10277 10278 // Return original node to notify the driver to stop replacing. 10279 return SDValue(AddeNode, 0); 10280 } 10281 return SDValue(); 10282 } 10283 10284 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 10285 const ARMSubtarget *Subtarget) { 10286 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10287 return SDValue(); 10288 10289 // Check that we have a pair of ADDC and ADDE as operands. 10290 // Both addends of the ADDE must be zero. 10291 SDNode* AddcNode = N->getOperand(2).getNode(); 10292 SDNode* AddeNode = N->getOperand(3).getNode(); 10293 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 10294 (AddeNode->getOpcode() == ARMISD::ADDE) && 10295 isNullConstant(AddeNode->getOperand(0)) && 10296 isNullConstant(AddeNode->getOperand(1)) && 10297 (AddeNode->getOperand(2).getNode() == AddcNode)) 10298 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 10299 DAG.getVTList(MVT::i32, MVT::i32), 10300 {N->getOperand(0), N->getOperand(1), 10301 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 10302 else 10303 return SDValue(); 10304 } 10305 10306 static SDValue PerformAddcSubcCombine(SDNode *N, 10307 TargetLowering::DAGCombinerInfo &DCI, 10308 const ARMSubtarget *Subtarget) { 10309 SelectionDAG &DAG(DCI.DAG); 10310 10311 if (N->getOpcode() == ARMISD::SUBC) { 10312 // (SUBC (ADDE 0, 0, C), 1) -> C 10313 SDValue LHS = N->getOperand(0); 10314 SDValue RHS = N->getOperand(1); 10315 if (LHS->getOpcode() == ARMISD::ADDE && 10316 isNullConstant(LHS->getOperand(0)) && 10317 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 10318 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10319 } 10320 } 10321 10322 if (Subtarget->isThumb1Only()) { 10323 SDValue RHS = N->getOperand(1); 10324 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10325 int32_t imm = C->getSExtValue(); 10326 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10327 SDLoc DL(N); 10328 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10329 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10330 : ARMISD::ADDC; 10331 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10332 } 10333 } 10334 } 10335 return SDValue(); 10336 } 10337 10338 static SDValue PerformAddeSubeCombine(SDNode *N, 10339 TargetLowering::DAGCombinerInfo &DCI, 10340 const ARMSubtarget *Subtarget) { 10341 if (Subtarget->isThumb1Only()) { 10342 SelectionDAG &DAG = DCI.DAG; 10343 SDValue RHS = N->getOperand(1); 10344 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10345 int64_t imm = C->getSExtValue(); 10346 if (imm < 0) { 10347 SDLoc DL(N); 10348 10349 // The with-carry-in form matches bitwise not instead of the negation. 10350 // Effectively, the inverse interpretation of the carry flag already 10351 // accounts for part of the negation. 10352 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10353 10354 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10355 : ARMISD::ADDE; 10356 return DAG.getNode(Opcode, DL, N->getVTList(), 10357 N->getOperand(0), RHS, N->getOperand(2)); 10358 } 10359 } 10360 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 10361 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 10362 } 10363 return SDValue(); 10364 } 10365 10366 /// PerformADDECombine - Target-specific dag combine transform from 10367 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10368 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10369 static SDValue PerformADDECombine(SDNode *N, 10370 TargetLowering::DAGCombinerInfo &DCI, 10371 const ARMSubtarget *Subtarget) { 10372 // Only ARM and Thumb2 support UMLAL/SMLAL. 10373 if (Subtarget->isThumb1Only()) 10374 return PerformAddeSubeCombine(N, DCI, Subtarget); 10375 10376 // Only perform the checks after legalize when the pattern is available. 10377 if (DCI.isBeforeLegalize()) return SDValue(); 10378 10379 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10380 } 10381 10382 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10383 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10384 /// called with the default operands, and if that fails, with commuted 10385 /// operands. 10386 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10387 TargetLowering::DAGCombinerInfo &DCI, 10388 const ARMSubtarget *Subtarget){ 10389 // Attempt to create vpadd for this add. 10390 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10391 return Result; 10392 10393 // Attempt to create vpaddl for this add. 10394 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10395 return Result; 10396 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10397 Subtarget)) 10398 return Result; 10399 10400 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10401 if (N0.getNode()->hasOneUse()) 10402 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10403 return Result; 10404 return SDValue(); 10405 } 10406 10407 static SDValue PerformSHLSimplify(SDNode *N, 10408 TargetLowering::DAGCombinerInfo &DCI, 10409 const ARMSubtarget *ST) { 10410 // Allow the generic combiner to identify potential bswaps. 10411 if (DCI.isBeforeLegalize()) 10412 return SDValue(); 10413 10414 // DAG combiner will fold: 10415 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10416 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 10417 // Other code patterns that can be also be modified have the following form: 10418 // b + ((a << 1) | 510) 10419 // b + ((a << 1) & 510) 10420 // b + ((a << 1) ^ 510) 10421 // b + ((a << 1) + 510) 10422 10423 // Many instructions can perform the shift for free, but it requires both 10424 // the operands to be registers. If c1 << c2 is too large, a mov immediate 10425 // instruction will needed. So, unfold back to the original pattern if: 10426 // - if c1 and c2 are small enough that they don't require mov imms. 10427 // - the user(s) of the node can perform an shl 10428 10429 // No shifted operands for 16-bit instructions. 10430 if (ST->isThumb() && ST->isThumb1Only()) 10431 return SDValue(); 10432 10433 // Check that all the users could perform the shl themselves. 10434 for (auto U : N->uses()) { 10435 switch(U->getOpcode()) { 10436 default: 10437 return SDValue(); 10438 case ISD::SUB: 10439 case ISD::ADD: 10440 case ISD::AND: 10441 case ISD::OR: 10442 case ISD::XOR: 10443 case ISD::SETCC: 10444 case ARMISD::CMP: 10445 // Check that its not already using a shl. 10446 if (U->getOperand(0).getOpcode() == ISD::SHL || 10447 U->getOperand(1).getOpcode() == ISD::SHL) 10448 return SDValue(); 10449 break; 10450 } 10451 } 10452 10453 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 10454 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 10455 return SDValue(); 10456 10457 if (N->getOperand(0).getOpcode() != ISD::SHL) 10458 return SDValue(); 10459 10460 SDValue SHL = N->getOperand(0); 10461 10462 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10463 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 10464 if (!C1ShlC2 || !C2) 10465 return SDValue(); 10466 10467 DEBUG(dbgs() << "Trying to simplify shl: "; N->dump()); 10468 10469 APInt C2Int = C2->getAPIntValue(); 10470 APInt C1Int = C1ShlC2->getAPIntValue(); 10471 10472 // Check that performing a lshr will not lose any information. 10473 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 10474 C2Int.getBitWidth() - C2->getZExtValue()); 10475 if ((C1Int & Mask) != C1Int) 10476 return SDValue(); 10477 10478 // Shift the first constant. 10479 C1Int.lshrInPlace(C2Int); 10480 10481 // The immediates are encoded as an 8-bit value that can be rotated. 10482 unsigned Zeros = C1Int.countLeadingZeros() + C1Int.countTrailingZeros(); 10483 if (C1Int.getBitWidth() - Zeros > 8) 10484 return SDValue(); 10485 10486 Zeros = C2Int.countLeadingZeros() + C2Int.countTrailingZeros(); 10487 if (C2Int.getBitWidth() - Zeros > 8) 10488 return SDValue(); 10489 10490 SelectionDAG &DAG = DCI.DAG; 10491 SDLoc dl(N); 10492 SDValue X = SHL.getOperand(0); 10493 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 10494 DAG.getConstant(C1Int, dl, MVT::i32)); 10495 // Shift left to compensate for the lshr of C1Int. 10496 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 10497 10498 DAG.ReplaceAllUsesWith(SDValue(N, 0), Res); 10499 return SDValue(N, 0); 10500 } 10501 10502 10503 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10504 /// 10505 static SDValue PerformADDCombine(SDNode *N, 10506 TargetLowering::DAGCombinerInfo &DCI, 10507 const ARMSubtarget *Subtarget) { 10508 SDValue N0 = N->getOperand(0); 10509 SDValue N1 = N->getOperand(1); 10510 10511 // Only works one way, because it needs an immediate operand. 10512 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10513 return Result; 10514 10515 // First try with the default operand order. 10516 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10517 return Result; 10518 10519 // If that didn't work, try again with the operands commuted. 10520 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10521 } 10522 10523 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 10524 /// 10525 static SDValue PerformSUBCombine(SDNode *N, 10526 TargetLowering::DAGCombinerInfo &DCI) { 10527 SDValue N0 = N->getOperand(0); 10528 SDValue N1 = N->getOperand(1); 10529 10530 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10531 if (N1.getNode()->hasOneUse()) 10532 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 10533 return Result; 10534 10535 return SDValue(); 10536 } 10537 10538 /// PerformVMULCombine 10539 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 10540 /// special multiplier accumulator forwarding. 10541 /// vmul d3, d0, d2 10542 /// vmla d3, d1, d2 10543 /// is faster than 10544 /// vadd d3, d0, d1 10545 /// vmul d3, d3, d2 10546 // However, for (A + B) * (A + B), 10547 // vadd d2, d0, d1 10548 // vmul d3, d0, d2 10549 // vmla d3, d1, d2 10550 // is slower than 10551 // vadd d2, d0, d1 10552 // vmul d3, d2, d2 10553 static SDValue PerformVMULCombine(SDNode *N, 10554 TargetLowering::DAGCombinerInfo &DCI, 10555 const ARMSubtarget *Subtarget) { 10556 if (!Subtarget->hasVMLxForwarding()) 10557 return SDValue(); 10558 10559 SelectionDAG &DAG = DCI.DAG; 10560 SDValue N0 = N->getOperand(0); 10561 SDValue N1 = N->getOperand(1); 10562 unsigned Opcode = N0.getOpcode(); 10563 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10564 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10565 Opcode = N1.getOpcode(); 10566 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10567 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10568 return SDValue(); 10569 std::swap(N0, N1); 10570 } 10571 10572 if (N0 == N1) 10573 return SDValue(); 10574 10575 EVT VT = N->getValueType(0); 10576 SDLoc DL(N); 10577 SDValue N00 = N0->getOperand(0); 10578 SDValue N01 = N0->getOperand(1); 10579 return DAG.getNode(Opcode, DL, VT, 10580 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10581 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10582 } 10583 10584 static SDValue PerformMULCombine(SDNode *N, 10585 TargetLowering::DAGCombinerInfo &DCI, 10586 const ARMSubtarget *Subtarget) { 10587 SelectionDAG &DAG = DCI.DAG; 10588 10589 if (Subtarget->isThumb1Only()) 10590 return SDValue(); 10591 10592 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10593 return SDValue(); 10594 10595 EVT VT = N->getValueType(0); 10596 if (VT.is64BitVector() || VT.is128BitVector()) 10597 return PerformVMULCombine(N, DCI, Subtarget); 10598 if (VT != MVT::i32) 10599 return SDValue(); 10600 10601 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10602 if (!C) 10603 return SDValue(); 10604 10605 int64_t MulAmt = C->getSExtValue(); 10606 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10607 10608 ShiftAmt = ShiftAmt & (32 - 1); 10609 SDValue V = N->getOperand(0); 10610 SDLoc DL(N); 10611 10612 SDValue Res; 10613 MulAmt >>= ShiftAmt; 10614 10615 if (MulAmt >= 0) { 10616 if (isPowerOf2_32(MulAmt - 1)) { 10617 // (mul x, 2^N + 1) => (add (shl x, N), x) 10618 Res = DAG.getNode(ISD::ADD, DL, VT, 10619 V, 10620 DAG.getNode(ISD::SHL, DL, VT, 10621 V, 10622 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10623 MVT::i32))); 10624 } else if (isPowerOf2_32(MulAmt + 1)) { 10625 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10626 Res = DAG.getNode(ISD::SUB, DL, VT, 10627 DAG.getNode(ISD::SHL, DL, VT, 10628 V, 10629 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10630 MVT::i32)), 10631 V); 10632 } else 10633 return SDValue(); 10634 } else { 10635 uint64_t MulAmtAbs = -MulAmt; 10636 if (isPowerOf2_32(MulAmtAbs + 1)) { 10637 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10638 Res = DAG.getNode(ISD::SUB, DL, VT, 10639 V, 10640 DAG.getNode(ISD::SHL, DL, VT, 10641 V, 10642 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10643 MVT::i32))); 10644 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10645 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10646 Res = DAG.getNode(ISD::ADD, DL, VT, 10647 V, 10648 DAG.getNode(ISD::SHL, DL, VT, 10649 V, 10650 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10651 MVT::i32))); 10652 Res = DAG.getNode(ISD::SUB, DL, VT, 10653 DAG.getConstant(0, DL, MVT::i32), Res); 10654 } else 10655 return SDValue(); 10656 } 10657 10658 if (ShiftAmt != 0) 10659 Res = DAG.getNode(ISD::SHL, DL, VT, 10660 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10661 10662 // Do not add new nodes to DAG combiner worklist. 10663 DCI.CombineTo(N, Res, false); 10664 return SDValue(); 10665 } 10666 10667 static SDValue PerformANDCombine(SDNode *N, 10668 TargetLowering::DAGCombinerInfo &DCI, 10669 const ARMSubtarget *Subtarget) { 10670 // Attempt to use immediate-form VBIC 10671 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10672 SDLoc dl(N); 10673 EVT VT = N->getValueType(0); 10674 SelectionDAG &DAG = DCI.DAG; 10675 10676 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10677 return SDValue(); 10678 10679 APInt SplatBits, SplatUndef; 10680 unsigned SplatBitSize; 10681 bool HasAnyUndefs; 10682 if (BVN && 10683 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10684 if (SplatBitSize <= 64) { 10685 EVT VbicVT; 10686 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10687 SplatUndef.getZExtValue(), SplatBitSize, 10688 DAG, dl, VbicVT, VT.is128BitVector(), 10689 OtherModImm); 10690 if (Val.getNode()) { 10691 SDValue Input = 10692 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10693 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10694 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10695 } 10696 } 10697 } 10698 10699 if (!Subtarget->isThumb1Only()) { 10700 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10701 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10702 return Result; 10703 10704 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10705 return Result; 10706 } 10707 10708 return SDValue(); 10709 } 10710 10711 // Try combining OR nodes to SMULWB, SMULWT. 10712 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10713 TargetLowering::DAGCombinerInfo &DCI, 10714 const ARMSubtarget *Subtarget) { 10715 if (!Subtarget->hasV6Ops() || 10716 (Subtarget->isThumb() && 10717 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10718 return SDValue(); 10719 10720 SDValue SRL = OR->getOperand(0); 10721 SDValue SHL = OR->getOperand(1); 10722 10723 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10724 SRL = OR->getOperand(1); 10725 SHL = OR->getOperand(0); 10726 } 10727 if (!isSRL16(SRL) || !isSHL16(SHL)) 10728 return SDValue(); 10729 10730 // The first operands to the shifts need to be the two results from the 10731 // same smul_lohi node. 10732 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10733 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10734 return SDValue(); 10735 10736 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10737 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10738 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10739 return SDValue(); 10740 10741 // Now we have: 10742 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10743 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10744 // For SMUWB the 16-bit value will signed extended somehow. 10745 // For SMULWT only the SRA is required. 10746 // Check both sides of SMUL_LOHI 10747 SDValue OpS16 = SMULLOHI->getOperand(0); 10748 SDValue OpS32 = SMULLOHI->getOperand(1); 10749 10750 SelectionDAG &DAG = DCI.DAG; 10751 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10752 OpS16 = OpS32; 10753 OpS32 = SMULLOHI->getOperand(0); 10754 } 10755 10756 SDLoc dl(OR); 10757 unsigned Opcode = 0; 10758 if (isS16(OpS16, DAG)) 10759 Opcode = ARMISD::SMULWB; 10760 else if (isSRA16(OpS16)) { 10761 Opcode = ARMISD::SMULWT; 10762 OpS16 = OpS16->getOperand(0); 10763 } 10764 else 10765 return SDValue(); 10766 10767 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10768 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10769 return SDValue(OR, 0); 10770 } 10771 10772 static SDValue PerformORCombineToBFI(SDNode *N, 10773 TargetLowering::DAGCombinerInfo &DCI, 10774 const ARMSubtarget *Subtarget) { 10775 // BFI is only available on V6T2+ 10776 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10777 return SDValue(); 10778 10779 EVT VT = N->getValueType(0); 10780 SDValue N0 = N->getOperand(0); 10781 SDValue N1 = N->getOperand(1); 10782 SelectionDAG &DAG = DCI.DAG; 10783 SDLoc DL(N); 10784 // 1) or (and A, mask), val => ARMbfi A, val, mask 10785 // iff (val & mask) == val 10786 // 10787 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10788 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10789 // && mask == ~mask2 10790 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10791 // && ~mask == mask2 10792 // (i.e., copy a bitfield value into another bitfield of the same width) 10793 10794 if (VT != MVT::i32) 10795 return SDValue(); 10796 10797 SDValue N00 = N0.getOperand(0); 10798 10799 // The value and the mask need to be constants so we can verify this is 10800 // actually a bitfield set. If the mask is 0xffff, we can do better 10801 // via a movt instruction, so don't use BFI in that case. 10802 SDValue MaskOp = N0.getOperand(1); 10803 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10804 if (!MaskC) 10805 return SDValue(); 10806 unsigned Mask = MaskC->getZExtValue(); 10807 if (Mask == 0xffff) 10808 return SDValue(); 10809 SDValue Res; 10810 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10811 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10812 if (N1C) { 10813 unsigned Val = N1C->getZExtValue(); 10814 if ((Val & ~Mask) != Val) 10815 return SDValue(); 10816 10817 if (ARM::isBitFieldInvertedMask(Mask)) { 10818 Val >>= countTrailingZeros(~Mask); 10819 10820 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10821 DAG.getConstant(Val, DL, MVT::i32), 10822 DAG.getConstant(Mask, DL, MVT::i32)); 10823 10824 DCI.CombineTo(N, Res, false); 10825 // Return value from the original node to inform the combiner than N is 10826 // now dead. 10827 return SDValue(N, 0); 10828 } 10829 } else if (N1.getOpcode() == ISD::AND) { 10830 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10831 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10832 if (!N11C) 10833 return SDValue(); 10834 unsigned Mask2 = N11C->getZExtValue(); 10835 10836 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10837 // as is to match. 10838 if (ARM::isBitFieldInvertedMask(Mask) && 10839 (Mask == ~Mask2)) { 10840 // The pack halfword instruction works better for masks that fit it, 10841 // so use that when it's available. 10842 if (Subtarget->hasDSP() && 10843 (Mask == 0xffff || Mask == 0xffff0000)) 10844 return SDValue(); 10845 // 2a 10846 unsigned amt = countTrailingZeros(Mask2); 10847 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10848 DAG.getConstant(amt, DL, MVT::i32)); 10849 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10850 DAG.getConstant(Mask, DL, MVT::i32)); 10851 DCI.CombineTo(N, Res, false); 10852 // Return value from the original node to inform the combiner than N is 10853 // now dead. 10854 return SDValue(N, 0); 10855 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10856 (~Mask == Mask2)) { 10857 // The pack halfword instruction works better for masks that fit it, 10858 // so use that when it's available. 10859 if (Subtarget->hasDSP() && 10860 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10861 return SDValue(); 10862 // 2b 10863 unsigned lsb = countTrailingZeros(Mask); 10864 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10865 DAG.getConstant(lsb, DL, MVT::i32)); 10866 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10867 DAG.getConstant(Mask2, DL, MVT::i32)); 10868 DCI.CombineTo(N, Res, false); 10869 // Return value from the original node to inform the combiner than N is 10870 // now dead. 10871 return SDValue(N, 0); 10872 } 10873 } 10874 10875 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10876 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10877 ARM::isBitFieldInvertedMask(~Mask)) { 10878 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10879 // where lsb(mask) == #shamt and masked bits of B are known zero. 10880 SDValue ShAmt = N00.getOperand(1); 10881 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10882 unsigned LSB = countTrailingZeros(Mask); 10883 if (ShAmtC != LSB) 10884 return SDValue(); 10885 10886 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10887 DAG.getConstant(~Mask, DL, MVT::i32)); 10888 10889 DCI.CombineTo(N, Res, false); 10890 // Return value from the original node to inform the combiner than N is 10891 // now dead. 10892 return SDValue(N, 0); 10893 } 10894 10895 return SDValue(); 10896 } 10897 10898 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 10899 static SDValue PerformORCombine(SDNode *N, 10900 TargetLowering::DAGCombinerInfo &DCI, 10901 const ARMSubtarget *Subtarget) { 10902 // Attempt to use immediate-form VORR 10903 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10904 SDLoc dl(N); 10905 EVT VT = N->getValueType(0); 10906 SelectionDAG &DAG = DCI.DAG; 10907 10908 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10909 return SDValue(); 10910 10911 APInt SplatBits, SplatUndef; 10912 unsigned SplatBitSize; 10913 bool HasAnyUndefs; 10914 if (BVN && Subtarget->hasNEON() && 10915 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10916 if (SplatBitSize <= 64) { 10917 EVT VorrVT; 10918 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 10919 SplatUndef.getZExtValue(), SplatBitSize, 10920 DAG, dl, VorrVT, VT.is128BitVector(), 10921 OtherModImm); 10922 if (Val.getNode()) { 10923 SDValue Input = 10924 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 10925 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 10926 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 10927 } 10928 } 10929 } 10930 10931 if (!Subtarget->isThumb1Only()) { 10932 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10933 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10934 return Result; 10935 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 10936 return Result; 10937 } 10938 10939 SDValue N0 = N->getOperand(0); 10940 SDValue N1 = N->getOperand(1); 10941 10942 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 10943 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 10944 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10945 10946 // The code below optimizes (or (and X, Y), Z). 10947 // The AND operand needs to have a single user to make these optimizations 10948 // profitable. 10949 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 10950 return SDValue(); 10951 10952 APInt SplatUndef; 10953 unsigned SplatBitSize; 10954 bool HasAnyUndefs; 10955 10956 APInt SplatBits0, SplatBits1; 10957 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 10958 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 10959 // Ensure that the second operand of both ands are constants 10960 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 10961 HasAnyUndefs) && !HasAnyUndefs) { 10962 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 10963 HasAnyUndefs) && !HasAnyUndefs) { 10964 // Ensure that the bit width of the constants are the same and that 10965 // the splat arguments are logical inverses as per the pattern we 10966 // are trying to simplify. 10967 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 10968 SplatBits0 == ~SplatBits1) { 10969 // Canonicalize the vector type to make instruction selection 10970 // simpler. 10971 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 10972 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 10973 N0->getOperand(1), 10974 N0->getOperand(0), 10975 N1->getOperand(0)); 10976 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 10977 } 10978 } 10979 } 10980 } 10981 10982 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 10983 // reasonable. 10984 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 10985 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 10986 return Res; 10987 } 10988 10989 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10990 return Result; 10991 10992 return SDValue(); 10993 } 10994 10995 static SDValue PerformXORCombine(SDNode *N, 10996 TargetLowering::DAGCombinerInfo &DCI, 10997 const ARMSubtarget *Subtarget) { 10998 EVT VT = N->getValueType(0); 10999 SelectionDAG &DAG = DCI.DAG; 11000 11001 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11002 return SDValue(); 11003 11004 if (!Subtarget->isThumb1Only()) { 11005 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11006 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11007 return Result; 11008 11009 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11010 return Result; 11011 } 11012 11013 return SDValue(); 11014 } 11015 11016 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 11017 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 11018 // their position in "to" (Rd). 11019 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 11020 assert(N->getOpcode() == ARMISD::BFI); 11021 11022 SDValue From = N->getOperand(1); 11023 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 11024 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 11025 11026 // If the Base came from a SHR #C, we can deduce that it is really testing bit 11027 // #C in the base of the SHR. 11028 if (From->getOpcode() == ISD::SRL && 11029 isa<ConstantSDNode>(From->getOperand(1))) { 11030 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 11031 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 11032 FromMask <<= Shift.getLimitedValue(31); 11033 From = From->getOperand(0); 11034 } 11035 11036 return From; 11037 } 11038 11039 // If A and B contain one contiguous set of bits, does A | B == A . B? 11040 // 11041 // Neither A nor B must be zero. 11042 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 11043 unsigned LastActiveBitInA = A.countTrailingZeros(); 11044 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 11045 return LastActiveBitInA - 1 == FirstActiveBitInB; 11046 } 11047 11048 static SDValue FindBFIToCombineWith(SDNode *N) { 11049 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 11050 // if one exists. 11051 APInt ToMask, FromMask; 11052 SDValue From = ParseBFI(N, ToMask, FromMask); 11053 SDValue To = N->getOperand(0); 11054 11055 // Now check for a compatible BFI to merge with. We can pass through BFIs that 11056 // aren't compatible, but not if they set the same bit in their destination as 11057 // we do (or that of any BFI we're going to combine with). 11058 SDValue V = To; 11059 APInt CombinedToMask = ToMask; 11060 while (V.getOpcode() == ARMISD::BFI) { 11061 APInt NewToMask, NewFromMask; 11062 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 11063 if (NewFrom != From) { 11064 // This BFI has a different base. Keep going. 11065 CombinedToMask |= NewToMask; 11066 V = V.getOperand(0); 11067 continue; 11068 } 11069 11070 // Do the written bits conflict with any we've seen so far? 11071 if ((NewToMask & CombinedToMask).getBoolValue()) 11072 // Conflicting bits - bail out because going further is unsafe. 11073 return SDValue(); 11074 11075 // Are the new bits contiguous when combined with the old bits? 11076 if (BitsProperlyConcatenate(ToMask, NewToMask) && 11077 BitsProperlyConcatenate(FromMask, NewFromMask)) 11078 return V; 11079 if (BitsProperlyConcatenate(NewToMask, ToMask) && 11080 BitsProperlyConcatenate(NewFromMask, FromMask)) 11081 return V; 11082 11083 // We've seen a write to some bits, so track it. 11084 CombinedToMask |= NewToMask; 11085 // Keep going... 11086 V = V.getOperand(0); 11087 } 11088 11089 return SDValue(); 11090 } 11091 11092 static SDValue PerformBFICombine(SDNode *N, 11093 TargetLowering::DAGCombinerInfo &DCI) { 11094 SDValue N1 = N->getOperand(1); 11095 if (N1.getOpcode() == ISD::AND) { 11096 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 11097 // the bits being cleared by the AND are not demanded by the BFI. 11098 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11099 if (!N11C) 11100 return SDValue(); 11101 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 11102 unsigned LSB = countTrailingZeros(~InvMask); 11103 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 11104 assert(Width < 11105 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 11106 "undefined behavior"); 11107 unsigned Mask = (1u << Width) - 1; 11108 unsigned Mask2 = N11C->getZExtValue(); 11109 if ((Mask & (~Mask2)) == 0) 11110 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 11111 N->getOperand(0), N1.getOperand(0), 11112 N->getOperand(2)); 11113 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 11114 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 11115 // Keep track of any consecutive bits set that all come from the same base 11116 // value. We can combine these together into a single BFI. 11117 SDValue CombineBFI = FindBFIToCombineWith(N); 11118 if (CombineBFI == SDValue()) 11119 return SDValue(); 11120 11121 // We've found a BFI. 11122 APInt ToMask1, FromMask1; 11123 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 11124 11125 APInt ToMask2, FromMask2; 11126 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 11127 assert(From1 == From2); 11128 (void)From2; 11129 11130 // First, unlink CombineBFI. 11131 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 11132 // Then create a new BFI, combining the two together. 11133 APInt NewFromMask = FromMask1 | FromMask2; 11134 APInt NewToMask = ToMask1 | ToMask2; 11135 11136 EVT VT = N->getValueType(0); 11137 SDLoc dl(N); 11138 11139 if (NewFromMask[0] == 0) 11140 From1 = DCI.DAG.getNode( 11141 ISD::SRL, dl, VT, From1, 11142 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 11143 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 11144 DCI.DAG.getConstant(~NewToMask, dl, VT)); 11145 } 11146 return SDValue(); 11147 } 11148 11149 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 11150 /// ARMISD::VMOVRRD. 11151 static SDValue PerformVMOVRRDCombine(SDNode *N, 11152 TargetLowering::DAGCombinerInfo &DCI, 11153 const ARMSubtarget *Subtarget) { 11154 // vmovrrd(vmovdrr x, y) -> x,y 11155 SDValue InDouble = N->getOperand(0); 11156 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 11157 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 11158 11159 // vmovrrd(load f64) -> (load i32), (load i32) 11160 SDNode *InNode = InDouble.getNode(); 11161 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 11162 InNode->getValueType(0) == MVT::f64 && 11163 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 11164 !cast<LoadSDNode>(InNode)->isVolatile()) { 11165 // TODO: Should this be done for non-FrameIndex operands? 11166 LoadSDNode *LD = cast<LoadSDNode>(InNode); 11167 11168 SelectionDAG &DAG = DCI.DAG; 11169 SDLoc DL(LD); 11170 SDValue BasePtr = LD->getBasePtr(); 11171 SDValue NewLD1 = 11172 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 11173 LD->getAlignment(), LD->getMemOperand()->getFlags()); 11174 11175 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11176 DAG.getConstant(4, DL, MVT::i32)); 11177 SDValue NewLD2 = DAG.getLoad( 11178 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 11179 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 11180 11181 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 11182 if (DCI.DAG.getDataLayout().isBigEndian()) 11183 std::swap (NewLD1, NewLD2); 11184 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 11185 return Result; 11186 } 11187 11188 return SDValue(); 11189 } 11190 11191 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 11192 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 11193 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 11194 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 11195 SDValue Op0 = N->getOperand(0); 11196 SDValue Op1 = N->getOperand(1); 11197 if (Op0.getOpcode() == ISD::BITCAST) 11198 Op0 = Op0.getOperand(0); 11199 if (Op1.getOpcode() == ISD::BITCAST) 11200 Op1 = Op1.getOperand(0); 11201 if (Op0.getOpcode() == ARMISD::VMOVRRD && 11202 Op0.getNode() == Op1.getNode() && 11203 Op0.getResNo() == 0 && Op1.getResNo() == 1) 11204 return DAG.getNode(ISD::BITCAST, SDLoc(N), 11205 N->getValueType(0), Op0.getOperand(0)); 11206 return SDValue(); 11207 } 11208 11209 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 11210 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 11211 /// i64 vector to have f64 elements, since the value can then be loaded 11212 /// directly into a VFP register. 11213 static bool hasNormalLoadOperand(SDNode *N) { 11214 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 11215 for (unsigned i = 0; i < NumElts; ++i) { 11216 SDNode *Elt = N->getOperand(i).getNode(); 11217 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 11218 return true; 11219 } 11220 return false; 11221 } 11222 11223 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 11224 /// ISD::BUILD_VECTOR. 11225 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 11226 TargetLowering::DAGCombinerInfo &DCI, 11227 const ARMSubtarget *Subtarget) { 11228 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 11229 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 11230 // into a pair of GPRs, which is fine when the value is used as a scalar, 11231 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 11232 SelectionDAG &DAG = DCI.DAG; 11233 if (N->getNumOperands() == 2) 11234 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 11235 return RV; 11236 11237 // Load i64 elements as f64 values so that type legalization does not split 11238 // them up into i32 values. 11239 EVT VT = N->getValueType(0); 11240 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 11241 return SDValue(); 11242 SDLoc dl(N); 11243 SmallVector<SDValue, 8> Ops; 11244 unsigned NumElts = VT.getVectorNumElements(); 11245 for (unsigned i = 0; i < NumElts; ++i) { 11246 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 11247 Ops.push_back(V); 11248 // Make the DAGCombiner fold the bitcast. 11249 DCI.AddToWorklist(V.getNode()); 11250 } 11251 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 11252 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 11253 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11254 } 11255 11256 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 11257 static SDValue 11258 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11259 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 11260 // At that time, we may have inserted bitcasts from integer to float. 11261 // If these bitcasts have survived DAGCombine, change the lowering of this 11262 // BUILD_VECTOR in something more vector friendly, i.e., that does not 11263 // force to use floating point types. 11264 11265 // Make sure we can change the type of the vector. 11266 // This is possible iff: 11267 // 1. The vector is only used in a bitcast to a integer type. I.e., 11268 // 1.1. Vector is used only once. 11269 // 1.2. Use is a bit convert to an integer type. 11270 // 2. The size of its operands are 32-bits (64-bits are not legal). 11271 EVT VT = N->getValueType(0); 11272 EVT EltVT = VT.getVectorElementType(); 11273 11274 // Check 1.1. and 2. 11275 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 11276 return SDValue(); 11277 11278 // By construction, the input type must be float. 11279 assert(EltVT == MVT::f32 && "Unexpected type!"); 11280 11281 // Check 1.2. 11282 SDNode *Use = *N->use_begin(); 11283 if (Use->getOpcode() != ISD::BITCAST || 11284 Use->getValueType(0).isFloatingPoint()) 11285 return SDValue(); 11286 11287 // Check profitability. 11288 // Model is, if more than half of the relevant operands are bitcast from 11289 // i32, turn the build_vector into a sequence of insert_vector_elt. 11290 // Relevant operands are everything that is not statically 11291 // (i.e., at compile time) bitcasted. 11292 unsigned NumOfBitCastedElts = 0; 11293 unsigned NumElts = VT.getVectorNumElements(); 11294 unsigned NumOfRelevantElts = NumElts; 11295 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 11296 SDValue Elt = N->getOperand(Idx); 11297 if (Elt->getOpcode() == ISD::BITCAST) { 11298 // Assume only bit cast to i32 will go away. 11299 if (Elt->getOperand(0).getValueType() == MVT::i32) 11300 ++NumOfBitCastedElts; 11301 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 11302 // Constants are statically casted, thus do not count them as 11303 // relevant operands. 11304 --NumOfRelevantElts; 11305 } 11306 11307 // Check if more than half of the elements require a non-free bitcast. 11308 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 11309 return SDValue(); 11310 11311 SelectionDAG &DAG = DCI.DAG; 11312 // Create the new vector type. 11313 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 11314 // Check if the type is legal. 11315 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11316 if (!TLI.isTypeLegal(VecVT)) 11317 return SDValue(); 11318 11319 // Combine: 11320 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 11321 // => BITCAST INSERT_VECTOR_ELT 11322 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 11323 // (BITCAST EN), N. 11324 SDValue Vec = DAG.getUNDEF(VecVT); 11325 SDLoc dl(N); 11326 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 11327 SDValue V = N->getOperand(Idx); 11328 if (V.isUndef()) 11329 continue; 11330 if (V.getOpcode() == ISD::BITCAST && 11331 V->getOperand(0).getValueType() == MVT::i32) 11332 // Fold obvious case. 11333 V = V.getOperand(0); 11334 else { 11335 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 11336 // Make the DAGCombiner fold the bitcasts. 11337 DCI.AddToWorklist(V.getNode()); 11338 } 11339 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 11340 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 11341 } 11342 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 11343 // Make the DAGCombiner fold the bitcasts. 11344 DCI.AddToWorklist(Vec.getNode()); 11345 return Vec; 11346 } 11347 11348 /// PerformInsertEltCombine - Target-specific dag combine xforms for 11349 /// ISD::INSERT_VECTOR_ELT. 11350 static SDValue PerformInsertEltCombine(SDNode *N, 11351 TargetLowering::DAGCombinerInfo &DCI) { 11352 // Bitcast an i64 load inserted into a vector to f64. 11353 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11354 EVT VT = N->getValueType(0); 11355 SDNode *Elt = N->getOperand(1).getNode(); 11356 if (VT.getVectorElementType() != MVT::i64 || 11357 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 11358 return SDValue(); 11359 11360 SelectionDAG &DAG = DCI.DAG; 11361 SDLoc dl(N); 11362 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11363 VT.getVectorNumElements()); 11364 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 11365 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 11366 // Make the DAGCombiner fold the bitcasts. 11367 DCI.AddToWorklist(Vec.getNode()); 11368 DCI.AddToWorklist(V.getNode()); 11369 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 11370 Vec, V, N->getOperand(2)); 11371 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 11372 } 11373 11374 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 11375 /// ISD::VECTOR_SHUFFLE. 11376 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 11377 // The LLVM shufflevector instruction does not require the shuffle mask 11378 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 11379 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 11380 // operands do not match the mask length, they are extended by concatenating 11381 // them with undef vectors. That is probably the right thing for other 11382 // targets, but for NEON it is better to concatenate two double-register 11383 // size vector operands into a single quad-register size vector. Do that 11384 // transformation here: 11385 // shuffle(concat(v1, undef), concat(v2, undef)) -> 11386 // shuffle(concat(v1, v2), undef) 11387 SDValue Op0 = N->getOperand(0); 11388 SDValue Op1 = N->getOperand(1); 11389 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 11390 Op1.getOpcode() != ISD::CONCAT_VECTORS || 11391 Op0.getNumOperands() != 2 || 11392 Op1.getNumOperands() != 2) 11393 return SDValue(); 11394 SDValue Concat0Op1 = Op0.getOperand(1); 11395 SDValue Concat1Op1 = Op1.getOperand(1); 11396 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 11397 return SDValue(); 11398 // Skip the transformation if any of the types are illegal. 11399 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11400 EVT VT = N->getValueType(0); 11401 if (!TLI.isTypeLegal(VT) || 11402 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 11403 !TLI.isTypeLegal(Concat1Op1.getValueType())) 11404 return SDValue(); 11405 11406 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11407 Op0.getOperand(0), Op1.getOperand(0)); 11408 // Translate the shuffle mask. 11409 SmallVector<int, 16> NewMask; 11410 unsigned NumElts = VT.getVectorNumElements(); 11411 unsigned HalfElts = NumElts/2; 11412 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11413 for (unsigned n = 0; n < NumElts; ++n) { 11414 int MaskElt = SVN->getMaskElt(n); 11415 int NewElt = -1; 11416 if (MaskElt < (int)HalfElts) 11417 NewElt = MaskElt; 11418 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 11419 NewElt = HalfElts + MaskElt - NumElts; 11420 NewMask.push_back(NewElt); 11421 } 11422 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 11423 DAG.getUNDEF(VT), NewMask); 11424 } 11425 11426 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 11427 /// NEON load/store intrinsics, and generic vector load/stores, to merge 11428 /// base address updates. 11429 /// For generic load/stores, the memory type is assumed to be a vector. 11430 /// The caller is assumed to have checked legality. 11431 static SDValue CombineBaseUpdate(SDNode *N, 11432 TargetLowering::DAGCombinerInfo &DCI) { 11433 SelectionDAG &DAG = DCI.DAG; 11434 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 11435 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 11436 const bool isStore = N->getOpcode() == ISD::STORE; 11437 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 11438 SDValue Addr = N->getOperand(AddrOpIdx); 11439 MemSDNode *MemN = cast<MemSDNode>(N); 11440 SDLoc dl(N); 11441 11442 // Search for a use of the address operand that is an increment. 11443 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11444 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11445 SDNode *User = *UI; 11446 if (User->getOpcode() != ISD::ADD || 11447 UI.getUse().getResNo() != Addr.getResNo()) 11448 continue; 11449 11450 // Check that the add is independent of the load/store. Otherwise, folding 11451 // it would create a cycle. 11452 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 11453 continue; 11454 11455 // Find the new opcode for the updating load/store. 11456 bool isLoadOp = true; 11457 bool isLaneOp = false; 11458 unsigned NewOpc = 0; 11459 unsigned NumVecs = 0; 11460 if (isIntrinsic) { 11461 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11462 switch (IntNo) { 11463 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11464 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 11465 NumVecs = 1; break; 11466 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 11467 NumVecs = 2; break; 11468 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 11469 NumVecs = 3; break; 11470 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 11471 NumVecs = 4; break; 11472 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 11473 NumVecs = 2; isLaneOp = true; break; 11474 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 11475 NumVecs = 3; isLaneOp = true; break; 11476 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 11477 NumVecs = 4; isLaneOp = true; break; 11478 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 11479 NumVecs = 1; isLoadOp = false; break; 11480 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 11481 NumVecs = 2; isLoadOp = false; break; 11482 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 11483 NumVecs = 3; isLoadOp = false; break; 11484 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 11485 NumVecs = 4; isLoadOp = false; break; 11486 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 11487 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 11488 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 11489 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 11490 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 11491 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 11492 } 11493 } else { 11494 isLaneOp = true; 11495 switch (N->getOpcode()) { 11496 default: llvm_unreachable("unexpected opcode for Neon base update"); 11497 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 11498 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 11499 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 11500 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 11501 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 11502 NumVecs = 1; isLaneOp = false; break; 11503 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 11504 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 11505 } 11506 } 11507 11508 // Find the size of memory referenced by the load/store. 11509 EVT VecTy; 11510 if (isLoadOp) { 11511 VecTy = N->getValueType(0); 11512 } else if (isIntrinsic) { 11513 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 11514 } else { 11515 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 11516 VecTy = N->getOperand(1).getValueType(); 11517 } 11518 11519 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11520 if (isLaneOp) 11521 NumBytes /= VecTy.getVectorNumElements(); 11522 11523 // If the increment is a constant, it must match the memory ref size. 11524 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11525 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 11526 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 11527 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 11528 // separate instructions that make it harder to use a non-constant update. 11529 continue; 11530 } 11531 11532 // OK, we found an ADD we can fold into the base update. 11533 // Now, create a _UPD node, taking care of not breaking alignment. 11534 11535 EVT AlignedVecTy = VecTy; 11536 unsigned Alignment = MemN->getAlignment(); 11537 11538 // If this is a less-than-standard-aligned load/store, change the type to 11539 // match the standard alignment. 11540 // The alignment is overlooked when selecting _UPD variants; and it's 11541 // easier to introduce bitcasts here than fix that. 11542 // There are 3 ways to get to this base-update combine: 11543 // - intrinsics: they are assumed to be properly aligned (to the standard 11544 // alignment of the memory type), so we don't need to do anything. 11545 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 11546 // intrinsics, so, likewise, there's nothing to do. 11547 // - generic load/store instructions: the alignment is specified as an 11548 // explicit operand, rather than implicitly as the standard alignment 11549 // of the memory type (like the intrisics). We need to change the 11550 // memory type to match the explicit alignment. That way, we don't 11551 // generate non-standard-aligned ARMISD::VLDx nodes. 11552 if (isa<LSBaseSDNode>(N)) { 11553 if (Alignment == 0) 11554 Alignment = 1; 11555 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 11556 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 11557 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 11558 assert(!isLaneOp && "Unexpected generic load/store lane."); 11559 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 11560 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 11561 } 11562 // Don't set an explicit alignment on regular load/stores that we want 11563 // to transform to VLD/VST 1_UPD nodes. 11564 // This matches the behavior of regular load/stores, which only get an 11565 // explicit alignment if the MMO alignment is larger than the standard 11566 // alignment of the memory type. 11567 // Intrinsics, however, always get an explicit alignment, set to the 11568 // alignment of the MMO. 11569 Alignment = 1; 11570 } 11571 11572 // Create the new updating load/store node. 11573 // First, create an SDVTList for the new updating node's results. 11574 EVT Tys[6]; 11575 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 11576 unsigned n; 11577 for (n = 0; n < NumResultVecs; ++n) 11578 Tys[n] = AlignedVecTy; 11579 Tys[n++] = MVT::i32; 11580 Tys[n] = MVT::Other; 11581 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 11582 11583 // Then, gather the new node's operands. 11584 SmallVector<SDValue, 8> Ops; 11585 Ops.push_back(N->getOperand(0)); // incoming chain 11586 Ops.push_back(N->getOperand(AddrOpIdx)); 11587 Ops.push_back(Inc); 11588 11589 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 11590 // Try to match the intrinsic's signature 11591 Ops.push_back(StN->getValue()); 11592 } else { 11593 // Loads (and of course intrinsics) match the intrinsics' signature, 11594 // so just add all but the alignment operand. 11595 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 11596 Ops.push_back(N->getOperand(i)); 11597 } 11598 11599 // For all node types, the alignment operand is always the last one. 11600 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 11601 11602 // If this is a non-standard-aligned STORE, the penultimate operand is the 11603 // stored value. Bitcast it to the aligned type. 11604 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 11605 SDValue &StVal = Ops[Ops.size()-2]; 11606 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 11607 } 11608 11609 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 11610 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 11611 MemN->getMemOperand()); 11612 11613 // Update the uses. 11614 SmallVector<SDValue, 5> NewResults; 11615 for (unsigned i = 0; i < NumResultVecs; ++i) 11616 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11617 11618 // If this is an non-standard-aligned LOAD, the first result is the loaded 11619 // value. Bitcast it to the expected result type. 11620 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 11621 SDValue &LdVal = NewResults[0]; 11622 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 11623 } 11624 11625 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 11626 DCI.CombineTo(N, NewResults); 11627 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11628 11629 break; 11630 } 11631 return SDValue(); 11632 } 11633 11634 static SDValue PerformVLDCombine(SDNode *N, 11635 TargetLowering::DAGCombinerInfo &DCI) { 11636 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11637 return SDValue(); 11638 11639 return CombineBaseUpdate(N, DCI); 11640 } 11641 11642 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 11643 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 11644 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11645 /// return true. 11646 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11647 SelectionDAG &DAG = DCI.DAG; 11648 EVT VT = N->getValueType(0); 11649 // vldN-dup instructions only support 64-bit vectors for N > 1. 11650 if (!VT.is64BitVector()) 11651 return false; 11652 11653 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11654 SDNode *VLD = N->getOperand(0).getNode(); 11655 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11656 return false; 11657 unsigned NumVecs = 0; 11658 unsigned NewOpc = 0; 11659 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11660 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11661 NumVecs = 2; 11662 NewOpc = ARMISD::VLD2DUP; 11663 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11664 NumVecs = 3; 11665 NewOpc = ARMISD::VLD3DUP; 11666 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11667 NumVecs = 4; 11668 NewOpc = ARMISD::VLD4DUP; 11669 } else { 11670 return false; 11671 } 11672 11673 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11674 // numbers match the load. 11675 unsigned VLDLaneNo = 11676 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11677 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11678 UI != UE; ++UI) { 11679 // Ignore uses of the chain result. 11680 if (UI.getUse().getResNo() == NumVecs) 11681 continue; 11682 SDNode *User = *UI; 11683 if (User->getOpcode() != ARMISD::VDUPLANE || 11684 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11685 return false; 11686 } 11687 11688 // Create the vldN-dup node. 11689 EVT Tys[5]; 11690 unsigned n; 11691 for (n = 0; n < NumVecs; ++n) 11692 Tys[n] = VT; 11693 Tys[n] = MVT::Other; 11694 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11695 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11696 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11697 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11698 Ops, VLDMemInt->getMemoryVT(), 11699 VLDMemInt->getMemOperand()); 11700 11701 // Update the uses. 11702 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11703 UI != UE; ++UI) { 11704 unsigned ResNo = UI.getUse().getResNo(); 11705 // Ignore uses of the chain result. 11706 if (ResNo == NumVecs) 11707 continue; 11708 SDNode *User = *UI; 11709 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11710 } 11711 11712 // Now the vldN-lane intrinsic is dead except for its chain result. 11713 // Update uses of the chain. 11714 std::vector<SDValue> VLDDupResults; 11715 for (unsigned n = 0; n < NumVecs; ++n) 11716 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11717 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11718 DCI.CombineTo(VLD, VLDDupResults); 11719 11720 return true; 11721 } 11722 11723 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11724 /// ARMISD::VDUPLANE. 11725 static SDValue PerformVDUPLANECombine(SDNode *N, 11726 TargetLowering::DAGCombinerInfo &DCI) { 11727 SDValue Op = N->getOperand(0); 11728 11729 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11730 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11731 if (CombineVLDDUP(N, DCI)) 11732 return SDValue(N, 0); 11733 11734 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11735 // redundant. Ignore bit_converts for now; element sizes are checked below. 11736 while (Op.getOpcode() == ISD::BITCAST) 11737 Op = Op.getOperand(0); 11738 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11739 return SDValue(); 11740 11741 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11742 unsigned EltSize = Op.getScalarValueSizeInBits(); 11743 // The canonical VMOV for a zero vector uses a 32-bit element size. 11744 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11745 unsigned EltBits; 11746 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11747 EltSize = 8; 11748 EVT VT = N->getValueType(0); 11749 if (EltSize > VT.getScalarSizeInBits()) 11750 return SDValue(); 11751 11752 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11753 } 11754 11755 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11756 static SDValue PerformVDUPCombine(SDNode *N, 11757 TargetLowering::DAGCombinerInfo &DCI) { 11758 SelectionDAG &DAG = DCI.DAG; 11759 SDValue Op = N->getOperand(0); 11760 11761 // Match VDUP(LOAD) -> VLD1DUP. 11762 // We match this pattern here rather than waiting for isel because the 11763 // transform is only legal for unindexed loads. 11764 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11765 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11766 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11767 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11768 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11769 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11770 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11771 Ops, LD->getMemoryVT(), 11772 LD->getMemOperand()); 11773 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11774 return VLDDup; 11775 } 11776 11777 return SDValue(); 11778 } 11779 11780 static SDValue PerformLOADCombine(SDNode *N, 11781 TargetLowering::DAGCombinerInfo &DCI) { 11782 EVT VT = N->getValueType(0); 11783 11784 // If this is a legal vector load, try to combine it into a VLD1_UPD. 11785 if (ISD::isNormalLoad(N) && VT.isVector() && 11786 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11787 return CombineBaseUpdate(N, DCI); 11788 11789 return SDValue(); 11790 } 11791 11792 /// PerformSTORECombine - Target-specific dag combine xforms for 11793 /// ISD::STORE. 11794 static SDValue PerformSTORECombine(SDNode *N, 11795 TargetLowering::DAGCombinerInfo &DCI) { 11796 StoreSDNode *St = cast<StoreSDNode>(N); 11797 if (St->isVolatile()) 11798 return SDValue(); 11799 11800 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 11801 // pack all of the elements in one place. Next, store to memory in fewer 11802 // chunks. 11803 SDValue StVal = St->getValue(); 11804 EVT VT = StVal.getValueType(); 11805 if (St->isTruncatingStore() && VT.isVector()) { 11806 SelectionDAG &DAG = DCI.DAG; 11807 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11808 EVT StVT = St->getMemoryVT(); 11809 unsigned NumElems = VT.getVectorNumElements(); 11810 assert(StVT != VT && "Cannot truncate to the same type"); 11811 unsigned FromEltSz = VT.getScalarSizeInBits(); 11812 unsigned ToEltSz = StVT.getScalarSizeInBits(); 11813 11814 // From, To sizes and ElemCount must be pow of two 11815 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 11816 11817 // We are going to use the original vector elt for storing. 11818 // Accumulated smaller vector elements must be a multiple of the store size. 11819 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 11820 11821 unsigned SizeRatio = FromEltSz / ToEltSz; 11822 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 11823 11824 // Create a type on which we perform the shuffle. 11825 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 11826 NumElems*SizeRatio); 11827 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 11828 11829 SDLoc DL(St); 11830 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 11831 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 11832 for (unsigned i = 0; i < NumElems; ++i) 11833 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 11834 ? (i + 1) * SizeRatio - 1 11835 : i * SizeRatio; 11836 11837 // Can't shuffle using an illegal type. 11838 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 11839 11840 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 11841 DAG.getUNDEF(WideVec.getValueType()), 11842 ShuffleVec); 11843 // At this point all of the data is stored at the bottom of the 11844 // register. We now need to save it to mem. 11845 11846 // Find the largest store unit 11847 MVT StoreType = MVT::i8; 11848 for (MVT Tp : MVT::integer_valuetypes()) { 11849 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 11850 StoreType = Tp; 11851 } 11852 // Didn't find a legal store type. 11853 if (!TLI.isTypeLegal(StoreType)) 11854 return SDValue(); 11855 11856 // Bitcast the original vector into a vector of store-size units 11857 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 11858 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 11859 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 11860 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 11861 SmallVector<SDValue, 8> Chains; 11862 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 11863 TLI.getPointerTy(DAG.getDataLayout())); 11864 SDValue BasePtr = St->getBasePtr(); 11865 11866 // Perform one or more big stores into memory. 11867 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 11868 for (unsigned I = 0; I < E; I++) { 11869 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 11870 StoreType, ShuffWide, 11871 DAG.getIntPtrConstant(I, DL)); 11872 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 11873 St->getPointerInfo(), St->getAlignment(), 11874 St->getMemOperand()->getFlags()); 11875 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 11876 Increment); 11877 Chains.push_back(Ch); 11878 } 11879 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11880 } 11881 11882 if (!ISD::isNormalStore(St)) 11883 return SDValue(); 11884 11885 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 11886 // ARM stores of arguments in the same cache line. 11887 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 11888 StVal.getNode()->hasOneUse()) { 11889 SelectionDAG &DAG = DCI.DAG; 11890 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 11891 SDLoc DL(St); 11892 SDValue BasePtr = St->getBasePtr(); 11893 SDValue NewST1 = DAG.getStore( 11894 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 11895 BasePtr, St->getPointerInfo(), St->getAlignment(), 11896 St->getMemOperand()->getFlags()); 11897 11898 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11899 DAG.getConstant(4, DL, MVT::i32)); 11900 return DAG.getStore(NewST1.getValue(0), DL, 11901 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 11902 OffsetPtr, St->getPointerInfo(), 11903 std::min(4U, St->getAlignment() / 2), 11904 St->getMemOperand()->getFlags()); 11905 } 11906 11907 if (StVal.getValueType() == MVT::i64 && 11908 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11909 11910 // Bitcast an i64 store extracted from a vector to f64. 11911 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11912 SelectionDAG &DAG = DCI.DAG; 11913 SDLoc dl(StVal); 11914 SDValue IntVec = StVal.getOperand(0); 11915 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11916 IntVec.getValueType().getVectorNumElements()); 11917 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 11918 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 11919 Vec, StVal.getOperand(1)); 11920 dl = SDLoc(N); 11921 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 11922 // Make the DAGCombiner fold the bitcasts. 11923 DCI.AddToWorklist(Vec.getNode()); 11924 DCI.AddToWorklist(ExtElt.getNode()); 11925 DCI.AddToWorklist(V.getNode()); 11926 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 11927 St->getPointerInfo(), St->getAlignment(), 11928 St->getMemOperand()->getFlags(), St->getAAInfo()); 11929 } 11930 11931 // If this is a legal vector store, try to combine it into a VST1_UPD. 11932 if (ISD::isNormalStore(N) && VT.isVector() && 11933 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11934 return CombineBaseUpdate(N, DCI); 11935 11936 return SDValue(); 11937 } 11938 11939 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11940 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11941 /// when the VMUL has a constant operand that is a power of 2. 11942 /// 11943 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11944 /// vmul.f32 d16, d17, d16 11945 /// vcvt.s32.f32 d16, d16 11946 /// becomes: 11947 /// vcvt.s32.f32 d16, d16, #3 11948 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11949 const ARMSubtarget *Subtarget) { 11950 if (!Subtarget->hasNEON()) 11951 return SDValue(); 11952 11953 SDValue Op = N->getOperand(0); 11954 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 11955 Op.getOpcode() != ISD::FMUL) 11956 return SDValue(); 11957 11958 SDValue ConstVec = Op->getOperand(1); 11959 if (!isa<BuildVectorSDNode>(ConstVec)) 11960 return SDValue(); 11961 11962 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 11963 uint32_t FloatBits = FloatTy.getSizeInBits(); 11964 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 11965 uint32_t IntBits = IntTy.getSizeInBits(); 11966 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11967 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11968 // These instructions only exist converting from f32 to i32. We can handle 11969 // smaller integers by generating an extra truncate, but larger ones would 11970 // be lossy. We also can't handle more then 4 lanes, since these intructions 11971 // only support v2i32/v4i32 types. 11972 return SDValue(); 11973 } 11974 11975 BitVector UndefElements; 11976 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11977 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11978 if (C == -1 || C == 0 || C > 32) 11979 return SDValue(); 11980 11981 SDLoc dl(N); 11982 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 11983 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 11984 Intrinsic::arm_neon_vcvtfp2fxu; 11985 SDValue FixConv = DAG.getNode( 11986 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11987 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 11988 DAG.getConstant(C, dl, MVT::i32)); 11989 11990 if (IntBits < FloatBits) 11991 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 11992 11993 return FixConv; 11994 } 11995 11996 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 11997 /// can replace combinations of VCVT (integer to floating-point) and VDIV 11998 /// when the VDIV has a constant operand that is a power of 2. 11999 /// 12000 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12001 /// vcvt.f32.s32 d16, d16 12002 /// vdiv.f32 d16, d17, d16 12003 /// becomes: 12004 /// vcvt.f32.s32 d16, d16, #3 12005 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 12006 const ARMSubtarget *Subtarget) { 12007 if (!Subtarget->hasNEON()) 12008 return SDValue(); 12009 12010 SDValue Op = N->getOperand(0); 12011 unsigned OpOpcode = Op.getNode()->getOpcode(); 12012 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 12013 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 12014 return SDValue(); 12015 12016 SDValue ConstVec = N->getOperand(1); 12017 if (!isa<BuildVectorSDNode>(ConstVec)) 12018 return SDValue(); 12019 12020 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 12021 uint32_t FloatBits = FloatTy.getSizeInBits(); 12022 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 12023 uint32_t IntBits = IntTy.getSizeInBits(); 12024 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12025 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 12026 // These instructions only exist converting from i32 to f32. We can handle 12027 // smaller integers by generating an extra extend, but larger ones would 12028 // be lossy. We also can't handle more then 4 lanes, since these intructions 12029 // only support v2i32/v4i32 types. 12030 return SDValue(); 12031 } 12032 12033 BitVector UndefElements; 12034 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12035 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12036 if (C == -1 || C == 0 || C > 32) 12037 return SDValue(); 12038 12039 SDLoc dl(N); 12040 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 12041 SDValue ConvInput = Op.getOperand(0); 12042 if (IntBits < FloatBits) 12043 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 12044 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12045 ConvInput); 12046 12047 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 12048 Intrinsic::arm_neon_vcvtfxu2fp; 12049 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 12050 Op.getValueType(), 12051 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 12052 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 12053 } 12054 12055 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 12056 /// operand of a vector shift operation, where all the elements of the 12057 /// build_vector must have the same constant integer value. 12058 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 12059 // Ignore bit_converts. 12060 while (Op.getOpcode() == ISD::BITCAST) 12061 Op = Op.getOperand(0); 12062 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 12063 APInt SplatBits, SplatUndef; 12064 unsigned SplatBitSize; 12065 bool HasAnyUndefs; 12066 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 12067 HasAnyUndefs, ElementBits) || 12068 SplatBitSize > ElementBits) 12069 return false; 12070 Cnt = SplatBits.getSExtValue(); 12071 return true; 12072 } 12073 12074 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 12075 /// operand of a vector shift left operation. That value must be in the range: 12076 /// 0 <= Value < ElementBits for a left shift; or 12077 /// 0 <= Value <= ElementBits for a long left shift. 12078 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 12079 assert(VT.isVector() && "vector shift count is not a vector type"); 12080 int64_t ElementBits = VT.getScalarSizeInBits(); 12081 if (! getVShiftImm(Op, ElementBits, Cnt)) 12082 return false; 12083 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 12084 } 12085 12086 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 12087 /// operand of a vector shift right operation. For a shift opcode, the value 12088 /// is positive, but for an intrinsic the value count must be negative. The 12089 /// absolute value must be in the range: 12090 /// 1 <= |Value| <= ElementBits for a right shift; or 12091 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 12092 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 12093 int64_t &Cnt) { 12094 assert(VT.isVector() && "vector shift count is not a vector type"); 12095 int64_t ElementBits = VT.getScalarSizeInBits(); 12096 if (! getVShiftImm(Op, ElementBits, Cnt)) 12097 return false; 12098 if (!isIntrinsic) 12099 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 12100 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 12101 Cnt = -Cnt; 12102 return true; 12103 } 12104 return false; 12105 } 12106 12107 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 12108 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 12109 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12110 switch (IntNo) { 12111 default: 12112 // Don't do anything for most intrinsics. 12113 break; 12114 12115 // Vector shifts: check for immediate versions and lower them. 12116 // Note: This is done during DAG combining instead of DAG legalizing because 12117 // the build_vectors for 64-bit vector element shift counts are generally 12118 // not legal, and it is hard to see their values after they get legalized to 12119 // loads from a constant pool. 12120 case Intrinsic::arm_neon_vshifts: 12121 case Intrinsic::arm_neon_vshiftu: 12122 case Intrinsic::arm_neon_vrshifts: 12123 case Intrinsic::arm_neon_vrshiftu: 12124 case Intrinsic::arm_neon_vrshiftn: 12125 case Intrinsic::arm_neon_vqshifts: 12126 case Intrinsic::arm_neon_vqshiftu: 12127 case Intrinsic::arm_neon_vqshiftsu: 12128 case Intrinsic::arm_neon_vqshiftns: 12129 case Intrinsic::arm_neon_vqshiftnu: 12130 case Intrinsic::arm_neon_vqshiftnsu: 12131 case Intrinsic::arm_neon_vqrshiftns: 12132 case Intrinsic::arm_neon_vqrshiftnu: 12133 case Intrinsic::arm_neon_vqrshiftnsu: { 12134 EVT VT = N->getOperand(1).getValueType(); 12135 int64_t Cnt; 12136 unsigned VShiftOpc = 0; 12137 12138 switch (IntNo) { 12139 case Intrinsic::arm_neon_vshifts: 12140 case Intrinsic::arm_neon_vshiftu: 12141 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 12142 VShiftOpc = ARMISD::VSHL; 12143 break; 12144 } 12145 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 12146 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 12147 ARMISD::VSHRs : ARMISD::VSHRu); 12148 break; 12149 } 12150 return SDValue(); 12151 12152 case Intrinsic::arm_neon_vrshifts: 12153 case Intrinsic::arm_neon_vrshiftu: 12154 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 12155 break; 12156 return SDValue(); 12157 12158 case Intrinsic::arm_neon_vqshifts: 12159 case Intrinsic::arm_neon_vqshiftu: 12160 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12161 break; 12162 return SDValue(); 12163 12164 case Intrinsic::arm_neon_vqshiftsu: 12165 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12166 break; 12167 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 12168 12169 case Intrinsic::arm_neon_vrshiftn: 12170 case Intrinsic::arm_neon_vqshiftns: 12171 case Intrinsic::arm_neon_vqshiftnu: 12172 case Intrinsic::arm_neon_vqshiftnsu: 12173 case Intrinsic::arm_neon_vqrshiftns: 12174 case Intrinsic::arm_neon_vqrshiftnu: 12175 case Intrinsic::arm_neon_vqrshiftnsu: 12176 // Narrowing shifts require an immediate right shift. 12177 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 12178 break; 12179 llvm_unreachable("invalid shift count for narrowing vector shift " 12180 "intrinsic"); 12181 12182 default: 12183 llvm_unreachable("unhandled vector shift"); 12184 } 12185 12186 switch (IntNo) { 12187 case Intrinsic::arm_neon_vshifts: 12188 case Intrinsic::arm_neon_vshiftu: 12189 // Opcode already set above. 12190 break; 12191 case Intrinsic::arm_neon_vrshifts: 12192 VShiftOpc = ARMISD::VRSHRs; break; 12193 case Intrinsic::arm_neon_vrshiftu: 12194 VShiftOpc = ARMISD::VRSHRu; break; 12195 case Intrinsic::arm_neon_vrshiftn: 12196 VShiftOpc = ARMISD::VRSHRN; break; 12197 case Intrinsic::arm_neon_vqshifts: 12198 VShiftOpc = ARMISD::VQSHLs; break; 12199 case Intrinsic::arm_neon_vqshiftu: 12200 VShiftOpc = ARMISD::VQSHLu; break; 12201 case Intrinsic::arm_neon_vqshiftsu: 12202 VShiftOpc = ARMISD::VQSHLsu; break; 12203 case Intrinsic::arm_neon_vqshiftns: 12204 VShiftOpc = ARMISD::VQSHRNs; break; 12205 case Intrinsic::arm_neon_vqshiftnu: 12206 VShiftOpc = ARMISD::VQSHRNu; break; 12207 case Intrinsic::arm_neon_vqshiftnsu: 12208 VShiftOpc = ARMISD::VQSHRNsu; break; 12209 case Intrinsic::arm_neon_vqrshiftns: 12210 VShiftOpc = ARMISD::VQRSHRNs; break; 12211 case Intrinsic::arm_neon_vqrshiftnu: 12212 VShiftOpc = ARMISD::VQRSHRNu; break; 12213 case Intrinsic::arm_neon_vqrshiftnsu: 12214 VShiftOpc = ARMISD::VQRSHRNsu; break; 12215 } 12216 12217 SDLoc dl(N); 12218 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12219 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 12220 } 12221 12222 case Intrinsic::arm_neon_vshiftins: { 12223 EVT VT = N->getOperand(1).getValueType(); 12224 int64_t Cnt; 12225 unsigned VShiftOpc = 0; 12226 12227 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 12228 VShiftOpc = ARMISD::VSLI; 12229 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 12230 VShiftOpc = ARMISD::VSRI; 12231 else { 12232 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 12233 } 12234 12235 SDLoc dl(N); 12236 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12237 N->getOperand(1), N->getOperand(2), 12238 DAG.getConstant(Cnt, dl, MVT::i32)); 12239 } 12240 12241 case Intrinsic::arm_neon_vqrshifts: 12242 case Intrinsic::arm_neon_vqrshiftu: 12243 // No immediate versions of these to check for. 12244 break; 12245 } 12246 12247 return SDValue(); 12248 } 12249 12250 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 12251 /// lowers them. As with the vector shift intrinsics, this is done during DAG 12252 /// combining instead of DAG legalizing because the build_vectors for 64-bit 12253 /// vector element shift counts are generally not legal, and it is hard to see 12254 /// their values after they get legalized to loads from a constant pool. 12255 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 12256 const ARMSubtarget *ST) { 12257 EVT VT = N->getValueType(0); 12258 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 12259 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 12260 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 12261 SDValue N1 = N->getOperand(1); 12262 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12263 SDValue N0 = N->getOperand(0); 12264 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 12265 DAG.MaskedValueIsZero(N0.getOperand(0), 12266 APInt::getHighBitsSet(32, 16))) 12267 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 12268 } 12269 } 12270 12271 // Nothing to be done for scalar shifts. 12272 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12273 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 12274 return SDValue(); 12275 12276 assert(ST->hasNEON() && "unexpected vector shift"); 12277 int64_t Cnt; 12278 12279 switch (N->getOpcode()) { 12280 default: llvm_unreachable("unexpected shift opcode"); 12281 12282 case ISD::SHL: 12283 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 12284 SDLoc dl(N); 12285 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 12286 DAG.getConstant(Cnt, dl, MVT::i32)); 12287 } 12288 break; 12289 12290 case ISD::SRA: 12291 case ISD::SRL: 12292 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 12293 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 12294 ARMISD::VSHRs : ARMISD::VSHRu); 12295 SDLoc dl(N); 12296 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 12297 DAG.getConstant(Cnt, dl, MVT::i32)); 12298 } 12299 } 12300 return SDValue(); 12301 } 12302 12303 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 12304 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 12305 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 12306 const ARMSubtarget *ST) { 12307 SDValue N0 = N->getOperand(0); 12308 12309 // Check for sign- and zero-extensions of vector extract operations of 8- 12310 // and 16-bit vector elements. NEON supports these directly. They are 12311 // handled during DAG combining because type legalization will promote them 12312 // to 32-bit types and it is messy to recognize the operations after that. 12313 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12314 SDValue Vec = N0.getOperand(0); 12315 SDValue Lane = N0.getOperand(1); 12316 EVT VT = N->getValueType(0); 12317 EVT EltVT = N0.getValueType(); 12318 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12319 12320 if (VT == MVT::i32 && 12321 (EltVT == MVT::i8 || EltVT == MVT::i16) && 12322 TLI.isTypeLegal(Vec.getValueType()) && 12323 isa<ConstantSDNode>(Lane)) { 12324 12325 unsigned Opc = 0; 12326 switch (N->getOpcode()) { 12327 default: llvm_unreachable("unexpected opcode"); 12328 case ISD::SIGN_EXTEND: 12329 Opc = ARMISD::VGETLANEs; 12330 break; 12331 case ISD::ZERO_EXTEND: 12332 case ISD::ANY_EXTEND: 12333 Opc = ARMISD::VGETLANEu; 12334 break; 12335 } 12336 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 12337 } 12338 } 12339 12340 return SDValue(); 12341 } 12342 12343 static const APInt *isPowerOf2Constant(SDValue V) { 12344 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 12345 if (!C) 12346 return nullptr; 12347 const APInt *CV = &C->getAPIntValue(); 12348 return CV->isPowerOf2() ? CV : nullptr; 12349 } 12350 12351 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 12352 // If we have a CMOV, OR and AND combination such as: 12353 // if (x & CN) 12354 // y |= CM; 12355 // 12356 // And: 12357 // * CN is a single bit; 12358 // * All bits covered by CM are known zero in y 12359 // 12360 // Then we can convert this into a sequence of BFI instructions. This will 12361 // always be a win if CM is a single bit, will always be no worse than the 12362 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 12363 // three bits (due to the extra IT instruction). 12364 12365 SDValue Op0 = CMOV->getOperand(0); 12366 SDValue Op1 = CMOV->getOperand(1); 12367 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 12368 auto CC = CCNode->getAPIntValue().getLimitedValue(); 12369 SDValue CmpZ = CMOV->getOperand(4); 12370 12371 // The compare must be against zero. 12372 if (!isNullConstant(CmpZ->getOperand(1))) 12373 return SDValue(); 12374 12375 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 12376 SDValue And = CmpZ->getOperand(0); 12377 if (And->getOpcode() != ISD::AND) 12378 return SDValue(); 12379 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 12380 if (!AndC) 12381 return SDValue(); 12382 SDValue X = And->getOperand(0); 12383 12384 if (CC == ARMCC::EQ) { 12385 // We're performing an "equal to zero" compare. Swap the operands so we 12386 // canonicalize on a "not equal to zero" compare. 12387 std::swap(Op0, Op1); 12388 } else { 12389 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 12390 } 12391 12392 if (Op1->getOpcode() != ISD::OR) 12393 return SDValue(); 12394 12395 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 12396 if (!OrC) 12397 return SDValue(); 12398 SDValue Y = Op1->getOperand(0); 12399 12400 if (Op0 != Y) 12401 return SDValue(); 12402 12403 // Now, is it profitable to continue? 12404 APInt OrCI = OrC->getAPIntValue(); 12405 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 12406 if (OrCI.countPopulation() > Heuristic) 12407 return SDValue(); 12408 12409 // Lastly, can we determine that the bits defined by OrCI 12410 // are zero in Y? 12411 KnownBits Known; 12412 DAG.computeKnownBits(Y, Known); 12413 if ((OrCI & Known.Zero) != OrCI) 12414 return SDValue(); 12415 12416 // OK, we can do the combine. 12417 SDValue V = Y; 12418 SDLoc dl(X); 12419 EVT VT = X.getValueType(); 12420 unsigned BitInX = AndC->logBase2(); 12421 12422 if (BitInX != 0) { 12423 // We must shift X first. 12424 X = DAG.getNode(ISD::SRL, dl, VT, X, 12425 DAG.getConstant(BitInX, dl, VT)); 12426 } 12427 12428 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 12429 BitInY < NumActiveBits; ++BitInY) { 12430 if (OrCI[BitInY] == 0) 12431 continue; 12432 APInt Mask(VT.getSizeInBits(), 0); 12433 Mask.setBit(BitInY); 12434 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 12435 // Confusingly, the operand is an *inverted* mask. 12436 DAG.getConstant(~Mask, dl, VT)); 12437 } 12438 12439 return V; 12440 } 12441 12442 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 12443 SDValue 12444 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 12445 SDValue Cmp = N->getOperand(4); 12446 if (Cmp.getOpcode() != ARMISD::CMPZ) 12447 // Only looking at NE cases. 12448 return SDValue(); 12449 12450 EVT VT = N->getValueType(0); 12451 SDLoc dl(N); 12452 SDValue LHS = Cmp.getOperand(0); 12453 SDValue RHS = Cmp.getOperand(1); 12454 SDValue Chain = N->getOperand(0); 12455 SDValue BB = N->getOperand(1); 12456 SDValue ARMcc = N->getOperand(2); 12457 ARMCC::CondCodes CC = 12458 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12459 12460 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 12461 // -> (brcond Chain BB CC CPSR Cmp) 12462 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 12463 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 12464 LHS->getOperand(0)->hasOneUse()) { 12465 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 12466 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 12467 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12468 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12469 if ((LHS00C && LHS00C->getZExtValue() == 0) && 12470 (LHS01C && LHS01C->getZExtValue() == 1) && 12471 (LHS1C && LHS1C->getZExtValue() == 1) && 12472 (RHSC && RHSC->getZExtValue() == 0)) { 12473 return DAG.getNode( 12474 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 12475 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 12476 } 12477 } 12478 12479 return SDValue(); 12480 } 12481 12482 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 12483 SDValue 12484 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 12485 SDValue Cmp = N->getOperand(4); 12486 if (Cmp.getOpcode() != ARMISD::CMPZ) 12487 // Only looking at EQ and NE cases. 12488 return SDValue(); 12489 12490 EVT VT = N->getValueType(0); 12491 SDLoc dl(N); 12492 SDValue LHS = Cmp.getOperand(0); 12493 SDValue RHS = Cmp.getOperand(1); 12494 SDValue FalseVal = N->getOperand(0); 12495 SDValue TrueVal = N->getOperand(1); 12496 SDValue ARMcc = N->getOperand(2); 12497 ARMCC::CondCodes CC = 12498 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12499 12500 // BFI is only available on V6T2+. 12501 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 12502 SDValue R = PerformCMOVToBFICombine(N, DAG); 12503 if (R) 12504 return R; 12505 } 12506 12507 // Simplify 12508 // mov r1, r0 12509 // cmp r1, x 12510 // mov r0, y 12511 // moveq r0, x 12512 // to 12513 // cmp r0, x 12514 // movne r0, y 12515 // 12516 // mov r1, r0 12517 // cmp r1, x 12518 // mov r0, x 12519 // movne r0, y 12520 // to 12521 // cmp r0, x 12522 // movne r0, y 12523 /// FIXME: Turn this into a target neutral optimization? 12524 SDValue Res; 12525 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 12526 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 12527 N->getOperand(3), Cmp); 12528 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 12529 SDValue ARMcc; 12530 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 12531 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 12532 N->getOperand(3), NewCmp); 12533 } 12534 12535 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 12536 // -> (cmov F T CC CPSR Cmp) 12537 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 12538 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 12539 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12540 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12541 if ((LHS0C && LHS0C->getZExtValue() == 0) && 12542 (LHS1C && LHS1C->getZExtValue() == 1) && 12543 (RHSC && RHSC->getZExtValue() == 0)) { 12544 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 12545 LHS->getOperand(2), LHS->getOperand(3), 12546 LHS->getOperand(4)); 12547 } 12548 } 12549 12550 if (!VT.isInteger()) 12551 return SDValue(); 12552 12553 // Materialize a boolean comparison for integers so we can avoid branching. 12554 if (isNullConstant(FalseVal)) { 12555 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 12556 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 12557 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 12558 // right 5 bits will make that 32 be 1, otherwise it will be 0. 12559 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 12560 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12561 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 12562 DAG.getConstant(5, dl, MVT::i32)); 12563 } else { 12564 // CMOV 0, 1, ==, (CMPZ x, y) -> 12565 // (ADDCARRY (SUB x, y), t:0, t:1) 12566 // where t = (SUBCARRY 0, (SUB x, y), 0) 12567 // 12568 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 12569 // x != y. In other words, a carry C == 1 when x == y, C == 0 12570 // otherwise. 12571 // The final ADDCARRY computes 12572 // x - y + (0 - (x - y)) + C == C 12573 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12574 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12575 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 12576 // ISD::SUBCARRY returns a borrow but we want the carry here 12577 // actually. 12578 SDValue Carry = 12579 DAG.getNode(ISD::SUB, dl, MVT::i32, 12580 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 12581 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 12582 } 12583 } else if (CC == ARMCC::NE && LHS != RHS && 12584 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 12585 // This seems pointless but will allow us to combine it further below. 12586 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUB x, y), z, !=, (CMPZ x, y) 12587 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12588 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 12589 N->getOperand(3), Cmp); 12590 } 12591 } else if (isNullConstant(TrueVal)) { 12592 if (CC == ARMCC::EQ && LHS != RHS && 12593 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 12594 // This seems pointless but will allow us to combine it further below 12595 // Note that we change == for != as this is the dual for the case above. 12596 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUB x, y), z, !=, (CMPZ x, y) 12597 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12598 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 12599 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 12600 N->getOperand(3), Cmp); 12601 } 12602 } 12603 12604 // On Thumb1, the DAG above may be further combined if z is a power of 2 12605 // (z == 2 ^ K). 12606 // CMOV (SUB x, y), z, !=, (CMPZ x, y) -> 12607 // merge t3, t4 12608 // where t1 = (SUBCARRY (SUB x, y), z, 0) 12609 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 12610 // t3 = if K != 0 then (SHL t2:0, K) else t2:0 12611 // t4 = (SUB 1, t2:1) [ we want a carry, not a borrow ] 12612 const APInt *TrueConst; 12613 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 12614 (FalseVal.getOpcode() == ISD::SUB) && (FalseVal.getOperand(0) == LHS) && 12615 (FalseVal.getOperand(1) == RHS) && 12616 (TrueConst = isPowerOf2Constant(TrueVal))) { 12617 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12618 unsigned ShiftAmount = TrueConst->logBase2(); 12619 if (ShiftAmount) 12620 TrueVal = DAG.getConstant(1, dl, VT); 12621 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 12622 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 12623 // Make it a carry, not a borrow. 12624 SDValue Carry = DAG.getNode( 12625 ISD::SUB, dl, VT, DAG.getConstant(1, dl, MVT::i32), Res.getValue(1)); 12626 Res = DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Res, Carry); 12627 12628 if (ShiftAmount) 12629 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 12630 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 12631 } 12632 12633 if (Res.getNode()) { 12634 KnownBits Known; 12635 DAG.computeKnownBits(SDValue(N,0), Known); 12636 // Capture demanded bits information that would be otherwise lost. 12637 if (Known.Zero == 0xfffffffe) 12638 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12639 DAG.getValueType(MVT::i1)); 12640 else if (Known.Zero == 0xffffff00) 12641 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12642 DAG.getValueType(MVT::i8)); 12643 else if (Known.Zero == 0xffff0000) 12644 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12645 DAG.getValueType(MVT::i16)); 12646 } 12647 12648 return Res; 12649 } 12650 12651 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 12652 DAGCombinerInfo &DCI) const { 12653 switch (N->getOpcode()) { 12654 default: break; 12655 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 12656 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 12657 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 12658 case ISD::SUB: return PerformSUBCombine(N, DCI); 12659 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 12660 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 12661 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 12662 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 12663 case ARMISD::ADDC: 12664 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 12665 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 12666 case ARMISD::BFI: return PerformBFICombine(N, DCI); 12667 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 12668 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 12669 case ISD::STORE: return PerformSTORECombine(N, DCI); 12670 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 12671 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 12672 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 12673 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 12674 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 12675 case ISD::FP_TO_SINT: 12676 case ISD::FP_TO_UINT: 12677 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 12678 case ISD::FDIV: 12679 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 12680 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 12681 case ISD::SHL: 12682 case ISD::SRA: 12683 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 12684 case ISD::SIGN_EXTEND: 12685 case ISD::ZERO_EXTEND: 12686 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 12687 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 12688 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 12689 case ISD::LOAD: return PerformLOADCombine(N, DCI); 12690 case ARMISD::VLD1DUP: 12691 case ARMISD::VLD2DUP: 12692 case ARMISD::VLD3DUP: 12693 case ARMISD::VLD4DUP: 12694 return PerformVLDCombine(N, DCI); 12695 case ARMISD::BUILD_VECTOR: 12696 return PerformARMBUILD_VECTORCombine(N, DCI); 12697 case ARMISD::SMULWB: { 12698 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12699 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12700 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12701 return SDValue(); 12702 break; 12703 } 12704 case ARMISD::SMULWT: { 12705 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12706 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12707 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12708 return SDValue(); 12709 break; 12710 } 12711 case ARMISD::SMLALBB: { 12712 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12713 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12714 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12715 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12716 return SDValue(); 12717 break; 12718 } 12719 case ARMISD::SMLALBT: { 12720 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 12721 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12722 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 12723 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12724 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 12725 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12726 return SDValue(); 12727 break; 12728 } 12729 case ARMISD::SMLALTB: { 12730 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12731 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12732 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12733 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12734 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12735 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12736 return SDValue(); 12737 break; 12738 } 12739 case ARMISD::SMLALTT: { 12740 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12741 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12742 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12743 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12744 return SDValue(); 12745 break; 12746 } 12747 case ISD::INTRINSIC_VOID: 12748 case ISD::INTRINSIC_W_CHAIN: 12749 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12750 case Intrinsic::arm_neon_vld1: 12751 case Intrinsic::arm_neon_vld2: 12752 case Intrinsic::arm_neon_vld3: 12753 case Intrinsic::arm_neon_vld4: 12754 case Intrinsic::arm_neon_vld2lane: 12755 case Intrinsic::arm_neon_vld3lane: 12756 case Intrinsic::arm_neon_vld4lane: 12757 case Intrinsic::arm_neon_vst1: 12758 case Intrinsic::arm_neon_vst2: 12759 case Intrinsic::arm_neon_vst3: 12760 case Intrinsic::arm_neon_vst4: 12761 case Intrinsic::arm_neon_vst2lane: 12762 case Intrinsic::arm_neon_vst3lane: 12763 case Intrinsic::arm_neon_vst4lane: 12764 return PerformVLDCombine(N, DCI); 12765 default: break; 12766 } 12767 break; 12768 } 12769 return SDValue(); 12770 } 12771 12772 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 12773 EVT VT) const { 12774 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 12775 } 12776 12777 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12778 unsigned, 12779 unsigned, 12780 bool *Fast) const { 12781 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 12782 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 12783 12784 switch (VT.getSimpleVT().SimpleTy) { 12785 default: 12786 return false; 12787 case MVT::i8: 12788 case MVT::i16: 12789 case MVT::i32: { 12790 // Unaligned access can use (for example) LRDB, LRDH, LDR 12791 if (AllowsUnaligned) { 12792 if (Fast) 12793 *Fast = Subtarget->hasV7Ops(); 12794 return true; 12795 } 12796 return false; 12797 } 12798 case MVT::f64: 12799 case MVT::v2f64: { 12800 // For any little-endian targets with neon, we can support unaligned ld/st 12801 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 12802 // A big-endian target may also explicitly support unaligned accesses 12803 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 12804 if (Fast) 12805 *Fast = true; 12806 return true; 12807 } 12808 return false; 12809 } 12810 } 12811 } 12812 12813 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 12814 unsigned AlignCheck) { 12815 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 12816 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 12817 } 12818 12819 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 12820 unsigned DstAlign, unsigned SrcAlign, 12821 bool IsMemset, bool ZeroMemset, 12822 bool MemcpyStrSrc, 12823 MachineFunction &MF) const { 12824 const Function &F = MF.getFunction(); 12825 12826 // See if we can use NEON instructions for this... 12827 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 12828 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 12829 bool Fast; 12830 if (Size >= 16 && 12831 (memOpAlign(SrcAlign, DstAlign, 16) || 12832 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 12833 return MVT::v2f64; 12834 } else if (Size >= 8 && 12835 (memOpAlign(SrcAlign, DstAlign, 8) || 12836 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 12837 Fast))) { 12838 return MVT::f64; 12839 } 12840 } 12841 12842 // Let the target-independent logic figure it out. 12843 return MVT::Other; 12844 } 12845 12846 // 64-bit integers are split into their high and low parts and held in two 12847 // different registers, so the trunc is free since the low register can just 12848 // be used. 12849 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 12850 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 12851 return false; 12852 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 12853 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 12854 return (SrcBits == 64 && DestBits == 32); 12855 } 12856 12857 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 12858 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 12859 !DstVT.isInteger()) 12860 return false; 12861 unsigned SrcBits = SrcVT.getSizeInBits(); 12862 unsigned DestBits = DstVT.getSizeInBits(); 12863 return (SrcBits == 64 && DestBits == 32); 12864 } 12865 12866 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12867 if (Val.getOpcode() != ISD::LOAD) 12868 return false; 12869 12870 EVT VT1 = Val.getValueType(); 12871 if (!VT1.isSimple() || !VT1.isInteger() || 12872 !VT2.isSimple() || !VT2.isInteger()) 12873 return false; 12874 12875 switch (VT1.getSimpleVT().SimpleTy) { 12876 default: break; 12877 case MVT::i1: 12878 case MVT::i8: 12879 case MVT::i16: 12880 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 12881 return true; 12882 } 12883 12884 return false; 12885 } 12886 12887 bool ARMTargetLowering::isFNegFree(EVT VT) const { 12888 if (!VT.isSimple()) 12889 return false; 12890 12891 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 12892 // negate values directly (fneg is free). So, we don't want to let the DAG 12893 // combiner rewrite fneg into xors and some other instructions. For f16 and 12894 // FullFP16 argument passing, some bitcast nodes may be introduced, 12895 // triggering this DAG combine rewrite, so we are avoiding that with this. 12896 switch (VT.getSimpleVT().SimpleTy) { 12897 default: break; 12898 case MVT::f16: 12899 return Subtarget->hasFullFP16(); 12900 } 12901 12902 return false; 12903 } 12904 12905 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 12906 EVT VT = ExtVal.getValueType(); 12907 12908 if (!isTypeLegal(VT)) 12909 return false; 12910 12911 // Don't create a loadext if we can fold the extension into a wide/long 12912 // instruction. 12913 // If there's more than one user instruction, the loadext is desirable no 12914 // matter what. There can be two uses by the same instruction. 12915 if (ExtVal->use_empty() || 12916 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 12917 return true; 12918 12919 SDNode *U = *ExtVal->use_begin(); 12920 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 12921 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 12922 return false; 12923 12924 return true; 12925 } 12926 12927 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 12928 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12929 return false; 12930 12931 if (!isTypeLegal(EVT::getEVT(Ty1))) 12932 return false; 12933 12934 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 12935 12936 // Assuming the caller doesn't have a zeroext or signext return parameter, 12937 // truncation all the way down to i1 is valid. 12938 return true; 12939 } 12940 12941 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 12942 const AddrMode &AM, Type *Ty, 12943 unsigned AS) const { 12944 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 12945 if (Subtarget->hasFPAO()) 12946 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 12947 return 0; 12948 } 12949 return -1; 12950 } 12951 12952 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 12953 if (V < 0) 12954 return false; 12955 12956 unsigned Scale = 1; 12957 switch (VT.getSimpleVT().SimpleTy) { 12958 default: return false; 12959 case MVT::i1: 12960 case MVT::i8: 12961 // Scale == 1; 12962 break; 12963 case MVT::i16: 12964 // Scale == 2; 12965 Scale = 2; 12966 break; 12967 case MVT::i32: 12968 // Scale == 4; 12969 Scale = 4; 12970 break; 12971 } 12972 12973 if ((V & (Scale - 1)) != 0) 12974 return false; 12975 V /= Scale; 12976 return V == (V & ((1LL << 5) - 1)); 12977 } 12978 12979 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 12980 const ARMSubtarget *Subtarget) { 12981 bool isNeg = false; 12982 if (V < 0) { 12983 isNeg = true; 12984 V = - V; 12985 } 12986 12987 switch (VT.getSimpleVT().SimpleTy) { 12988 default: return false; 12989 case MVT::i1: 12990 case MVT::i8: 12991 case MVT::i16: 12992 case MVT::i32: 12993 // + imm12 or - imm8 12994 if (isNeg) 12995 return V == (V & ((1LL << 8) - 1)); 12996 return V == (V & ((1LL << 12) - 1)); 12997 case MVT::f32: 12998 case MVT::f64: 12999 // Same as ARM mode. FIXME: NEON? 13000 if (!Subtarget->hasVFP2()) 13001 return false; 13002 if ((V & 3) != 0) 13003 return false; 13004 V >>= 2; 13005 return V == (V & ((1LL << 8) - 1)); 13006 } 13007 } 13008 13009 /// isLegalAddressImmediate - Return true if the integer value can be used 13010 /// as the offset of the target addressing mode for load / store of the 13011 /// given type. 13012 static bool isLegalAddressImmediate(int64_t V, EVT VT, 13013 const ARMSubtarget *Subtarget) { 13014 if (V == 0) 13015 return true; 13016 13017 if (!VT.isSimple()) 13018 return false; 13019 13020 if (Subtarget->isThumb1Only()) 13021 return isLegalT1AddressImmediate(V, VT); 13022 else if (Subtarget->isThumb2()) 13023 return isLegalT2AddressImmediate(V, VT, Subtarget); 13024 13025 // ARM mode. 13026 if (V < 0) 13027 V = - V; 13028 switch (VT.getSimpleVT().SimpleTy) { 13029 default: return false; 13030 case MVT::i1: 13031 case MVT::i8: 13032 case MVT::i32: 13033 // +- imm12 13034 return V == (V & ((1LL << 12) - 1)); 13035 case MVT::i16: 13036 // +- imm8 13037 return V == (V & ((1LL << 8) - 1)); 13038 case MVT::f32: 13039 case MVT::f64: 13040 if (!Subtarget->hasVFP2()) // FIXME: NEON? 13041 return false; 13042 if ((V & 3) != 0) 13043 return false; 13044 V >>= 2; 13045 return V == (V & ((1LL << 8) - 1)); 13046 } 13047 } 13048 13049 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 13050 EVT VT) const { 13051 int Scale = AM.Scale; 13052 if (Scale < 0) 13053 return false; 13054 13055 switch (VT.getSimpleVT().SimpleTy) { 13056 default: return false; 13057 case MVT::i1: 13058 case MVT::i8: 13059 case MVT::i16: 13060 case MVT::i32: 13061 if (Scale == 1) 13062 return true; 13063 // r + r << imm 13064 Scale = Scale & ~1; 13065 return Scale == 2 || Scale == 4 || Scale == 8; 13066 case MVT::i64: 13067 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 13068 // version in Thumb mode. 13069 // r + r 13070 if (Scale == 1) 13071 return true; 13072 // r * 2 (this can be lowered to r + r). 13073 if (!AM.HasBaseReg && Scale == 2) 13074 return true; 13075 return false; 13076 case MVT::isVoid: 13077 // Note, we allow "void" uses (basically, uses that aren't loads or 13078 // stores), because arm allows folding a scale into many arithmetic 13079 // operations. This should be made more precise and revisited later. 13080 13081 // Allow r << imm, but the imm has to be a multiple of two. 13082 if (Scale & 1) return false; 13083 return isPowerOf2_32(Scale); 13084 } 13085 } 13086 13087 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 13088 EVT VT) const { 13089 const int Scale = AM.Scale; 13090 13091 // Negative scales are not supported in Thumb1. 13092 if (Scale < 0) 13093 return false; 13094 13095 // Thumb1 addressing modes do not support register scaling excepting the 13096 // following cases: 13097 // 1. Scale == 1 means no scaling. 13098 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 13099 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 13100 } 13101 13102 /// isLegalAddressingMode - Return true if the addressing mode represented 13103 /// by AM is legal for this target, for a load/store of the specified type. 13104 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13105 const AddrMode &AM, Type *Ty, 13106 unsigned AS, Instruction *I) const { 13107 EVT VT = getValueType(DL, Ty, true); 13108 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 13109 return false; 13110 13111 // Can never fold addr of global into load/store. 13112 if (AM.BaseGV) 13113 return false; 13114 13115 switch (AM.Scale) { 13116 case 0: // no scale reg, must be "r+i" or "r", or "i". 13117 break; 13118 default: 13119 // ARM doesn't support any R+R*scale+imm addr modes. 13120 if (AM.BaseOffs) 13121 return false; 13122 13123 if (!VT.isSimple()) 13124 return false; 13125 13126 if (Subtarget->isThumb1Only()) 13127 return isLegalT1ScaledAddressingMode(AM, VT); 13128 13129 if (Subtarget->isThumb2()) 13130 return isLegalT2ScaledAddressingMode(AM, VT); 13131 13132 int Scale = AM.Scale; 13133 switch (VT.getSimpleVT().SimpleTy) { 13134 default: return false; 13135 case MVT::i1: 13136 case MVT::i8: 13137 case MVT::i32: 13138 if (Scale < 0) Scale = -Scale; 13139 if (Scale == 1) 13140 return true; 13141 // r + r << imm 13142 return isPowerOf2_32(Scale & ~1); 13143 case MVT::i16: 13144 case MVT::i64: 13145 // r +/- r 13146 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 13147 return true; 13148 // r * 2 (this can be lowered to r + r). 13149 if (!AM.HasBaseReg && Scale == 2) 13150 return true; 13151 return false; 13152 13153 case MVT::isVoid: 13154 // Note, we allow "void" uses (basically, uses that aren't loads or 13155 // stores), because arm allows folding a scale into many arithmetic 13156 // operations. This should be made more precise and revisited later. 13157 13158 // Allow r << imm, but the imm has to be a multiple of two. 13159 if (Scale & 1) return false; 13160 return isPowerOf2_32(Scale); 13161 } 13162 } 13163 return true; 13164 } 13165 13166 /// isLegalICmpImmediate - Return true if the specified immediate is legal 13167 /// icmp immediate, that is the target has icmp instructions which can compare 13168 /// a register against the immediate without having to materialize the 13169 /// immediate into a register. 13170 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13171 // Thumb2 and ARM modes can use cmn for negative immediates. 13172 if (!Subtarget->isThumb()) 13173 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 13174 if (Subtarget->isThumb2()) 13175 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 13176 // Thumb1 doesn't have cmn, and only 8-bit immediates. 13177 return Imm >= 0 && Imm <= 255; 13178 } 13179 13180 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 13181 /// *or sub* immediate, that is the target has add or sub instructions which can 13182 /// add a register with the immediate without having to materialize the 13183 /// immediate into a register. 13184 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13185 // Same encoding for add/sub, just flip the sign. 13186 int64_t AbsImm = std::abs(Imm); 13187 if (!Subtarget->isThumb()) 13188 return ARM_AM::getSOImmVal(AbsImm) != -1; 13189 if (Subtarget->isThumb2()) 13190 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 13191 // Thumb1 only has 8-bit unsigned immediate. 13192 return AbsImm >= 0 && AbsImm <= 255; 13193 } 13194 13195 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 13196 bool isSEXTLoad, SDValue &Base, 13197 SDValue &Offset, bool &isInc, 13198 SelectionDAG &DAG) { 13199 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13200 return false; 13201 13202 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 13203 // AddressingMode 3 13204 Base = Ptr->getOperand(0); 13205 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13206 int RHSC = (int)RHS->getZExtValue(); 13207 if (RHSC < 0 && RHSC > -256) { 13208 assert(Ptr->getOpcode() == ISD::ADD); 13209 isInc = false; 13210 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13211 return true; 13212 } 13213 } 13214 isInc = (Ptr->getOpcode() == ISD::ADD); 13215 Offset = Ptr->getOperand(1); 13216 return true; 13217 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 13218 // AddressingMode 2 13219 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13220 int RHSC = (int)RHS->getZExtValue(); 13221 if (RHSC < 0 && RHSC > -0x1000) { 13222 assert(Ptr->getOpcode() == ISD::ADD); 13223 isInc = false; 13224 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13225 Base = Ptr->getOperand(0); 13226 return true; 13227 } 13228 } 13229 13230 if (Ptr->getOpcode() == ISD::ADD) { 13231 isInc = true; 13232 ARM_AM::ShiftOpc ShOpcVal= 13233 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 13234 if (ShOpcVal != ARM_AM::no_shift) { 13235 Base = Ptr->getOperand(1); 13236 Offset = Ptr->getOperand(0); 13237 } else { 13238 Base = Ptr->getOperand(0); 13239 Offset = Ptr->getOperand(1); 13240 } 13241 return true; 13242 } 13243 13244 isInc = (Ptr->getOpcode() == ISD::ADD); 13245 Base = Ptr->getOperand(0); 13246 Offset = Ptr->getOperand(1); 13247 return true; 13248 } 13249 13250 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 13251 return false; 13252 } 13253 13254 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 13255 bool isSEXTLoad, SDValue &Base, 13256 SDValue &Offset, bool &isInc, 13257 SelectionDAG &DAG) { 13258 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13259 return false; 13260 13261 Base = Ptr->getOperand(0); 13262 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13263 int RHSC = (int)RHS->getZExtValue(); 13264 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 13265 assert(Ptr->getOpcode() == ISD::ADD); 13266 isInc = false; 13267 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13268 return true; 13269 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 13270 isInc = Ptr->getOpcode() == ISD::ADD; 13271 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13272 return true; 13273 } 13274 } 13275 13276 return false; 13277 } 13278 13279 /// getPreIndexedAddressParts - returns true by value, base pointer and 13280 /// offset pointer and addressing mode by reference if the node's address 13281 /// can be legally represented as pre-indexed load / store address. 13282 bool 13283 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 13284 SDValue &Offset, 13285 ISD::MemIndexedMode &AM, 13286 SelectionDAG &DAG) const { 13287 if (Subtarget->isThumb1Only()) 13288 return false; 13289 13290 EVT VT; 13291 SDValue Ptr; 13292 bool isSEXTLoad = false; 13293 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13294 Ptr = LD->getBasePtr(); 13295 VT = LD->getMemoryVT(); 13296 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13297 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13298 Ptr = ST->getBasePtr(); 13299 VT = ST->getMemoryVT(); 13300 } else 13301 return false; 13302 13303 bool isInc; 13304 bool isLegal = false; 13305 if (Subtarget->isThumb2()) 13306 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13307 Offset, isInc, DAG); 13308 else 13309 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13310 Offset, isInc, DAG); 13311 if (!isLegal) 13312 return false; 13313 13314 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 13315 return true; 13316 } 13317 13318 /// getPostIndexedAddressParts - returns true by value, base pointer and 13319 /// offset pointer and addressing mode by reference if this node can be 13320 /// combined with a load / store to form a post-indexed load / store. 13321 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 13322 SDValue &Base, 13323 SDValue &Offset, 13324 ISD::MemIndexedMode &AM, 13325 SelectionDAG &DAG) const { 13326 EVT VT; 13327 SDValue Ptr; 13328 bool isSEXTLoad = false, isNonExt; 13329 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13330 VT = LD->getMemoryVT(); 13331 Ptr = LD->getBasePtr(); 13332 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13333 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 13334 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13335 VT = ST->getMemoryVT(); 13336 Ptr = ST->getBasePtr(); 13337 isNonExt = !ST->isTruncatingStore(); 13338 } else 13339 return false; 13340 13341 if (Subtarget->isThumb1Only()) { 13342 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 13343 // must be non-extending/truncating, i32, with an offset of 4. 13344 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 13345 if (Op->getOpcode() != ISD::ADD || !isNonExt) 13346 return false; 13347 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 13348 if (!RHS || RHS->getZExtValue() != 4) 13349 return false; 13350 13351 Offset = Op->getOperand(1); 13352 Base = Op->getOperand(0); 13353 AM = ISD::POST_INC; 13354 return true; 13355 } 13356 13357 bool isInc; 13358 bool isLegal = false; 13359 if (Subtarget->isThumb2()) 13360 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13361 isInc, DAG); 13362 else 13363 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13364 isInc, DAG); 13365 if (!isLegal) 13366 return false; 13367 13368 if (Ptr != Base) { 13369 // Swap base ptr and offset to catch more post-index load / store when 13370 // it's legal. In Thumb2 mode, offset must be an immediate. 13371 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 13372 !Subtarget->isThumb2()) 13373 std::swap(Base, Offset); 13374 13375 // Post-indexed load / store update the base pointer. 13376 if (Ptr != Base) 13377 return false; 13378 } 13379 13380 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 13381 return true; 13382 } 13383 13384 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13385 KnownBits &Known, 13386 const APInt &DemandedElts, 13387 const SelectionDAG &DAG, 13388 unsigned Depth) const { 13389 unsigned BitWidth = Known.getBitWidth(); 13390 Known.resetAll(); 13391 switch (Op.getOpcode()) { 13392 default: break; 13393 case ARMISD::ADDC: 13394 case ARMISD::ADDE: 13395 case ARMISD::SUBC: 13396 case ARMISD::SUBE: 13397 // Special cases when we convert a carry to a boolean. 13398 if (Op.getResNo() == 0) { 13399 SDValue LHS = Op.getOperand(0); 13400 SDValue RHS = Op.getOperand(1); 13401 // (ADDE 0, 0, C) will give us a single bit. 13402 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 13403 isNullConstant(RHS)) { 13404 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 13405 return; 13406 } 13407 } 13408 break; 13409 case ARMISD::CMOV: { 13410 // Bits are known zero/one if known on the LHS and RHS. 13411 DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1); 13412 if (Known.isUnknown()) 13413 return; 13414 13415 KnownBits KnownRHS; 13416 DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1); 13417 Known.Zero &= KnownRHS.Zero; 13418 Known.One &= KnownRHS.One; 13419 return; 13420 } 13421 case ISD::INTRINSIC_W_CHAIN: { 13422 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 13423 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 13424 switch (IntID) { 13425 default: return; 13426 case Intrinsic::arm_ldaex: 13427 case Intrinsic::arm_ldrex: { 13428 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 13429 unsigned MemBits = VT.getScalarSizeInBits(); 13430 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 13431 return; 13432 } 13433 } 13434 } 13435 case ARMISD::BFI: { 13436 // Conservatively, we can recurse down the first operand 13437 // and just mask out all affected bits. 13438 DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1); 13439 13440 // The operand to BFI is already a mask suitable for removing the bits it 13441 // sets. 13442 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 13443 const APInt &Mask = CI->getAPIntValue(); 13444 Known.Zero &= Mask; 13445 Known.One &= Mask; 13446 return; 13447 } 13448 } 13449 } 13450 13451 //===----------------------------------------------------------------------===// 13452 // ARM Inline Assembly Support 13453 //===----------------------------------------------------------------------===// 13454 13455 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 13456 // Looking for "rev" which is V6+. 13457 if (!Subtarget->hasV6Ops()) 13458 return false; 13459 13460 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 13461 std::string AsmStr = IA->getAsmString(); 13462 SmallVector<StringRef, 4> AsmPieces; 13463 SplitString(AsmStr, AsmPieces, ";\n"); 13464 13465 switch (AsmPieces.size()) { 13466 default: return false; 13467 case 1: 13468 AsmStr = AsmPieces[0]; 13469 AsmPieces.clear(); 13470 SplitString(AsmStr, AsmPieces, " \t,"); 13471 13472 // rev $0, $1 13473 if (AsmPieces.size() == 3 && 13474 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 13475 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 13476 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 13477 if (Ty && Ty->getBitWidth() == 32) 13478 return IntrinsicLowering::LowerToByteSwap(CI); 13479 } 13480 break; 13481 } 13482 13483 return false; 13484 } 13485 13486 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 13487 // At this point, we have to lower this constraint to something else, so we 13488 // lower it to an "r" or "w". However, by doing this we will force the result 13489 // to be in register, while the X constraint is much more permissive. 13490 // 13491 // Although we are correct (we are free to emit anything, without 13492 // constraints), we might break use cases that would expect us to be more 13493 // efficient and emit something else. 13494 if (!Subtarget->hasVFP2()) 13495 return "r"; 13496 if (ConstraintVT.isFloatingPoint()) 13497 return "w"; 13498 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 13499 (ConstraintVT.getSizeInBits() == 64 || 13500 ConstraintVT.getSizeInBits() == 128)) 13501 return "w"; 13502 13503 return "r"; 13504 } 13505 13506 /// getConstraintType - Given a constraint letter, return the type of 13507 /// constraint it is for this target. 13508 ARMTargetLowering::ConstraintType 13509 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 13510 if (Constraint.size() == 1) { 13511 switch (Constraint[0]) { 13512 default: break; 13513 case 'l': return C_RegisterClass; 13514 case 'w': return C_RegisterClass; 13515 case 'h': return C_RegisterClass; 13516 case 'x': return C_RegisterClass; 13517 case 't': return C_RegisterClass; 13518 case 'j': return C_Other; // Constant for movw. 13519 // An address with a single base register. Due to the way we 13520 // currently handle addresses it is the same as an 'r' memory constraint. 13521 case 'Q': return C_Memory; 13522 } 13523 } else if (Constraint.size() == 2) { 13524 switch (Constraint[0]) { 13525 default: break; 13526 // All 'U+' constraints are addresses. 13527 case 'U': return C_Memory; 13528 } 13529 } 13530 return TargetLowering::getConstraintType(Constraint); 13531 } 13532 13533 /// Examine constraint type and operand type and determine a weight value. 13534 /// This object must already have been set up with the operand type 13535 /// and the current alternative constraint selected. 13536 TargetLowering::ConstraintWeight 13537 ARMTargetLowering::getSingleConstraintMatchWeight( 13538 AsmOperandInfo &info, const char *constraint) const { 13539 ConstraintWeight weight = CW_Invalid; 13540 Value *CallOperandVal = info.CallOperandVal; 13541 // If we don't have a value, we can't do a match, 13542 // but allow it at the lowest weight. 13543 if (!CallOperandVal) 13544 return CW_Default; 13545 Type *type = CallOperandVal->getType(); 13546 // Look at the constraint type. 13547 switch (*constraint) { 13548 default: 13549 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13550 break; 13551 case 'l': 13552 if (type->isIntegerTy()) { 13553 if (Subtarget->isThumb()) 13554 weight = CW_SpecificReg; 13555 else 13556 weight = CW_Register; 13557 } 13558 break; 13559 case 'w': 13560 if (type->isFloatingPointTy()) 13561 weight = CW_Register; 13562 break; 13563 } 13564 return weight; 13565 } 13566 13567 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 13568 13569 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 13570 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 13571 if (Constraint.size() == 1) { 13572 // GCC ARM Constraint Letters 13573 switch (Constraint[0]) { 13574 case 'l': // Low regs or general regs. 13575 if (Subtarget->isThumb()) 13576 return RCPair(0U, &ARM::tGPRRegClass); 13577 return RCPair(0U, &ARM::GPRRegClass); 13578 case 'h': // High regs or no regs. 13579 if (Subtarget->isThumb()) 13580 return RCPair(0U, &ARM::hGPRRegClass); 13581 break; 13582 case 'r': 13583 if (Subtarget->isThumb1Only()) 13584 return RCPair(0U, &ARM::tGPRRegClass); 13585 return RCPair(0U, &ARM::GPRRegClass); 13586 case 'w': 13587 if (VT == MVT::Other) 13588 break; 13589 if (VT == MVT::f32) 13590 return RCPair(0U, &ARM::SPRRegClass); 13591 if (VT.getSizeInBits() == 64) 13592 return RCPair(0U, &ARM::DPRRegClass); 13593 if (VT.getSizeInBits() == 128) 13594 return RCPair(0U, &ARM::QPRRegClass); 13595 break; 13596 case 'x': 13597 if (VT == MVT::Other) 13598 break; 13599 if (VT == MVT::f32) 13600 return RCPair(0U, &ARM::SPR_8RegClass); 13601 if (VT.getSizeInBits() == 64) 13602 return RCPair(0U, &ARM::DPR_8RegClass); 13603 if (VT.getSizeInBits() == 128) 13604 return RCPair(0U, &ARM::QPR_8RegClass); 13605 break; 13606 case 't': 13607 if (VT == MVT::Other) 13608 break; 13609 if (VT == MVT::f32 || VT == MVT::i32) 13610 return RCPair(0U, &ARM::SPRRegClass); 13611 if (VT.getSizeInBits() == 64) 13612 return RCPair(0U, &ARM::DPR_VFP2RegClass); 13613 if (VT.getSizeInBits() == 128) 13614 return RCPair(0U, &ARM::QPR_VFP2RegClass); 13615 break; 13616 } 13617 } 13618 if (StringRef("{cc}").equals_lower(Constraint)) 13619 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 13620 13621 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13622 } 13623 13624 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13625 /// vector. If it is invalid, don't add anything to Ops. 13626 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13627 std::string &Constraint, 13628 std::vector<SDValue>&Ops, 13629 SelectionDAG &DAG) const { 13630 SDValue Result; 13631 13632 // Currently only support length 1 constraints. 13633 if (Constraint.length() != 1) return; 13634 13635 char ConstraintLetter = Constraint[0]; 13636 switch (ConstraintLetter) { 13637 default: break; 13638 case 'j': 13639 case 'I': case 'J': case 'K': case 'L': 13640 case 'M': case 'N': case 'O': 13641 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 13642 if (!C) 13643 return; 13644 13645 int64_t CVal64 = C->getSExtValue(); 13646 int CVal = (int) CVal64; 13647 // None of these constraints allow values larger than 32 bits. Check 13648 // that the value fits in an int. 13649 if (CVal != CVal64) 13650 return; 13651 13652 switch (ConstraintLetter) { 13653 case 'j': 13654 // Constant suitable for movw, must be between 0 and 13655 // 65535. 13656 if (Subtarget->hasV6T2Ops()) 13657 if (CVal >= 0 && CVal <= 65535) 13658 break; 13659 return; 13660 case 'I': 13661 if (Subtarget->isThumb1Only()) { 13662 // This must be a constant between 0 and 255, for ADD 13663 // immediates. 13664 if (CVal >= 0 && CVal <= 255) 13665 break; 13666 } else if (Subtarget->isThumb2()) { 13667 // A constant that can be used as an immediate value in a 13668 // data-processing instruction. 13669 if (ARM_AM::getT2SOImmVal(CVal) != -1) 13670 break; 13671 } else { 13672 // A constant that can be used as an immediate value in a 13673 // data-processing instruction. 13674 if (ARM_AM::getSOImmVal(CVal) != -1) 13675 break; 13676 } 13677 return; 13678 13679 case 'J': 13680 if (Subtarget->isThumb1Only()) { 13681 // This must be a constant between -255 and -1, for negated ADD 13682 // immediates. This can be used in GCC with an "n" modifier that 13683 // prints the negated value, for use with SUB instructions. It is 13684 // not useful otherwise but is implemented for compatibility. 13685 if (CVal >= -255 && CVal <= -1) 13686 break; 13687 } else { 13688 // This must be a constant between -4095 and 4095. It is not clear 13689 // what this constraint is intended for. Implemented for 13690 // compatibility with GCC. 13691 if (CVal >= -4095 && CVal <= 4095) 13692 break; 13693 } 13694 return; 13695 13696 case 'K': 13697 if (Subtarget->isThumb1Only()) { 13698 // A 32-bit value where only one byte has a nonzero value. Exclude 13699 // zero to match GCC. This constraint is used by GCC internally for 13700 // constants that can be loaded with a move/shift combination. 13701 // It is not useful otherwise but is implemented for compatibility. 13702 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 13703 break; 13704 } else if (Subtarget->isThumb2()) { 13705 // A constant whose bitwise inverse can be used as an immediate 13706 // value in a data-processing instruction. This can be used in GCC 13707 // with a "B" modifier that prints the inverted value, for use with 13708 // BIC and MVN instructions. It is not useful otherwise but is 13709 // implemented for compatibility. 13710 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 13711 break; 13712 } else { 13713 // A constant whose bitwise inverse can be used as an immediate 13714 // value in a data-processing instruction. This can be used in GCC 13715 // with a "B" modifier that prints the inverted value, for use with 13716 // BIC and MVN instructions. It is not useful otherwise but is 13717 // implemented for compatibility. 13718 if (ARM_AM::getSOImmVal(~CVal) != -1) 13719 break; 13720 } 13721 return; 13722 13723 case 'L': 13724 if (Subtarget->isThumb1Only()) { 13725 // This must be a constant between -7 and 7, 13726 // for 3-operand ADD/SUB immediate instructions. 13727 if (CVal >= -7 && CVal < 7) 13728 break; 13729 } else if (Subtarget->isThumb2()) { 13730 // A constant whose negation can be used as an immediate value in a 13731 // data-processing instruction. This can be used in GCC with an "n" 13732 // modifier that prints the negated value, for use with SUB 13733 // instructions. It is not useful otherwise but is implemented for 13734 // compatibility. 13735 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 13736 break; 13737 } else { 13738 // A constant whose negation can be used as an immediate value in a 13739 // data-processing instruction. This can be used in GCC with an "n" 13740 // modifier that prints the negated value, for use with SUB 13741 // instructions. It is not useful otherwise but is implemented for 13742 // compatibility. 13743 if (ARM_AM::getSOImmVal(-CVal) != -1) 13744 break; 13745 } 13746 return; 13747 13748 case 'M': 13749 if (Subtarget->isThumb1Only()) { 13750 // This must be a multiple of 4 between 0 and 1020, for 13751 // ADD sp + immediate. 13752 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 13753 break; 13754 } else { 13755 // A power of two or a constant between 0 and 32. This is used in 13756 // GCC for the shift amount on shifted register operands, but it is 13757 // useful in general for any shift amounts. 13758 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 13759 break; 13760 } 13761 return; 13762 13763 case 'N': 13764 if (Subtarget->isThumb()) { // FIXME thumb2 13765 // This must be a constant between 0 and 31, for shift amounts. 13766 if (CVal >= 0 && CVal <= 31) 13767 break; 13768 } 13769 return; 13770 13771 case 'O': 13772 if (Subtarget->isThumb()) { // FIXME thumb2 13773 // This must be a multiple of 4 between -508 and 508, for 13774 // ADD/SUB sp = sp + immediate. 13775 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 13776 break; 13777 } 13778 return; 13779 } 13780 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 13781 break; 13782 } 13783 13784 if (Result.getNode()) { 13785 Ops.push_back(Result); 13786 return; 13787 } 13788 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13789 } 13790 13791 static RTLIB::Libcall getDivRemLibcall( 13792 const SDNode *N, MVT::SimpleValueType SVT) { 13793 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13794 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13795 "Unhandled Opcode in getDivRemLibcall"); 13796 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13797 N->getOpcode() == ISD::SREM; 13798 RTLIB::Libcall LC; 13799 switch (SVT) { 13800 default: llvm_unreachable("Unexpected request for libcall!"); 13801 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 13802 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 13803 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 13804 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 13805 } 13806 return LC; 13807 } 13808 13809 static TargetLowering::ArgListTy getDivRemArgList( 13810 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 13811 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13812 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13813 "Unhandled Opcode in getDivRemArgList"); 13814 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13815 N->getOpcode() == ISD::SREM; 13816 TargetLowering::ArgListTy Args; 13817 TargetLowering::ArgListEntry Entry; 13818 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13819 EVT ArgVT = N->getOperand(i).getValueType(); 13820 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 13821 Entry.Node = N->getOperand(i); 13822 Entry.Ty = ArgTy; 13823 Entry.IsSExt = isSigned; 13824 Entry.IsZExt = !isSigned; 13825 Args.push_back(Entry); 13826 } 13827 if (Subtarget->isTargetWindows() && Args.size() >= 2) 13828 std::swap(Args[0], Args[1]); 13829 return Args; 13830 } 13831 13832 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 13833 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 13834 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 13835 Subtarget->isTargetWindows()) && 13836 "Register-based DivRem lowering only"); 13837 unsigned Opcode = Op->getOpcode(); 13838 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 13839 "Invalid opcode for Div/Rem lowering"); 13840 bool isSigned = (Opcode == ISD::SDIVREM); 13841 EVT VT = Op->getValueType(0); 13842 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 13843 SDLoc dl(Op); 13844 13845 // If the target has hardware divide, use divide + multiply + subtract: 13846 // div = a / b 13847 // rem = a - b * div 13848 // return {div, rem} 13849 // This should be lowered into UDIV/SDIV + MLS later on. 13850 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 13851 : Subtarget->hasDivideInARMMode(); 13852 if (hasDivide && Op->getValueType(0).isSimple() && 13853 Op->getSimpleValueType(0) == MVT::i32) { 13854 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 13855 const SDValue Dividend = Op->getOperand(0); 13856 const SDValue Divisor = Op->getOperand(1); 13857 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 13858 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 13859 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 13860 13861 SDValue Values[2] = {Div, Rem}; 13862 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 13863 } 13864 13865 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 13866 VT.getSimpleVT().SimpleTy); 13867 SDValue InChain = DAG.getEntryNode(); 13868 13869 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 13870 DAG.getContext(), 13871 Subtarget); 13872 13873 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13874 getPointerTy(DAG.getDataLayout())); 13875 13876 Type *RetTy = StructType::get(Ty, Ty); 13877 13878 if (Subtarget->isTargetWindows()) 13879 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 13880 13881 TargetLowering::CallLoweringInfo CLI(DAG); 13882 CLI.setDebugLoc(dl).setChain(InChain) 13883 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 13884 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 13885 13886 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 13887 return CallInfo.first; 13888 } 13889 13890 // Lowers REM using divmod helpers 13891 // see RTABI section 4.2/4.3 13892 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 13893 // Build return types (div and rem) 13894 std::vector<Type*> RetTyParams; 13895 Type *RetTyElement; 13896 13897 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 13898 default: llvm_unreachable("Unexpected request for libcall!"); 13899 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 13900 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 13901 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 13902 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 13903 } 13904 13905 RetTyParams.push_back(RetTyElement); 13906 RetTyParams.push_back(RetTyElement); 13907 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 13908 Type *RetTy = StructType::get(*DAG.getContext(), ret); 13909 13910 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 13911 SimpleTy); 13912 SDValue InChain = DAG.getEntryNode(); 13913 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 13914 Subtarget); 13915 bool isSigned = N->getOpcode() == ISD::SREM; 13916 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13917 getPointerTy(DAG.getDataLayout())); 13918 13919 if (Subtarget->isTargetWindows()) 13920 InChain = WinDBZCheckDenominator(DAG, N, InChain); 13921 13922 // Lower call 13923 CallLoweringInfo CLI(DAG); 13924 CLI.setChain(InChain) 13925 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 13926 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 13927 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 13928 13929 // Return second (rem) result operand (first contains div) 13930 SDNode *ResNode = CallResult.first.getNode(); 13931 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 13932 return ResNode->getOperand(1); 13933 } 13934 13935 SDValue 13936 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 13937 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 13938 SDLoc DL(Op); 13939 13940 // Get the inputs. 13941 SDValue Chain = Op.getOperand(0); 13942 SDValue Size = Op.getOperand(1); 13943 13944 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 13945 DAG.getConstant(2, DL, MVT::i32)); 13946 13947 SDValue Flag; 13948 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 13949 Flag = Chain.getValue(1); 13950 13951 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 13952 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 13953 13954 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 13955 Chain = NewSP.getValue(1); 13956 13957 SDValue Ops[2] = { NewSP, Chain }; 13958 return DAG.getMergeValues(Ops, DL); 13959 } 13960 13961 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 13962 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 13963 "Unexpected type for custom-lowering FP_EXTEND"); 13964 13965 RTLIB::Libcall LC; 13966 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 13967 13968 SDValue SrcVal = Op.getOperand(0); 13969 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13970 SDLoc(Op)).first; 13971 } 13972 13973 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 13974 assert(Op.getOperand(0).getValueType() == MVT::f64 && 13975 Subtarget->isFPOnlySP() && 13976 "Unexpected type for custom-lowering FP_ROUND"); 13977 13978 RTLIB::Libcall LC; 13979 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 13980 13981 SDValue SrcVal = Op.getOperand(0); 13982 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13983 SDLoc(Op)).first; 13984 } 13985 13986 bool 13987 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13988 // The ARM target isn't yet aware of offsets. 13989 return false; 13990 } 13991 13992 bool ARM::isBitFieldInvertedMask(unsigned v) { 13993 if (v == 0xffffffff) 13994 return false; 13995 13996 // there can be 1's on either or both "outsides", all the "inside" 13997 // bits must be 0's 13998 return isShiftedMask_32(~v); 13999 } 14000 14001 /// isFPImmLegal - Returns true if the target can instruction select the 14002 /// specified FP immediate natively. If false, the legalizer will 14003 /// materialize the FP immediate as a load from a constant pool. 14004 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 14005 if (!Subtarget->hasVFP3()) 14006 return false; 14007 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 14008 return ARM_AM::getFP16Imm(Imm) != -1; 14009 if (VT == MVT::f32) 14010 return ARM_AM::getFP32Imm(Imm) != -1; 14011 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 14012 return ARM_AM::getFP64Imm(Imm) != -1; 14013 return false; 14014 } 14015 14016 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 14017 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 14018 /// specified in the intrinsic calls. 14019 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14020 const CallInst &I, 14021 MachineFunction &MF, 14022 unsigned Intrinsic) const { 14023 switch (Intrinsic) { 14024 case Intrinsic::arm_neon_vld1: 14025 case Intrinsic::arm_neon_vld2: 14026 case Intrinsic::arm_neon_vld3: 14027 case Intrinsic::arm_neon_vld4: 14028 case Intrinsic::arm_neon_vld2lane: 14029 case Intrinsic::arm_neon_vld3lane: 14030 case Intrinsic::arm_neon_vld4lane: { 14031 Info.opc = ISD::INTRINSIC_W_CHAIN; 14032 // Conservatively set memVT to the entire set of vectors loaded. 14033 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14034 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14035 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14036 Info.ptrVal = I.getArgOperand(0); 14037 Info.offset = 0; 14038 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14039 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14040 // volatile loads with NEON intrinsics not supported 14041 Info.flags = MachineMemOperand::MOLoad; 14042 return true; 14043 } 14044 case Intrinsic::arm_neon_vst1: 14045 case Intrinsic::arm_neon_vst2: 14046 case Intrinsic::arm_neon_vst3: 14047 case Intrinsic::arm_neon_vst4: 14048 case Intrinsic::arm_neon_vst2lane: 14049 case Intrinsic::arm_neon_vst3lane: 14050 case Intrinsic::arm_neon_vst4lane: { 14051 Info.opc = ISD::INTRINSIC_VOID; 14052 // Conservatively set memVT to the entire set of vectors stored. 14053 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14054 unsigned NumElts = 0; 14055 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14056 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14057 if (!ArgTy->isVectorTy()) 14058 break; 14059 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14060 } 14061 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14062 Info.ptrVal = I.getArgOperand(0); 14063 Info.offset = 0; 14064 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14065 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14066 // volatile stores with NEON intrinsics not supported 14067 Info.flags = MachineMemOperand::MOStore; 14068 return true; 14069 } 14070 case Intrinsic::arm_ldaex: 14071 case Intrinsic::arm_ldrex: { 14072 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14073 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 14074 Info.opc = ISD::INTRINSIC_W_CHAIN; 14075 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14076 Info.ptrVal = I.getArgOperand(0); 14077 Info.offset = 0; 14078 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14079 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14080 return true; 14081 } 14082 case Intrinsic::arm_stlex: 14083 case Intrinsic::arm_strex: { 14084 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14085 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 14086 Info.opc = ISD::INTRINSIC_W_CHAIN; 14087 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14088 Info.ptrVal = I.getArgOperand(1); 14089 Info.offset = 0; 14090 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14091 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14092 return true; 14093 } 14094 case Intrinsic::arm_stlexd: 14095 case Intrinsic::arm_strexd: 14096 Info.opc = ISD::INTRINSIC_W_CHAIN; 14097 Info.memVT = MVT::i64; 14098 Info.ptrVal = I.getArgOperand(2); 14099 Info.offset = 0; 14100 Info.align = 8; 14101 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14102 return true; 14103 14104 case Intrinsic::arm_ldaexd: 14105 case Intrinsic::arm_ldrexd: 14106 Info.opc = ISD::INTRINSIC_W_CHAIN; 14107 Info.memVT = MVT::i64; 14108 Info.ptrVal = I.getArgOperand(0); 14109 Info.offset = 0; 14110 Info.align = 8; 14111 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14112 return true; 14113 14114 default: 14115 break; 14116 } 14117 14118 return false; 14119 } 14120 14121 /// \brief Returns true if it is beneficial to convert a load of a constant 14122 /// to just the constant itself. 14123 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14124 Type *Ty) const { 14125 assert(Ty->isIntegerTy()); 14126 14127 unsigned Bits = Ty->getPrimitiveSizeInBits(); 14128 if (Bits == 0 || Bits > 32) 14129 return false; 14130 return true; 14131 } 14132 14133 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 14134 unsigned Index) const { 14135 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 14136 return false; 14137 14138 return (Index == 0 || Index == ResVT.getVectorNumElements()); 14139 } 14140 14141 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 14142 ARM_MB::MemBOpt Domain) const { 14143 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14144 14145 // First, if the target has no DMB, see what fallback we can use. 14146 if (!Subtarget->hasDataBarrier()) { 14147 // Some ARMv6 cpus can support data barriers with an mcr instruction. 14148 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 14149 // here. 14150 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 14151 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 14152 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 14153 Builder.getInt32(0), Builder.getInt32(7), 14154 Builder.getInt32(10), Builder.getInt32(5)}; 14155 return Builder.CreateCall(MCR, args); 14156 } else { 14157 // Instead of using barriers, atomic accesses on these subtargets use 14158 // libcalls. 14159 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 14160 } 14161 } else { 14162 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 14163 // Only a full system barrier exists in the M-class architectures. 14164 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 14165 Constant *CDomain = Builder.getInt32(Domain); 14166 return Builder.CreateCall(DMB, CDomain); 14167 } 14168 } 14169 14170 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 14171 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 14172 Instruction *Inst, 14173 AtomicOrdering Ord) const { 14174 switch (Ord) { 14175 case AtomicOrdering::NotAtomic: 14176 case AtomicOrdering::Unordered: 14177 llvm_unreachable("Invalid fence: unordered/non-atomic"); 14178 case AtomicOrdering::Monotonic: 14179 case AtomicOrdering::Acquire: 14180 return nullptr; // Nothing to do 14181 case AtomicOrdering::SequentiallyConsistent: 14182 if (!Inst->hasAtomicStore()) 14183 return nullptr; // Nothing to do 14184 LLVM_FALLTHROUGH; 14185 case AtomicOrdering::Release: 14186 case AtomicOrdering::AcquireRelease: 14187 if (Subtarget->preferISHSTBarriers()) 14188 return makeDMB(Builder, ARM_MB::ISHST); 14189 // FIXME: add a comment with a link to documentation justifying this. 14190 else 14191 return makeDMB(Builder, ARM_MB::ISH); 14192 } 14193 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 14194 } 14195 14196 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 14197 Instruction *Inst, 14198 AtomicOrdering Ord) const { 14199 switch (Ord) { 14200 case AtomicOrdering::NotAtomic: 14201 case AtomicOrdering::Unordered: 14202 llvm_unreachable("Invalid fence: unordered/not-atomic"); 14203 case AtomicOrdering::Monotonic: 14204 case AtomicOrdering::Release: 14205 return nullptr; // Nothing to do 14206 case AtomicOrdering::Acquire: 14207 case AtomicOrdering::AcquireRelease: 14208 case AtomicOrdering::SequentiallyConsistent: 14209 return makeDMB(Builder, ARM_MB::ISH); 14210 } 14211 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 14212 } 14213 14214 // Loads and stores less than 64-bits are already atomic; ones above that 14215 // are doomed anyway, so defer to the default libcall and blame the OS when 14216 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14217 // anything for those. 14218 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 14219 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 14220 return (Size == 64) && !Subtarget->isMClass(); 14221 } 14222 14223 // Loads and stores less than 64-bits are already atomic; ones above that 14224 // are doomed anyway, so defer to the default libcall and blame the OS when 14225 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14226 // anything for those. 14227 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 14228 // guarantee, see DDI0406C ARM architecture reference manual, 14229 // sections A8.8.72-74 LDRD) 14230 TargetLowering::AtomicExpansionKind 14231 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 14232 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 14233 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 14234 : AtomicExpansionKind::None; 14235 } 14236 14237 // For the real atomic operations, we have ldrex/strex up to 32 bits, 14238 // and up to 64 bits on the non-M profiles 14239 TargetLowering::AtomicExpansionKind 14240 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 14241 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 14242 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14243 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 14244 ? AtomicExpansionKind::LLSC 14245 : AtomicExpansionKind::None; 14246 } 14247 14248 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 14249 AtomicCmpXchgInst *AI) const { 14250 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 14251 // implement cmpxchg without spilling. If the address being exchanged is also 14252 // on the stack and close enough to the spill slot, this can lead to a 14253 // situation where the monitor always gets cleared and the atomic operation 14254 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 14255 bool hasAtomicCmpXchg = 14256 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14257 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 14258 } 14259 14260 bool ARMTargetLowering::shouldInsertFencesForAtomic( 14261 const Instruction *I) const { 14262 return InsertFencesForAtomic; 14263 } 14264 14265 // This has so far only been implemented for MachO. 14266 bool ARMTargetLowering::useLoadStackGuardNode() const { 14267 return Subtarget->isTargetMachO(); 14268 } 14269 14270 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 14271 unsigned &Cost) const { 14272 // If we do not have NEON, vector types are not natively supported. 14273 if (!Subtarget->hasNEON()) 14274 return false; 14275 14276 // Floating point values and vector values map to the same register file. 14277 // Therefore, although we could do a store extract of a vector type, this is 14278 // better to leave at float as we have more freedom in the addressing mode for 14279 // those. 14280 if (VectorTy->isFPOrFPVectorTy()) 14281 return false; 14282 14283 // If the index is unknown at compile time, this is very expensive to lower 14284 // and it is not possible to combine the store with the extract. 14285 if (!isa<ConstantInt>(Idx)) 14286 return false; 14287 14288 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 14289 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 14290 // We can do a store + vector extract on any vector that fits perfectly in a D 14291 // or Q register. 14292 if (BitWidth == 64 || BitWidth == 128) { 14293 Cost = 0; 14294 return true; 14295 } 14296 return false; 14297 } 14298 14299 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 14300 return Subtarget->hasV6T2Ops(); 14301 } 14302 14303 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 14304 return Subtarget->hasV6T2Ops(); 14305 } 14306 14307 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 14308 AtomicOrdering Ord) const { 14309 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14310 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 14311 bool IsAcquire = isAcquireOrStronger(Ord); 14312 14313 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 14314 // intrinsic must return {i32, i32} and we have to recombine them into a 14315 // single i64 here. 14316 if (ValTy->getPrimitiveSizeInBits() == 64) { 14317 Intrinsic::ID Int = 14318 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 14319 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 14320 14321 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14322 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 14323 14324 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 14325 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 14326 if (!Subtarget->isLittle()) 14327 std::swap (Lo, Hi); 14328 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 14329 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 14330 return Builder.CreateOr( 14331 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 14332 } 14333 14334 Type *Tys[] = { Addr->getType() }; 14335 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 14336 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 14337 14338 return Builder.CreateTruncOrBitCast( 14339 Builder.CreateCall(Ldrex, Addr), 14340 cast<PointerType>(Addr->getType())->getElementType()); 14341 } 14342 14343 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 14344 IRBuilder<> &Builder) const { 14345 if (!Subtarget->hasV7Ops()) 14346 return; 14347 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14348 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 14349 } 14350 14351 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 14352 Value *Addr, 14353 AtomicOrdering Ord) const { 14354 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14355 bool IsRelease = isReleaseOrStronger(Ord); 14356 14357 // Since the intrinsics must have legal type, the i64 intrinsics take two 14358 // parameters: "i32, i32". We must marshal Val into the appropriate form 14359 // before the call. 14360 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 14361 Intrinsic::ID Int = 14362 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 14363 Function *Strex = Intrinsic::getDeclaration(M, Int); 14364 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 14365 14366 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 14367 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 14368 if (!Subtarget->isLittle()) 14369 std::swap(Lo, Hi); 14370 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14371 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 14372 } 14373 14374 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 14375 Type *Tys[] = { Addr->getType() }; 14376 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 14377 14378 return Builder.CreateCall( 14379 Strex, {Builder.CreateZExtOrBitCast( 14380 Val, Strex->getFunctionType()->getParamType(0)), 14381 Addr}); 14382 } 14383 14384 /// A helper function for determining the number of interleaved accesses we 14385 /// will generate when lowering accesses of the given type. 14386 unsigned 14387 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 14388 const DataLayout &DL) const { 14389 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 14390 } 14391 14392 bool ARMTargetLowering::isLegalInterleavedAccessType( 14393 VectorType *VecTy, const DataLayout &DL) const { 14394 14395 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 14396 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 14397 14398 // Ensure the vector doesn't have f16 elements. Even though we could do an 14399 // i16 vldN, we can't hold the f16 vectors and will end up converting via 14400 // f32. 14401 if (VecTy->getElementType()->isHalfTy()) 14402 return false; 14403 14404 // Ensure the number of vector elements is greater than 1. 14405 if (VecTy->getNumElements() < 2) 14406 return false; 14407 14408 // Ensure the element type is legal. 14409 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 14410 return false; 14411 14412 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 14413 // 128 will be split into multiple interleaved accesses. 14414 return VecSize == 64 || VecSize % 128 == 0; 14415 } 14416 14417 /// \brief Lower an interleaved load into a vldN intrinsic. 14418 /// 14419 /// E.g. Lower an interleaved load (Factor = 2): 14420 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 14421 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 14422 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 14423 /// 14424 /// Into: 14425 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 14426 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 14427 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 14428 bool ARMTargetLowering::lowerInterleavedLoad( 14429 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 14430 ArrayRef<unsigned> Indices, unsigned Factor) const { 14431 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14432 "Invalid interleave factor"); 14433 assert(!Shuffles.empty() && "Empty shufflevector input"); 14434 assert(Shuffles.size() == Indices.size() && 14435 "Unmatched number of shufflevectors and indices"); 14436 14437 VectorType *VecTy = Shuffles[0]->getType(); 14438 Type *EltTy = VecTy->getVectorElementType(); 14439 14440 const DataLayout &DL = LI->getModule()->getDataLayout(); 14441 14442 // Skip if we do not have NEON and skip illegal vector types. We can 14443 // "legalize" wide vector types into multiple interleaved accesses as long as 14444 // the vector types are divisible by 128. 14445 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 14446 return false; 14447 14448 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 14449 14450 // A pointer vector can not be the return type of the ldN intrinsics. Need to 14451 // load integer vectors first and then convert to pointer vectors. 14452 if (EltTy->isPointerTy()) 14453 VecTy = 14454 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 14455 14456 IRBuilder<> Builder(LI); 14457 14458 // The base address of the load. 14459 Value *BaseAddr = LI->getPointerOperand(); 14460 14461 if (NumLoads > 1) { 14462 // If we're going to generate more than one load, reset the sub-vector type 14463 // to something legal. 14464 VecTy = VectorType::get(VecTy->getVectorElementType(), 14465 VecTy->getVectorNumElements() / NumLoads); 14466 14467 // We will compute the pointer operand of each load from the original base 14468 // address using GEPs. Cast the base address to a pointer to the scalar 14469 // element type. 14470 BaseAddr = Builder.CreateBitCast( 14471 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 14472 LI->getPointerAddressSpace())); 14473 } 14474 14475 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 14476 14477 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 14478 Type *Tys[] = {VecTy, Int8Ptr}; 14479 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 14480 Intrinsic::arm_neon_vld3, 14481 Intrinsic::arm_neon_vld4}; 14482 Function *VldnFunc = 14483 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 14484 14485 // Holds sub-vectors extracted from the load intrinsic return values. The 14486 // sub-vectors are associated with the shufflevector instructions they will 14487 // replace. 14488 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 14489 14490 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 14491 // If we're generating more than one load, compute the base address of 14492 // subsequent loads as an offset from the previous. 14493 if (LoadCount > 0) 14494 BaseAddr = Builder.CreateConstGEP1_32( 14495 BaseAddr, VecTy->getVectorNumElements() * Factor); 14496 14497 SmallVector<Value *, 2> Ops; 14498 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14499 Ops.push_back(Builder.getInt32(LI->getAlignment())); 14500 14501 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 14502 14503 // Replace uses of each shufflevector with the corresponding vector loaded 14504 // by ldN. 14505 for (unsigned i = 0; i < Shuffles.size(); i++) { 14506 ShuffleVectorInst *SV = Shuffles[i]; 14507 unsigned Index = Indices[i]; 14508 14509 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 14510 14511 // Convert the integer vector to pointer vector if the element is pointer. 14512 if (EltTy->isPointerTy()) 14513 SubVec = Builder.CreateIntToPtr( 14514 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 14515 VecTy->getVectorNumElements())); 14516 14517 SubVecs[SV].push_back(SubVec); 14518 } 14519 } 14520 14521 // Replace uses of the shufflevector instructions with the sub-vectors 14522 // returned by the load intrinsic. If a shufflevector instruction is 14523 // associated with more than one sub-vector, those sub-vectors will be 14524 // concatenated into a single wide vector. 14525 for (ShuffleVectorInst *SVI : Shuffles) { 14526 auto &SubVec = SubVecs[SVI]; 14527 auto *WideVec = 14528 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 14529 SVI->replaceAllUsesWith(WideVec); 14530 } 14531 14532 return true; 14533 } 14534 14535 /// \brief Lower an interleaved store into a vstN intrinsic. 14536 /// 14537 /// E.g. Lower an interleaved store (Factor = 3): 14538 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 14539 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 14540 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 14541 /// 14542 /// Into: 14543 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 14544 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 14545 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 14546 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14547 /// 14548 /// Note that the new shufflevectors will be removed and we'll only generate one 14549 /// vst3 instruction in CodeGen. 14550 /// 14551 /// Example for a more general valid mask (Factor 3). Lower: 14552 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 14553 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 14554 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 14555 /// 14556 /// Into: 14557 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 14558 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 14559 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 14560 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14561 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 14562 ShuffleVectorInst *SVI, 14563 unsigned Factor) const { 14564 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14565 "Invalid interleave factor"); 14566 14567 VectorType *VecTy = SVI->getType(); 14568 assert(VecTy->getVectorNumElements() % Factor == 0 && 14569 "Invalid interleaved store"); 14570 14571 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 14572 Type *EltTy = VecTy->getVectorElementType(); 14573 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 14574 14575 const DataLayout &DL = SI->getModule()->getDataLayout(); 14576 14577 // Skip if we do not have NEON and skip illegal vector types. We can 14578 // "legalize" wide vector types into multiple interleaved accesses as long as 14579 // the vector types are divisible by 128. 14580 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 14581 return false; 14582 14583 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 14584 14585 Value *Op0 = SVI->getOperand(0); 14586 Value *Op1 = SVI->getOperand(1); 14587 IRBuilder<> Builder(SI); 14588 14589 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 14590 // vectors to integer vectors. 14591 if (EltTy->isPointerTy()) { 14592 Type *IntTy = DL.getIntPtrType(EltTy); 14593 14594 // Convert to the corresponding integer vector. 14595 Type *IntVecTy = 14596 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 14597 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 14598 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 14599 14600 SubVecTy = VectorType::get(IntTy, LaneLen); 14601 } 14602 14603 // The base address of the store. 14604 Value *BaseAddr = SI->getPointerOperand(); 14605 14606 if (NumStores > 1) { 14607 // If we're going to generate more than one store, reset the lane length 14608 // and sub-vector type to something legal. 14609 LaneLen /= NumStores; 14610 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 14611 14612 // We will compute the pointer operand of each store from the original base 14613 // address using GEPs. Cast the base address to a pointer to the scalar 14614 // element type. 14615 BaseAddr = Builder.CreateBitCast( 14616 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 14617 SI->getPointerAddressSpace())); 14618 } 14619 14620 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 14621 14622 auto Mask = SVI->getShuffleMask(); 14623 14624 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 14625 Type *Tys[] = {Int8Ptr, SubVecTy}; 14626 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 14627 Intrinsic::arm_neon_vst3, 14628 Intrinsic::arm_neon_vst4}; 14629 14630 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 14631 // If we generating more than one store, we compute the base address of 14632 // subsequent stores as an offset from the previous. 14633 if (StoreCount > 0) 14634 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 14635 14636 SmallVector<Value *, 6> Ops; 14637 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14638 14639 Function *VstNFunc = 14640 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 14641 14642 // Split the shufflevector operands into sub vectors for the new vstN call. 14643 for (unsigned i = 0; i < Factor; i++) { 14644 unsigned IdxI = StoreCount * LaneLen * Factor + i; 14645 if (Mask[IdxI] >= 0) { 14646 Ops.push_back(Builder.CreateShuffleVector( 14647 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 14648 } else { 14649 unsigned StartMask = 0; 14650 for (unsigned j = 1; j < LaneLen; j++) { 14651 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 14652 if (Mask[IdxJ * Factor + IdxI] >= 0) { 14653 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 14654 break; 14655 } 14656 } 14657 // Note: If all elements in a chunk are undefs, StartMask=0! 14658 // Note: Filling undef gaps with random elements is ok, since 14659 // those elements were being written anyway (with undefs). 14660 // In the case of all undefs we're defaulting to using elems from 0 14661 // Note: StartMask cannot be negative, it's checked in 14662 // isReInterleaveMask 14663 Ops.push_back(Builder.CreateShuffleVector( 14664 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 14665 } 14666 } 14667 14668 Ops.push_back(Builder.getInt32(SI->getAlignment())); 14669 Builder.CreateCall(VstNFunc, Ops); 14670 } 14671 return true; 14672 } 14673 14674 enum HABaseType { 14675 HA_UNKNOWN = 0, 14676 HA_FLOAT, 14677 HA_DOUBLE, 14678 HA_VECT64, 14679 HA_VECT128 14680 }; 14681 14682 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 14683 uint64_t &Members) { 14684 if (auto *ST = dyn_cast<StructType>(Ty)) { 14685 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 14686 uint64_t SubMembers = 0; 14687 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 14688 return false; 14689 Members += SubMembers; 14690 } 14691 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 14692 uint64_t SubMembers = 0; 14693 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 14694 return false; 14695 Members += SubMembers * AT->getNumElements(); 14696 } else if (Ty->isFloatTy()) { 14697 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 14698 return false; 14699 Members = 1; 14700 Base = HA_FLOAT; 14701 } else if (Ty->isDoubleTy()) { 14702 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 14703 return false; 14704 Members = 1; 14705 Base = HA_DOUBLE; 14706 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 14707 Members = 1; 14708 switch (Base) { 14709 case HA_FLOAT: 14710 case HA_DOUBLE: 14711 return false; 14712 case HA_VECT64: 14713 return VT->getBitWidth() == 64; 14714 case HA_VECT128: 14715 return VT->getBitWidth() == 128; 14716 case HA_UNKNOWN: 14717 switch (VT->getBitWidth()) { 14718 case 64: 14719 Base = HA_VECT64; 14720 return true; 14721 case 128: 14722 Base = HA_VECT128; 14723 return true; 14724 default: 14725 return false; 14726 } 14727 } 14728 } 14729 14730 return (Members > 0 && Members <= 4); 14731 } 14732 14733 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 14734 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 14735 /// passing according to AAPCS rules. 14736 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 14737 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 14738 if (getEffectiveCallingConv(CallConv, isVarArg) != 14739 CallingConv::ARM_AAPCS_VFP) 14740 return false; 14741 14742 HABaseType Base = HA_UNKNOWN; 14743 uint64_t Members = 0; 14744 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 14745 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 14746 14747 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 14748 return IsHA || IsIntArray; 14749 } 14750 14751 unsigned ARMTargetLowering::getExceptionPointerRegister( 14752 const Constant *PersonalityFn) const { 14753 // Platforms which do not use SjLj EH may return values in these registers 14754 // via the personality function. 14755 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 14756 } 14757 14758 unsigned ARMTargetLowering::getExceptionSelectorRegister( 14759 const Constant *PersonalityFn) const { 14760 // Platforms which do not use SjLj EH may return values in these registers 14761 // via the personality function. 14762 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 14763 } 14764 14765 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14766 // Update IsSplitCSR in ARMFunctionInfo. 14767 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 14768 AFI->setIsSplitCSR(true); 14769 } 14770 14771 void ARMTargetLowering::insertCopiesSplitCSR( 14772 MachineBasicBlock *Entry, 14773 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14774 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 14775 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14776 if (!IStart) 14777 return; 14778 14779 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 14780 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14781 MachineBasicBlock::iterator MBBI = Entry->begin(); 14782 for (const MCPhysReg *I = IStart; *I; ++I) { 14783 const TargetRegisterClass *RC = nullptr; 14784 if (ARM::GPRRegClass.contains(*I)) 14785 RC = &ARM::GPRRegClass; 14786 else if (ARM::DPRRegClass.contains(*I)) 14787 RC = &ARM::DPRRegClass; 14788 else 14789 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14790 14791 unsigned NewVR = MRI->createVirtualRegister(RC); 14792 // Create copy from CSR to a virtual register. 14793 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14794 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14795 // nounwind. If we want to generalize this later, we may need to emit 14796 // CFI pseudo-instructions. 14797 assert(Entry->getParent()->getFunction().hasFnAttribute( 14798 Attribute::NoUnwind) && 14799 "Function should be nounwind in insertCopiesSplitCSR!"); 14800 Entry->addLiveIn(*I); 14801 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14802 .addReg(*I); 14803 14804 // Insert the copy-back instructions right before the terminator. 14805 for (auto *Exit : Exits) 14806 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14807 TII->get(TargetOpcode::COPY), *I) 14808 .addReg(NewVR); 14809 } 14810 } 14811 14812 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 14813 MF.getFrameInfo().computeMaxCallFrameSize(MF); 14814 TargetLoweringBase::finalizeLowering(MF); 14815 } 14816