1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMISelLowering.h" 16 #include "ARMBaseInstrInfo.h" 17 #include "ARMBaseRegisterInfo.h" 18 #include "ARMCallingConv.h" 19 #include "ARMConstantPoolValue.h" 20 #include "ARMMachineFunctionInfo.h" 21 #include "ARMPerfectShuffle.h" 22 #include "ARMRegisterInfo.h" 23 #include "ARMSelectionDAGInfo.h" 24 #include "ARMSubtarget.h" 25 #include "MCTargetDesc/ARMAddressingModes.h" 26 #include "MCTargetDesc/ARMBaseInfo.h" 27 #include "Utils/ARMBaseInfo.h" 28 #include "llvm/ADT/APFloat.h" 29 #include "llvm/ADT/APInt.h" 30 #include "llvm/ADT/ArrayRef.h" 31 #include "llvm/ADT/BitVector.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallVector.h" 36 #include "llvm/ADT/Statistic.h" 37 #include "llvm/ADT/StringExtras.h" 38 #include "llvm/ADT/StringRef.h" 39 #include "llvm/ADT/StringSwitch.h" 40 #include "llvm/ADT/Triple.h" 41 #include "llvm/ADT/Twine.h" 42 #include "llvm/Analysis/VectorUtils.h" 43 #include "llvm/CodeGen/CallingConvLower.h" 44 #include "llvm/CodeGen/ISDOpcodes.h" 45 #include "llvm/CodeGen/IntrinsicLowering.h" 46 #include "llvm/CodeGen/MachineBasicBlock.h" 47 #include "llvm/CodeGen/MachineConstantPool.h" 48 #include "llvm/CodeGen/MachineFrameInfo.h" 49 #include "llvm/CodeGen/MachineFunction.h" 50 #include "llvm/CodeGen/MachineInstr.h" 51 #include "llvm/CodeGen/MachineInstrBuilder.h" 52 #include "llvm/CodeGen/MachineJumpTableInfo.h" 53 #include "llvm/CodeGen/MachineMemOperand.h" 54 #include "llvm/CodeGen/MachineOperand.h" 55 #include "llvm/CodeGen/MachineRegisterInfo.h" 56 #include "llvm/CodeGen/RuntimeLibcalls.h" 57 #include "llvm/CodeGen/SelectionDAG.h" 58 #include "llvm/CodeGen/SelectionDAGNodes.h" 59 #include "llvm/CodeGen/TargetInstrInfo.h" 60 #include "llvm/CodeGen/TargetLowering.h" 61 #include "llvm/CodeGen/TargetOpcodes.h" 62 #include "llvm/CodeGen/TargetRegisterInfo.h" 63 #include "llvm/CodeGen/TargetSubtargetInfo.h" 64 #include "llvm/CodeGen/ValueTypes.h" 65 #include "llvm/IR/Attributes.h" 66 #include "llvm/IR/CallingConv.h" 67 #include "llvm/IR/Constant.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugLoc.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GlobalAlias.h" 74 #include "llvm/IR/GlobalValue.h" 75 #include "llvm/IR/GlobalVariable.h" 76 #include "llvm/IR/IRBuilder.h" 77 #include "llvm/IR/InlineAsm.h" 78 #include "llvm/IR/Instruction.h" 79 #include "llvm/IR/Instructions.h" 80 #include "llvm/IR/IntrinsicInst.h" 81 #include "llvm/IR/Intrinsics.h" 82 #include "llvm/IR/Module.h" 83 #include "llvm/IR/Type.h" 84 #include "llvm/IR/User.h" 85 #include "llvm/IR/Value.h" 86 #include "llvm/MC/MCInstrDesc.h" 87 #include "llvm/MC/MCInstrItineraries.h" 88 #include "llvm/MC/MCRegisterInfo.h" 89 #include "llvm/MC/MCSchedule.h" 90 #include "llvm/Support/AtomicOrdering.h" 91 #include "llvm/Support/BranchProbability.h" 92 #include "llvm/Support/Casting.h" 93 #include "llvm/Support/CodeGen.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/ErrorHandling.h" 98 #include "llvm/Support/KnownBits.h" 99 #include "llvm/Support/MachineValueType.h" 100 #include "llvm/Support/MathExtras.h" 101 #include "llvm/Support/raw_ostream.h" 102 #include "llvm/Target/TargetMachine.h" 103 #include "llvm/Target/TargetOptions.h" 104 #include <algorithm> 105 #include <cassert> 106 #include <cstdint> 107 #include <cstdlib> 108 #include <iterator> 109 #include <limits> 110 #include <string> 111 #include <tuple> 112 #include <utility> 113 #include <vector> 114 115 using namespace llvm; 116 117 #define DEBUG_TYPE "arm-isel" 118 119 STATISTIC(NumTailCalls, "Number of tail calls"); 120 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 121 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 122 STATISTIC(NumConstpoolPromoted, 123 "Number of constants with their storage promoted into constant pools"); 124 125 static cl::opt<bool> 126 ARMInterworking("arm-interworking", cl::Hidden, 127 cl::desc("Enable / disable ARM interworking (for debugging only)"), 128 cl::init(true)); 129 130 static cl::opt<bool> EnableConstpoolPromotion( 131 "arm-promote-constant", cl::Hidden, 132 cl::desc("Enable / disable promotion of unnamed_addr constants into " 133 "constant pools"), 134 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed 135 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 136 "arm-promote-constant-max-size", cl::Hidden, 137 cl::desc("Maximum size of constant to promote into a constant pool"), 138 cl::init(64)); 139 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 140 "arm-promote-constant-max-total", cl::Hidden, 141 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 142 cl::init(128)); 143 144 // The APCS parameter registers. 145 static const MCPhysReg GPRArgRegs[] = { 146 ARM::R0, ARM::R1, ARM::R2, ARM::R3 147 }; 148 149 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 150 MVT PromotedBitwiseVT) { 151 if (VT != PromotedLdStVT) { 152 setOperationAction(ISD::LOAD, VT, Promote); 153 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 154 155 setOperationAction(ISD::STORE, VT, Promote); 156 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 157 } 158 159 MVT ElemTy = VT.getVectorElementType(); 160 if (ElemTy != MVT::f64) 161 setOperationAction(ISD::SETCC, VT, Custom); 162 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 163 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 164 if (ElemTy == MVT::i32) { 165 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 166 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 167 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 168 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 169 } else { 170 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 171 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 172 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 173 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 174 } 175 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 176 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 177 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 178 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 179 setOperationAction(ISD::SELECT, VT, Expand); 180 setOperationAction(ISD::SELECT_CC, VT, Expand); 181 setOperationAction(ISD::VSELECT, VT, Expand); 182 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 183 if (VT.isInteger()) { 184 setOperationAction(ISD::SHL, VT, Custom); 185 setOperationAction(ISD::SRA, VT, Custom); 186 setOperationAction(ISD::SRL, VT, Custom); 187 } 188 189 // Promote all bit-wise operations. 190 if (VT.isInteger() && VT != PromotedBitwiseVT) { 191 setOperationAction(ISD::AND, VT, Promote); 192 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 193 setOperationAction(ISD::OR, VT, Promote); 194 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 195 setOperationAction(ISD::XOR, VT, Promote); 196 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 197 } 198 199 // Neon does not support vector divide/remainder operations. 200 setOperationAction(ISD::SDIV, VT, Expand); 201 setOperationAction(ISD::UDIV, VT, Expand); 202 setOperationAction(ISD::FDIV, VT, Expand); 203 setOperationAction(ISD::SREM, VT, Expand); 204 setOperationAction(ISD::UREM, VT, Expand); 205 setOperationAction(ISD::FREM, VT, Expand); 206 207 if (!VT.isFloatingPoint() && 208 VT != MVT::v2i64 && VT != MVT::v1i64) 209 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 210 setOperationAction(Opcode, VT, Legal); 211 } 212 213 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 214 addRegisterClass(VT, &ARM::DPRRegClass); 215 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 216 } 217 218 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 219 addRegisterClass(VT, &ARM::DPairRegClass); 220 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 221 } 222 223 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 224 const ARMSubtarget &STI) 225 : TargetLowering(TM), Subtarget(&STI) { 226 RegInfo = Subtarget->getRegisterInfo(); 227 Itins = Subtarget->getInstrItineraryData(); 228 229 setBooleanContents(ZeroOrOneBooleanContent); 230 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 231 232 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 233 !Subtarget->isTargetWatchOS()) { 234 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 235 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 236 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 237 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 238 : CallingConv::ARM_AAPCS); 239 } 240 241 if (Subtarget->isTargetMachO()) { 242 // Uses VFP for Thumb libfuncs if available. 243 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 244 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 245 static const struct { 246 const RTLIB::Libcall Op; 247 const char * const Name; 248 const ISD::CondCode Cond; 249 } LibraryCalls[] = { 250 // Single-precision floating-point arithmetic. 251 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 252 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 253 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 254 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 255 256 // Double-precision floating-point arithmetic. 257 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 258 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 259 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 260 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 261 262 // Single-precision comparisons. 263 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 264 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 265 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 266 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 267 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 268 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 269 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 270 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 271 272 // Double-precision comparisons. 273 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 274 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 275 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 276 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 277 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 278 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 279 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 280 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 281 282 // Floating-point to integer conversions. 283 // i64 conversions are done via library routines even when generating VFP 284 // instructions, so use the same ones. 285 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 286 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 287 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 288 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 289 290 // Conversions between floating types. 291 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 292 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 293 294 // Integer to floating-point conversions. 295 // i64 conversions are done via library routines even when generating VFP 296 // instructions, so use the same ones. 297 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 298 // e.g., __floatunsidf vs. __floatunssidfvfp. 299 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 300 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 301 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 302 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 303 }; 304 305 for (const auto &LC : LibraryCalls) { 306 setLibcallName(LC.Op, LC.Name); 307 if (LC.Cond != ISD::SETCC_INVALID) 308 setCmpLibcallCC(LC.Op, LC.Cond); 309 } 310 } 311 312 // Set the correct calling convention for ARMv7k WatchOS. It's just 313 // AAPCS_VFP for functions as simple as libcalls. 314 if (Subtarget->isTargetWatchABI()) { 315 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 316 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 317 } 318 } 319 320 // These libcalls are not available in 32-bit. 321 setLibcallName(RTLIB::SHL_I128, nullptr); 322 setLibcallName(RTLIB::SRL_I128, nullptr); 323 setLibcallName(RTLIB::SRA_I128, nullptr); 324 325 // RTLIB 326 if (Subtarget->isAAPCS_ABI() && 327 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 328 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 329 static const struct { 330 const RTLIB::Libcall Op; 331 const char * const Name; 332 const CallingConv::ID CC; 333 const ISD::CondCode Cond; 334 } LibraryCalls[] = { 335 // Double-precision floating-point arithmetic helper functions 336 // RTABI chapter 4.1.2, Table 2 337 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 338 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 342 // Double-precision floating-point comparison helper functions 343 // RTABI chapter 4.1.2, Table 3 344 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 345 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 346 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 347 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 348 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 349 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 350 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 351 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 352 353 // Single-precision floating-point arithmetic helper functions 354 // RTABI chapter 4.1.2, Table 4 355 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 356 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 357 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 358 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 359 360 // Single-precision floating-point comparison helper functions 361 // RTABI chapter 4.1.2, Table 5 362 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 363 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 364 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 365 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 366 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 367 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 368 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 369 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 370 371 // Floating-point to integer conversions. 372 // RTABI chapter 4.1.2, Table 6 373 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 374 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 375 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 376 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 377 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 378 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 379 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 380 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 381 382 // Conversions between floating types. 383 // RTABI chapter 4.1.2, Table 7 384 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 385 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 386 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 387 388 // Integer to floating-point conversions. 389 // RTABI chapter 4.1.2, Table 8 390 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 391 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 392 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 393 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 394 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 395 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 396 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 397 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 398 399 // Long long helper functions 400 // RTABI chapter 4.2, Table 9 401 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 402 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 403 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 404 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 405 406 // Integer division functions 407 // RTABI chapter 4.3.1 408 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 409 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 410 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 411 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 412 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 413 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 414 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 415 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 416 }; 417 418 for (const auto &LC : LibraryCalls) { 419 setLibcallName(LC.Op, LC.Name); 420 setLibcallCallingConv(LC.Op, LC.CC); 421 if (LC.Cond != ISD::SETCC_INVALID) 422 setCmpLibcallCC(LC.Op, LC.Cond); 423 } 424 425 // EABI dependent RTLIB 426 if (TM.Options.EABIVersion == EABI::EABI4 || 427 TM.Options.EABIVersion == EABI::EABI5) { 428 static const struct { 429 const RTLIB::Libcall Op; 430 const char *const Name; 431 const CallingConv::ID CC; 432 const ISD::CondCode Cond; 433 } MemOpsLibraryCalls[] = { 434 // Memory operations 435 // RTABI chapter 4.3.4 436 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 437 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 438 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 439 }; 440 441 for (const auto &LC : MemOpsLibraryCalls) { 442 setLibcallName(LC.Op, LC.Name); 443 setLibcallCallingConv(LC.Op, LC.CC); 444 if (LC.Cond != ISD::SETCC_INVALID) 445 setCmpLibcallCC(LC.Op, LC.Cond); 446 } 447 } 448 } 449 450 if (Subtarget->isTargetWindows()) { 451 static const struct { 452 const RTLIB::Libcall Op; 453 const char * const Name; 454 const CallingConv::ID CC; 455 } LibraryCalls[] = { 456 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 457 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 458 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 459 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 460 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 461 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 462 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 463 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 464 }; 465 466 for (const auto &LC : LibraryCalls) { 467 setLibcallName(LC.Op, LC.Name); 468 setLibcallCallingConv(LC.Op, LC.CC); 469 } 470 } 471 472 // Use divmod compiler-rt calls for iOS 5.0 and later. 473 if (Subtarget->isTargetMachO() && 474 !(Subtarget->isTargetIOS() && 475 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 476 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 477 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 478 } 479 480 // The half <-> float conversion functions are always soft-float on 481 // non-watchos platforms, but are needed for some targets which use a 482 // hard-float calling convention by default. 483 if (!Subtarget->isTargetWatchABI()) { 484 if (Subtarget->isAAPCS_ABI()) { 485 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 486 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 487 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 488 } else { 489 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 490 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 491 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 492 } 493 } 494 495 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 496 // a __gnu_ prefix (which is the default). 497 if (Subtarget->isTargetAEABI()) { 498 static const struct { 499 const RTLIB::Libcall Op; 500 const char * const Name; 501 const CallingConv::ID CC; 502 } LibraryCalls[] = { 503 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 504 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 505 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 506 }; 507 508 for (const auto &LC : LibraryCalls) { 509 setLibcallName(LC.Op, LC.Name); 510 setLibcallCallingConv(LC.Op, LC.CC); 511 } 512 } 513 514 if (Subtarget->isThumb1Only()) 515 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 516 else 517 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 518 519 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 520 !Subtarget->isThumb1Only()) { 521 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 522 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 523 } 524 525 if (Subtarget->hasFullFP16()) { 526 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 527 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 528 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 529 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 530 531 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 532 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 533 } 534 535 for (MVT VT : MVT::vector_valuetypes()) { 536 for (MVT InnerVT : MVT::vector_valuetypes()) { 537 setTruncStoreAction(VT, InnerVT, Expand); 538 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 539 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 540 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 541 } 542 543 setOperationAction(ISD::MULHS, VT, Expand); 544 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 545 setOperationAction(ISD::MULHU, VT, Expand); 546 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 547 548 setOperationAction(ISD::BSWAP, VT, Expand); 549 } 550 551 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 552 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 553 554 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 555 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 556 557 if (Subtarget->hasNEON()) { 558 addDRTypeForNEON(MVT::v2f32); 559 addDRTypeForNEON(MVT::v8i8); 560 addDRTypeForNEON(MVT::v4i16); 561 addDRTypeForNEON(MVT::v2i32); 562 addDRTypeForNEON(MVT::v1i64); 563 564 addQRTypeForNEON(MVT::v4f32); 565 addQRTypeForNEON(MVT::v2f64); 566 addQRTypeForNEON(MVT::v16i8); 567 addQRTypeForNEON(MVT::v8i16); 568 addQRTypeForNEON(MVT::v4i32); 569 addQRTypeForNEON(MVT::v2i64); 570 571 if (Subtarget->hasFullFP16()) { 572 addQRTypeForNEON(MVT::v8f16); 573 addDRTypeForNEON(MVT::v4f16); 574 } 575 576 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 577 // neither Neon nor VFP support any arithmetic operations on it. 578 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 579 // supported for v4f32. 580 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 581 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 582 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 583 // FIXME: Code duplication: FDIV and FREM are expanded always, see 584 // ARMTargetLowering::addTypeForNEON method for details. 585 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 586 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 587 // FIXME: Create unittest. 588 // In another words, find a way when "copysign" appears in DAG with vector 589 // operands. 590 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 591 // FIXME: Code duplication: SETCC has custom operation action, see 592 // ARMTargetLowering::addTypeForNEON method for details. 593 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 594 // FIXME: Create unittest for FNEG and for FABS. 595 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 596 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 597 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 598 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 599 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 600 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 601 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 602 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 603 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 604 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 605 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 606 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 607 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 608 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 609 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 610 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 611 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 612 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 613 614 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 615 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 616 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 617 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 618 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 619 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 620 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 621 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 622 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 623 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 624 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 625 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 626 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 627 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 628 629 // Mark v2f32 intrinsics. 630 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 631 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 632 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 633 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 634 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 635 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 636 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 637 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 638 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 639 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 640 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 641 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 642 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 643 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 644 645 // Neon does not support some operations on v1i64 and v2i64 types. 646 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 647 // Custom handling for some quad-vector types to detect VMULL. 648 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 649 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 650 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 651 // Custom handling for some vector types to avoid expensive expansions 652 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 653 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 654 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 655 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 656 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 657 // a destination type that is wider than the source, and nor does 658 // it have a FP_TO_[SU]INT instruction with a narrower destination than 659 // source. 660 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 661 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 662 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 663 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 664 665 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 666 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 667 668 // NEON does not have single instruction CTPOP for vectors with element 669 // types wider than 8-bits. However, custom lowering can leverage the 670 // v8i8/v16i8 vcnt instruction. 671 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 672 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 673 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 674 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 675 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 676 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 677 678 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 679 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 680 681 // NEON does not have single instruction CTTZ for vectors. 682 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 683 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 684 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 685 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 686 687 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 688 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 689 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 690 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 691 692 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 693 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 694 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 695 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 696 697 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 698 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 699 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 700 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 701 702 // NEON only has FMA instructions as of VFP4. 703 if (!Subtarget->hasVFP4()) { 704 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 705 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 706 } 707 708 setTargetDAGCombine(ISD::INTRINSIC_VOID); 709 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 710 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 711 setTargetDAGCombine(ISD::SHL); 712 setTargetDAGCombine(ISD::SRL); 713 setTargetDAGCombine(ISD::SRA); 714 setTargetDAGCombine(ISD::SIGN_EXTEND); 715 setTargetDAGCombine(ISD::ZERO_EXTEND); 716 setTargetDAGCombine(ISD::ANY_EXTEND); 717 setTargetDAGCombine(ISD::BUILD_VECTOR); 718 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 719 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 720 setTargetDAGCombine(ISD::STORE); 721 setTargetDAGCombine(ISD::FP_TO_SINT); 722 setTargetDAGCombine(ISD::FP_TO_UINT); 723 setTargetDAGCombine(ISD::FDIV); 724 setTargetDAGCombine(ISD::LOAD); 725 726 // It is legal to extload from v4i8 to v4i16 or v4i32. 727 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 728 MVT::v2i32}) { 729 for (MVT VT : MVT::integer_vector_valuetypes()) { 730 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 731 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 732 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 733 } 734 } 735 } 736 737 if (Subtarget->isFPOnlySP()) { 738 // When targeting a floating-point unit with only single-precision 739 // operations, f64 is legal for the few double-precision instructions which 740 // are present However, no double-precision operations other than moves, 741 // loads and stores are provided by the hardware. 742 setOperationAction(ISD::FADD, MVT::f64, Expand); 743 setOperationAction(ISD::FSUB, MVT::f64, Expand); 744 setOperationAction(ISD::FMUL, MVT::f64, Expand); 745 setOperationAction(ISD::FMA, MVT::f64, Expand); 746 setOperationAction(ISD::FDIV, MVT::f64, Expand); 747 setOperationAction(ISD::FREM, MVT::f64, Expand); 748 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 749 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 750 setOperationAction(ISD::FNEG, MVT::f64, Expand); 751 setOperationAction(ISD::FABS, MVT::f64, Expand); 752 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 753 setOperationAction(ISD::FSIN, MVT::f64, Expand); 754 setOperationAction(ISD::FCOS, MVT::f64, Expand); 755 setOperationAction(ISD::FPOW, MVT::f64, Expand); 756 setOperationAction(ISD::FLOG, MVT::f64, Expand); 757 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 758 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 759 setOperationAction(ISD::FEXP, MVT::f64, Expand); 760 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 761 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 762 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 763 setOperationAction(ISD::FRINT, MVT::f64, Expand); 764 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 765 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 766 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 767 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 768 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 769 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 770 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 771 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 772 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 773 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 774 } 775 776 computeRegisterProperties(Subtarget->getRegisterInfo()); 777 778 // ARM does not have floating-point extending loads. 779 for (MVT VT : MVT::fp_valuetypes()) { 780 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 781 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 782 } 783 784 // ... or truncating stores 785 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 786 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 787 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 788 789 // ARM does not have i1 sign extending load. 790 for (MVT VT : MVT::integer_valuetypes()) 791 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 792 793 // ARM supports all 4 flavors of integer indexed load / store. 794 if (!Subtarget->isThumb1Only()) { 795 for (unsigned im = (unsigned)ISD::PRE_INC; 796 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 797 setIndexedLoadAction(im, MVT::i1, Legal); 798 setIndexedLoadAction(im, MVT::i8, Legal); 799 setIndexedLoadAction(im, MVT::i16, Legal); 800 setIndexedLoadAction(im, MVT::i32, Legal); 801 setIndexedStoreAction(im, MVT::i1, Legal); 802 setIndexedStoreAction(im, MVT::i8, Legal); 803 setIndexedStoreAction(im, MVT::i16, Legal); 804 setIndexedStoreAction(im, MVT::i32, Legal); 805 } 806 } else { 807 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 808 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 809 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 810 } 811 812 setOperationAction(ISD::SADDO, MVT::i32, Custom); 813 setOperationAction(ISD::UADDO, MVT::i32, Custom); 814 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 815 setOperationAction(ISD::USUBO, MVT::i32, Custom); 816 817 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 818 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 819 820 // i64 operation support. 821 setOperationAction(ISD::MUL, MVT::i64, Expand); 822 setOperationAction(ISD::MULHU, MVT::i32, Expand); 823 if (Subtarget->isThumb1Only()) { 824 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 825 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 826 } 827 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 828 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 829 setOperationAction(ISD::MULHS, MVT::i32, Expand); 830 831 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 832 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 833 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 834 setOperationAction(ISD::SRL, MVT::i64, Custom); 835 setOperationAction(ISD::SRA, MVT::i64, Custom); 836 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 837 838 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 839 if (Subtarget->isThumb1Only()) { 840 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 841 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 842 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 843 } 844 845 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 846 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 847 848 // ARM does not have ROTL. 849 setOperationAction(ISD::ROTL, MVT::i32, Expand); 850 for (MVT VT : MVT::vector_valuetypes()) { 851 setOperationAction(ISD::ROTL, VT, Expand); 852 setOperationAction(ISD::ROTR, VT, Expand); 853 } 854 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 855 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 856 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 857 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 858 859 // @llvm.readcyclecounter requires the Performance Monitors extension. 860 // Default to the 0 expansion on unsupported platforms. 861 // FIXME: Technically there are older ARM CPUs that have 862 // implementation-specific ways of obtaining this information. 863 if (Subtarget->hasPerfMon()) 864 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 865 866 // Only ARMv6 has BSWAP. 867 if (!Subtarget->hasV6Ops()) 868 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 869 870 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 871 : Subtarget->hasDivideInARMMode(); 872 if (!hasDivide) { 873 // These are expanded into libcalls if the cpu doesn't have HW divider. 874 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 875 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 876 } 877 878 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 879 setOperationAction(ISD::SDIV, MVT::i32, Custom); 880 setOperationAction(ISD::UDIV, MVT::i32, Custom); 881 882 setOperationAction(ISD::SDIV, MVT::i64, Custom); 883 setOperationAction(ISD::UDIV, MVT::i64, Custom); 884 } 885 886 setOperationAction(ISD::SREM, MVT::i32, Expand); 887 setOperationAction(ISD::UREM, MVT::i32, Expand); 888 889 // Register based DivRem for AEABI (RTABI 4.2) 890 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 891 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 892 Subtarget->isTargetWindows()) { 893 setOperationAction(ISD::SREM, MVT::i64, Custom); 894 setOperationAction(ISD::UREM, MVT::i64, Custom); 895 HasStandaloneRem = false; 896 897 if (Subtarget->isTargetWindows()) { 898 const struct { 899 const RTLIB::Libcall Op; 900 const char * const Name; 901 const CallingConv::ID CC; 902 } LibraryCalls[] = { 903 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 904 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 905 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 906 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 907 908 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 909 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 910 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 911 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 912 }; 913 914 for (const auto &LC : LibraryCalls) { 915 setLibcallName(LC.Op, LC.Name); 916 setLibcallCallingConv(LC.Op, LC.CC); 917 } 918 } else { 919 const struct { 920 const RTLIB::Libcall Op; 921 const char * const Name; 922 const CallingConv::ID CC; 923 } LibraryCalls[] = { 924 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 925 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 926 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 927 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 928 929 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 930 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 931 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 932 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 933 }; 934 935 for (const auto &LC : LibraryCalls) { 936 setLibcallName(LC.Op, LC.Name); 937 setLibcallCallingConv(LC.Op, LC.CC); 938 } 939 } 940 941 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 942 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 943 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 944 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 945 } else { 946 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 947 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 948 } 949 950 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 951 for (auto &VT : {MVT::f32, MVT::f64}) 952 setOperationAction(ISD::FPOWI, VT, Custom); 953 954 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 955 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 956 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 957 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 958 959 setOperationAction(ISD::TRAP, MVT::Other, Legal); 960 961 // Use the default implementation. 962 setOperationAction(ISD::VASTART, MVT::Other, Custom); 963 setOperationAction(ISD::VAARG, MVT::Other, Expand); 964 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 965 setOperationAction(ISD::VAEND, MVT::Other, Expand); 966 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 967 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 968 969 if (Subtarget->isTargetWindows()) 970 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 971 else 972 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 973 974 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 975 // the default expansion. 976 InsertFencesForAtomic = false; 977 if (Subtarget->hasAnyDataBarrier() && 978 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 979 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 980 // to ldrex/strex loops already. 981 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 982 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 983 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 984 985 // On v8, we have particularly efficient implementations of atomic fences 986 // if they can be combined with nearby atomic loads and stores. 987 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 988 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 989 InsertFencesForAtomic = true; 990 } 991 } else { 992 // If there's anything we can use as a barrier, go through custom lowering 993 // for ATOMIC_FENCE. 994 // If target has DMB in thumb, Fences can be inserted. 995 if (Subtarget->hasDataBarrier()) 996 InsertFencesForAtomic = true; 997 998 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 999 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 1000 1001 // Set them all for expansion, which will force libcalls. 1002 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1003 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1004 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1005 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1006 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1007 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1008 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1009 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1010 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1011 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1012 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1013 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1014 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1015 // Unordered/Monotonic case. 1016 if (!InsertFencesForAtomic) { 1017 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1018 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1019 } 1020 } 1021 1022 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1023 1024 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1025 if (!Subtarget->hasV6Ops()) { 1026 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1027 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1028 } 1029 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1030 1031 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1032 !Subtarget->isThumb1Only()) { 1033 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1034 // iff target supports vfp2. 1035 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1036 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1037 } 1038 1039 // We want to custom lower some of our intrinsics. 1040 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1041 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1042 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1043 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1044 if (Subtarget->useSjLjEH()) 1045 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1046 1047 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1048 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1049 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1050 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1051 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1052 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1053 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1054 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1055 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1056 if (Subtarget->hasFullFP16()) { 1057 setOperationAction(ISD::SETCC, MVT::f16, Expand); 1058 setOperationAction(ISD::SELECT, MVT::f16, Custom); 1059 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 1060 } 1061 1062 setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom); 1063 1064 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1065 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1066 if (Subtarget->hasFullFP16()) 1067 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 1068 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1069 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1070 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1071 1072 // We don't support sin/cos/fmod/copysign/pow 1073 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1074 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1075 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1076 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1077 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1078 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1079 setOperationAction(ISD::FREM, MVT::f64, Expand); 1080 setOperationAction(ISD::FREM, MVT::f32, Expand); 1081 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1082 !Subtarget->isThumb1Only()) { 1083 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1084 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1085 } 1086 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1087 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1088 1089 if (!Subtarget->hasVFP4()) { 1090 setOperationAction(ISD::FMA, MVT::f64, Expand); 1091 setOperationAction(ISD::FMA, MVT::f32, Expand); 1092 } 1093 1094 // Various VFP goodness 1095 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1096 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1097 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1098 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1099 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1100 } 1101 1102 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1103 if (!Subtarget->hasFP16()) { 1104 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1105 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1106 } 1107 } 1108 1109 // Use __sincos_stret if available. 1110 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1111 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1112 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1113 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1114 } 1115 1116 // FP-ARMv8 implements a lot of rounding-like FP operations. 1117 if (Subtarget->hasFPARMv8()) { 1118 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1119 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1120 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1121 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1122 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1123 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1124 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1125 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1126 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1127 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1128 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1129 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1130 1131 if (!Subtarget->isFPOnlySP()) { 1132 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1133 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1134 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1135 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1136 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1137 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1138 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1139 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1140 } 1141 } 1142 1143 if (Subtarget->hasNEON()) { 1144 // vmin and vmax aren't available in a scalar form, so we use 1145 // a NEON instruction with an undef lane instead. 1146 setOperationAction(ISD::FMINNAN, MVT::f16, Legal); 1147 setOperationAction(ISD::FMAXNAN, MVT::f16, Legal); 1148 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1149 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1150 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1151 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1152 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1153 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1154 } 1155 1156 // We have target-specific dag combine patterns for the following nodes: 1157 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1158 setTargetDAGCombine(ISD::ADD); 1159 setTargetDAGCombine(ISD::SUB); 1160 setTargetDAGCombine(ISD::MUL); 1161 setTargetDAGCombine(ISD::AND); 1162 setTargetDAGCombine(ISD::OR); 1163 setTargetDAGCombine(ISD::XOR); 1164 1165 if (Subtarget->hasV6Ops()) 1166 setTargetDAGCombine(ISD::SRL); 1167 1168 setStackPointerRegisterToSaveRestore(ARM::SP); 1169 1170 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1171 !Subtarget->hasVFP2()) 1172 setSchedulingPreference(Sched::RegPressure); 1173 else 1174 setSchedulingPreference(Sched::Hybrid); 1175 1176 //// temporary - rewrite interface to use type 1177 MaxStoresPerMemset = 8; 1178 MaxStoresPerMemsetOptSize = 4; 1179 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1180 MaxStoresPerMemcpyOptSize = 2; 1181 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1182 MaxStoresPerMemmoveOptSize = 2; 1183 1184 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1185 // are at least 4 bytes aligned. 1186 setMinStackArgumentAlignment(4); 1187 1188 // Prefer likely predicted branches to selects on out-of-order cores. 1189 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1190 1191 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1192 } 1193 1194 bool ARMTargetLowering::useSoftFloat() const { 1195 return Subtarget->useSoftFloat(); 1196 } 1197 1198 // FIXME: It might make sense to define the representative register class as the 1199 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1200 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1201 // SPR's representative would be DPR_VFP2. This should work well if register 1202 // pressure tracking were modified such that a register use would increment the 1203 // pressure of the register class's representative and all of it's super 1204 // classes' representatives transitively. We have not implemented this because 1205 // of the difficulty prior to coalescing of modeling operand register classes 1206 // due to the common occurrence of cross class copies and subregister insertions 1207 // and extractions. 1208 std::pair<const TargetRegisterClass *, uint8_t> 1209 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1210 MVT VT) const { 1211 const TargetRegisterClass *RRC = nullptr; 1212 uint8_t Cost = 1; 1213 switch (VT.SimpleTy) { 1214 default: 1215 return TargetLowering::findRepresentativeClass(TRI, VT); 1216 // Use DPR as representative register class for all floating point 1217 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1218 // the cost is 1 for both f32 and f64. 1219 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1220 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1221 RRC = &ARM::DPRRegClass; 1222 // When NEON is used for SP, only half of the register file is available 1223 // because operations that define both SP and DP results will be constrained 1224 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1225 // coalescing by double-counting the SP regs. See the FIXME above. 1226 if (Subtarget->useNEONForSinglePrecisionFP()) 1227 Cost = 2; 1228 break; 1229 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1230 case MVT::v4f32: case MVT::v2f64: 1231 RRC = &ARM::DPRRegClass; 1232 Cost = 2; 1233 break; 1234 case MVT::v4i64: 1235 RRC = &ARM::DPRRegClass; 1236 Cost = 4; 1237 break; 1238 case MVT::v8i64: 1239 RRC = &ARM::DPRRegClass; 1240 Cost = 8; 1241 break; 1242 } 1243 return std::make_pair(RRC, Cost); 1244 } 1245 1246 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1247 switch ((ARMISD::NodeType)Opcode) { 1248 case ARMISD::FIRST_NUMBER: break; 1249 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1250 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1251 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1252 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1253 case ARMISD::CALL: return "ARMISD::CALL"; 1254 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1255 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1256 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1257 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1258 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1259 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1260 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1261 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1262 case ARMISD::CMP: return "ARMISD::CMP"; 1263 case ARMISD::CMN: return "ARMISD::CMN"; 1264 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1265 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1266 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1267 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1268 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1269 1270 case ARMISD::CMOV: return "ARMISD::CMOV"; 1271 1272 case ARMISD::SSAT: return "ARMISD::SSAT"; 1273 case ARMISD::USAT: return "ARMISD::USAT"; 1274 1275 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1276 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1277 case ARMISD::RRX: return "ARMISD::RRX"; 1278 1279 case ARMISD::ADDC: return "ARMISD::ADDC"; 1280 case ARMISD::ADDE: return "ARMISD::ADDE"; 1281 case ARMISD::SUBC: return "ARMISD::SUBC"; 1282 case ARMISD::SUBE: return "ARMISD::SUBE"; 1283 1284 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1285 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1286 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1287 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1288 case ARMISD::VMOVSR: return "ARMISD::VMOVSR"; 1289 1290 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1291 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1292 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1293 1294 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1295 1296 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1297 1298 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1299 1300 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1301 1302 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1303 1304 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1305 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1306 1307 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1308 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1309 case ARMISD::VCGE: return "ARMISD::VCGE"; 1310 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1311 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1312 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1313 case ARMISD::VCGT: return "ARMISD::VCGT"; 1314 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1315 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1316 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1317 case ARMISD::VTST: return "ARMISD::VTST"; 1318 1319 case ARMISD::VSHL: return "ARMISD::VSHL"; 1320 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1321 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1322 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1323 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1324 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1325 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1326 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1327 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1328 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1329 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1330 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1331 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1332 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1333 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1334 case ARMISD::VSLI: return "ARMISD::VSLI"; 1335 case ARMISD::VSRI: return "ARMISD::VSRI"; 1336 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1337 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1338 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1339 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1340 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1341 case ARMISD::VDUP: return "ARMISD::VDUP"; 1342 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1343 case ARMISD::VEXT: return "ARMISD::VEXT"; 1344 case ARMISD::VREV64: return "ARMISD::VREV64"; 1345 case ARMISD::VREV32: return "ARMISD::VREV32"; 1346 case ARMISD::VREV16: return "ARMISD::VREV16"; 1347 case ARMISD::VZIP: return "ARMISD::VZIP"; 1348 case ARMISD::VUZP: return "ARMISD::VUZP"; 1349 case ARMISD::VTRN: return "ARMISD::VTRN"; 1350 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1351 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1352 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1353 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1354 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1355 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1356 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1357 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1358 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1359 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1360 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1361 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1362 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1363 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1364 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1365 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1366 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1367 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1368 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1369 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1370 case ARMISD::BFI: return "ARMISD::BFI"; 1371 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1372 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1373 case ARMISD::VBSL: return "ARMISD::VBSL"; 1374 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1375 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1376 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1377 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1378 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1379 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1380 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1381 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1382 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1383 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1384 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1385 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1386 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1387 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1388 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1389 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1390 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1391 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1392 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1393 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1394 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1395 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1396 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1397 } 1398 return nullptr; 1399 } 1400 1401 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1402 EVT VT) const { 1403 if (!VT.isVector()) 1404 return getPointerTy(DL); 1405 return VT.changeVectorElementTypeToInteger(); 1406 } 1407 1408 /// getRegClassFor - Return the register class that should be used for the 1409 /// specified value type. 1410 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1411 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1412 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1413 // load / store 4 to 8 consecutive D registers. 1414 if (Subtarget->hasNEON()) { 1415 if (VT == MVT::v4i64) 1416 return &ARM::QQPRRegClass; 1417 if (VT == MVT::v8i64) 1418 return &ARM::QQQQPRRegClass; 1419 } 1420 return TargetLowering::getRegClassFor(VT); 1421 } 1422 1423 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1424 // source/dest is aligned and the copy size is large enough. We therefore want 1425 // to align such objects passed to memory intrinsics. 1426 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1427 unsigned &PrefAlign) const { 1428 if (!isa<MemIntrinsic>(CI)) 1429 return false; 1430 MinSize = 8; 1431 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1432 // cycle faster than 4-byte aligned LDM. 1433 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1434 return true; 1435 } 1436 1437 // Create a fast isel object. 1438 FastISel * 1439 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1440 const TargetLibraryInfo *libInfo) const { 1441 return ARM::createFastISel(funcInfo, libInfo); 1442 } 1443 1444 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1445 unsigned NumVals = N->getNumValues(); 1446 if (!NumVals) 1447 return Sched::RegPressure; 1448 1449 for (unsigned i = 0; i != NumVals; ++i) { 1450 EVT VT = N->getValueType(i); 1451 if (VT == MVT::Glue || VT == MVT::Other) 1452 continue; 1453 if (VT.isFloatingPoint() || VT.isVector()) 1454 return Sched::ILP; 1455 } 1456 1457 if (!N->isMachineOpcode()) 1458 return Sched::RegPressure; 1459 1460 // Load are scheduled for latency even if there instruction itinerary 1461 // is not available. 1462 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1463 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1464 1465 if (MCID.getNumDefs() == 0) 1466 return Sched::RegPressure; 1467 if (!Itins->isEmpty() && 1468 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1469 return Sched::ILP; 1470 1471 return Sched::RegPressure; 1472 } 1473 1474 //===----------------------------------------------------------------------===// 1475 // Lowering Code 1476 //===----------------------------------------------------------------------===// 1477 1478 static bool isSRL16(const SDValue &Op) { 1479 if (Op.getOpcode() != ISD::SRL) 1480 return false; 1481 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1482 return Const->getZExtValue() == 16; 1483 return false; 1484 } 1485 1486 static bool isSRA16(const SDValue &Op) { 1487 if (Op.getOpcode() != ISD::SRA) 1488 return false; 1489 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1490 return Const->getZExtValue() == 16; 1491 return false; 1492 } 1493 1494 static bool isSHL16(const SDValue &Op) { 1495 if (Op.getOpcode() != ISD::SHL) 1496 return false; 1497 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1498 return Const->getZExtValue() == 16; 1499 return false; 1500 } 1501 1502 // Check for a signed 16-bit value. We special case SRA because it makes it 1503 // more simple when also looking for SRAs that aren't sign extending a 1504 // smaller value. Without the check, we'd need to take extra care with 1505 // checking order for some operations. 1506 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1507 if (isSRA16(Op)) 1508 return isSHL16(Op.getOperand(0)); 1509 return DAG.ComputeNumSignBits(Op) == 17; 1510 } 1511 1512 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1513 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1514 switch (CC) { 1515 default: llvm_unreachable("Unknown condition code!"); 1516 case ISD::SETNE: return ARMCC::NE; 1517 case ISD::SETEQ: return ARMCC::EQ; 1518 case ISD::SETGT: return ARMCC::GT; 1519 case ISD::SETGE: return ARMCC::GE; 1520 case ISD::SETLT: return ARMCC::LT; 1521 case ISD::SETLE: return ARMCC::LE; 1522 case ISD::SETUGT: return ARMCC::HI; 1523 case ISD::SETUGE: return ARMCC::HS; 1524 case ISD::SETULT: return ARMCC::LO; 1525 case ISD::SETULE: return ARMCC::LS; 1526 } 1527 } 1528 1529 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1530 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1531 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1532 CondCode2 = ARMCC::AL; 1533 InvalidOnQNaN = true; 1534 switch (CC) { 1535 default: llvm_unreachable("Unknown FP condition!"); 1536 case ISD::SETEQ: 1537 case ISD::SETOEQ: 1538 CondCode = ARMCC::EQ; 1539 InvalidOnQNaN = false; 1540 break; 1541 case ISD::SETGT: 1542 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1543 case ISD::SETGE: 1544 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1545 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1546 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1547 case ISD::SETONE: 1548 CondCode = ARMCC::MI; 1549 CondCode2 = ARMCC::GT; 1550 InvalidOnQNaN = false; 1551 break; 1552 case ISD::SETO: CondCode = ARMCC::VC; break; 1553 case ISD::SETUO: CondCode = ARMCC::VS; break; 1554 case ISD::SETUEQ: 1555 CondCode = ARMCC::EQ; 1556 CondCode2 = ARMCC::VS; 1557 InvalidOnQNaN = false; 1558 break; 1559 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1560 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1561 case ISD::SETLT: 1562 case ISD::SETULT: CondCode = ARMCC::LT; break; 1563 case ISD::SETLE: 1564 case ISD::SETULE: CondCode = ARMCC::LE; break; 1565 case ISD::SETNE: 1566 case ISD::SETUNE: 1567 CondCode = ARMCC::NE; 1568 InvalidOnQNaN = false; 1569 break; 1570 } 1571 } 1572 1573 //===----------------------------------------------------------------------===// 1574 // Calling Convention Implementation 1575 //===----------------------------------------------------------------------===// 1576 1577 #include "ARMGenCallingConv.inc" 1578 1579 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1580 /// account presence of floating point hardware and calling convention 1581 /// limitations, such as support for variadic functions. 1582 CallingConv::ID 1583 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1584 bool isVarArg) const { 1585 switch (CC) { 1586 default: 1587 report_fatal_error("Unsupported calling convention"); 1588 case CallingConv::ARM_AAPCS: 1589 case CallingConv::ARM_APCS: 1590 case CallingConv::GHC: 1591 return CC; 1592 case CallingConv::PreserveMost: 1593 return CallingConv::PreserveMost; 1594 case CallingConv::ARM_AAPCS_VFP: 1595 case CallingConv::Swift: 1596 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1597 case CallingConv::C: 1598 if (!Subtarget->isAAPCS_ABI()) 1599 return CallingConv::ARM_APCS; 1600 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1601 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1602 !isVarArg) 1603 return CallingConv::ARM_AAPCS_VFP; 1604 else 1605 return CallingConv::ARM_AAPCS; 1606 case CallingConv::Fast: 1607 case CallingConv::CXX_FAST_TLS: 1608 if (!Subtarget->isAAPCS_ABI()) { 1609 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1610 return CallingConv::Fast; 1611 return CallingConv::ARM_APCS; 1612 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1613 return CallingConv::ARM_AAPCS_VFP; 1614 else 1615 return CallingConv::ARM_AAPCS; 1616 } 1617 } 1618 1619 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1620 bool isVarArg) const { 1621 return CCAssignFnForNode(CC, false, isVarArg); 1622 } 1623 1624 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1625 bool isVarArg) const { 1626 return CCAssignFnForNode(CC, true, isVarArg); 1627 } 1628 1629 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1630 /// CallingConvention. 1631 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1632 bool Return, 1633 bool isVarArg) const { 1634 switch (getEffectiveCallingConv(CC, isVarArg)) { 1635 default: 1636 report_fatal_error("Unsupported calling convention"); 1637 case CallingConv::ARM_APCS: 1638 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1639 case CallingConv::ARM_AAPCS: 1640 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1641 case CallingConv::ARM_AAPCS_VFP: 1642 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1643 case CallingConv::Fast: 1644 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1645 case CallingConv::GHC: 1646 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1647 case CallingConv::PreserveMost: 1648 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1649 } 1650 } 1651 1652 /// LowerCallResult - Lower the result values of a call into the 1653 /// appropriate copies out of appropriate physical registers. 1654 SDValue ARMTargetLowering::LowerCallResult( 1655 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1656 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1657 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1658 SDValue ThisVal) const { 1659 // Assign locations to each value returned by this call. 1660 SmallVector<CCValAssign, 16> RVLocs; 1661 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1662 *DAG.getContext()); 1663 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1664 1665 // Copy all of the result registers out of their specified physreg. 1666 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1667 CCValAssign VA = RVLocs[i]; 1668 1669 // Pass 'this' value directly from the argument to return value, to avoid 1670 // reg unit interference 1671 if (i == 0 && isThisReturn) { 1672 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1673 "unexpected return calling convention register assignment"); 1674 InVals.push_back(ThisVal); 1675 continue; 1676 } 1677 1678 SDValue Val; 1679 if (VA.needsCustom()) { 1680 // Handle f64 or half of a v2f64. 1681 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1682 InFlag); 1683 Chain = Lo.getValue(1); 1684 InFlag = Lo.getValue(2); 1685 VA = RVLocs[++i]; // skip ahead to next loc 1686 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1687 InFlag); 1688 Chain = Hi.getValue(1); 1689 InFlag = Hi.getValue(2); 1690 if (!Subtarget->isLittle()) 1691 std::swap (Lo, Hi); 1692 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1693 1694 if (VA.getLocVT() == MVT::v2f64) { 1695 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1696 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1697 DAG.getConstant(0, dl, MVT::i32)); 1698 1699 VA = RVLocs[++i]; // skip ahead to next loc 1700 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1701 Chain = Lo.getValue(1); 1702 InFlag = Lo.getValue(2); 1703 VA = RVLocs[++i]; // skip ahead to next loc 1704 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1705 Chain = Hi.getValue(1); 1706 InFlag = Hi.getValue(2); 1707 if (!Subtarget->isLittle()) 1708 std::swap (Lo, Hi); 1709 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1710 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1711 DAG.getConstant(1, dl, MVT::i32)); 1712 } 1713 } else { 1714 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1715 InFlag); 1716 Chain = Val.getValue(1); 1717 InFlag = Val.getValue(2); 1718 } 1719 1720 switch (VA.getLocInfo()) { 1721 default: llvm_unreachable("Unknown loc info!"); 1722 case CCValAssign::Full: break; 1723 case CCValAssign::BCvt: 1724 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1725 break; 1726 } 1727 1728 InVals.push_back(Val); 1729 } 1730 1731 return Chain; 1732 } 1733 1734 /// LowerMemOpCallTo - Store the argument to the stack. 1735 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1736 SDValue Arg, const SDLoc &dl, 1737 SelectionDAG &DAG, 1738 const CCValAssign &VA, 1739 ISD::ArgFlagsTy Flags) const { 1740 unsigned LocMemOffset = VA.getLocMemOffset(); 1741 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1742 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1743 StackPtr, PtrOff); 1744 return DAG.getStore( 1745 Chain, dl, Arg, PtrOff, 1746 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1747 } 1748 1749 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1750 SDValue Chain, SDValue &Arg, 1751 RegsToPassVector &RegsToPass, 1752 CCValAssign &VA, CCValAssign &NextVA, 1753 SDValue &StackPtr, 1754 SmallVectorImpl<SDValue> &MemOpChains, 1755 ISD::ArgFlagsTy Flags) const { 1756 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1757 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1758 unsigned id = Subtarget->isLittle() ? 0 : 1; 1759 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1760 1761 if (NextVA.isRegLoc()) 1762 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1763 else { 1764 assert(NextVA.isMemLoc()); 1765 if (!StackPtr.getNode()) 1766 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1767 getPointerTy(DAG.getDataLayout())); 1768 1769 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1770 dl, DAG, NextVA, 1771 Flags)); 1772 } 1773 } 1774 1775 /// LowerCall - Lowering a call into a callseq_start <- 1776 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1777 /// nodes. 1778 SDValue 1779 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1780 SmallVectorImpl<SDValue> &InVals) const { 1781 SelectionDAG &DAG = CLI.DAG; 1782 SDLoc &dl = CLI.DL; 1783 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1784 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1785 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1786 SDValue Chain = CLI.Chain; 1787 SDValue Callee = CLI.Callee; 1788 bool &isTailCall = CLI.IsTailCall; 1789 CallingConv::ID CallConv = CLI.CallConv; 1790 bool doesNotRet = CLI.DoesNotReturn; 1791 bool isVarArg = CLI.IsVarArg; 1792 1793 MachineFunction &MF = DAG.getMachineFunction(); 1794 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1795 bool isThisReturn = false; 1796 bool isSibCall = false; 1797 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 1798 1799 // Disable tail calls if they're not supported. 1800 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1801 isTailCall = false; 1802 1803 if (isTailCall) { 1804 // Check if it's really possible to do a tail call. 1805 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1806 isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(), 1807 Outs, OutVals, Ins, DAG); 1808 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1809 report_fatal_error("failed to perform tail call elimination on a call " 1810 "site marked musttail"); 1811 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1812 // detected sibcalls. 1813 if (isTailCall) { 1814 ++NumTailCalls; 1815 isSibCall = true; 1816 } 1817 } 1818 1819 // Analyze operands of the call, assigning locations to each operand. 1820 SmallVector<CCValAssign, 16> ArgLocs; 1821 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1822 *DAG.getContext()); 1823 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1824 1825 // Get a count of how many bytes are to be pushed on the stack. 1826 unsigned NumBytes = CCInfo.getNextStackOffset(); 1827 1828 // For tail calls, memory operands are available in our caller's stack. 1829 if (isSibCall) 1830 NumBytes = 0; 1831 1832 // Adjust the stack pointer for the new arguments... 1833 // These operations are automatically eliminated by the prolog/epilog pass 1834 if (!isSibCall) 1835 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 1836 1837 SDValue StackPtr = 1838 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1839 1840 RegsToPassVector RegsToPass; 1841 SmallVector<SDValue, 8> MemOpChains; 1842 1843 // Walk the register/memloc assignments, inserting copies/loads. In the case 1844 // of tail call optimization, arguments are handled later. 1845 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1846 i != e; 1847 ++i, ++realArgIdx) { 1848 CCValAssign &VA = ArgLocs[i]; 1849 SDValue Arg = OutVals[realArgIdx]; 1850 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1851 bool isByVal = Flags.isByVal(); 1852 1853 // Promote the value if needed. 1854 switch (VA.getLocInfo()) { 1855 default: llvm_unreachable("Unknown loc info!"); 1856 case CCValAssign::Full: break; 1857 case CCValAssign::SExt: 1858 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1859 break; 1860 case CCValAssign::ZExt: 1861 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1862 break; 1863 case CCValAssign::AExt: 1864 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1865 break; 1866 case CCValAssign::BCvt: 1867 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1868 break; 1869 } 1870 1871 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1872 if (VA.needsCustom()) { 1873 if (VA.getLocVT() == MVT::v2f64) { 1874 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1875 DAG.getConstant(0, dl, MVT::i32)); 1876 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1877 DAG.getConstant(1, dl, MVT::i32)); 1878 1879 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1880 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1881 1882 VA = ArgLocs[++i]; // skip ahead to next loc 1883 if (VA.isRegLoc()) { 1884 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1885 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1886 } else { 1887 assert(VA.isMemLoc()); 1888 1889 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1890 dl, DAG, VA, Flags)); 1891 } 1892 } else { 1893 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1894 StackPtr, MemOpChains, Flags); 1895 } 1896 } else if (VA.isRegLoc()) { 1897 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1898 Outs[0].VT == MVT::i32) { 1899 assert(VA.getLocVT() == MVT::i32 && 1900 "unexpected calling convention register assignment"); 1901 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1902 "unexpected use of 'returned'"); 1903 isThisReturn = true; 1904 } 1905 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1906 } else if (isByVal) { 1907 assert(VA.isMemLoc()); 1908 unsigned offset = 0; 1909 1910 // True if this byval aggregate will be split between registers 1911 // and memory. 1912 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1913 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1914 1915 if (CurByValIdx < ByValArgsCount) { 1916 1917 unsigned RegBegin, RegEnd; 1918 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1919 1920 EVT PtrVT = 1921 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1922 unsigned int i, j; 1923 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1924 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1925 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1926 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1927 MachinePointerInfo(), 1928 DAG.InferPtrAlignment(AddArg)); 1929 MemOpChains.push_back(Load.getValue(1)); 1930 RegsToPass.push_back(std::make_pair(j, Load)); 1931 } 1932 1933 // If parameter size outsides register area, "offset" value 1934 // helps us to calculate stack slot for remained part properly. 1935 offset = RegEnd - RegBegin; 1936 1937 CCInfo.nextInRegsParam(); 1938 } 1939 1940 if (Flags.getByValSize() > 4*offset) { 1941 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1942 unsigned LocMemOffset = VA.getLocMemOffset(); 1943 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1944 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1945 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1946 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1947 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1948 MVT::i32); 1949 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1950 MVT::i32); 1951 1952 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1953 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1954 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1955 Ops)); 1956 } 1957 } else if (!isSibCall) { 1958 assert(VA.isMemLoc()); 1959 1960 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1961 dl, DAG, VA, Flags)); 1962 } 1963 } 1964 1965 if (!MemOpChains.empty()) 1966 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1967 1968 // Build a sequence of copy-to-reg nodes chained together with token chain 1969 // and flag operands which copy the outgoing args into the appropriate regs. 1970 SDValue InFlag; 1971 // Tail call byval lowering might overwrite argument registers so in case of 1972 // tail call optimization the copies to registers are lowered later. 1973 if (!isTailCall) 1974 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1975 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1976 RegsToPass[i].second, InFlag); 1977 InFlag = Chain.getValue(1); 1978 } 1979 1980 // For tail calls lower the arguments to the 'real' stack slot. 1981 if (isTailCall) { 1982 // Force all the incoming stack arguments to be loaded from the stack 1983 // before any new outgoing arguments are stored to the stack, because the 1984 // outgoing stack slots may alias the incoming argument stack slots, and 1985 // the alias isn't otherwise explicit. This is slightly more conservative 1986 // than necessary, because it means that each store effectively depends 1987 // on every argument instead of just those arguments it would clobber. 1988 1989 // Do not flag preceding copytoreg stuff together with the following stuff. 1990 InFlag = SDValue(); 1991 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1992 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1993 RegsToPass[i].second, InFlag); 1994 InFlag = Chain.getValue(1); 1995 } 1996 InFlag = SDValue(); 1997 } 1998 1999 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 2000 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 2001 // node so that legalize doesn't hack it. 2002 bool isDirect = false; 2003 2004 const TargetMachine &TM = getTargetMachine(); 2005 const Module *Mod = MF.getFunction().getParent(); 2006 const GlobalValue *GV = nullptr; 2007 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 2008 GV = G->getGlobal(); 2009 bool isStub = 2010 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2011 2012 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2013 bool isLocalARMFunc = false; 2014 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2015 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2016 2017 if (Subtarget->genLongCalls()) { 2018 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2019 "long-calls codegen is not position independent!"); 2020 // Handle a global address or an external symbol. If it's not one of 2021 // those, the target's already in a register, so we don't need to do 2022 // anything extra. 2023 if (isa<GlobalAddressSDNode>(Callee)) { 2024 // Create a constant pool entry for the callee address 2025 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2026 ARMConstantPoolValue *CPV = 2027 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2028 2029 // Get the address of the callee into a register 2030 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2031 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2032 Callee = DAG.getLoad( 2033 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2034 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2035 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2036 const char *Sym = S->getSymbol(); 2037 2038 // Create a constant pool entry for the callee address 2039 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2040 ARMConstantPoolValue *CPV = 2041 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2042 ARMPCLabelIndex, 0); 2043 // Get the address of the callee into a register 2044 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2045 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2046 Callee = DAG.getLoad( 2047 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2048 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2049 } 2050 } else if (isa<GlobalAddressSDNode>(Callee)) { 2051 // If we're optimizing for minimum size and the function is called three or 2052 // more times in this block, we can improve codesize by calling indirectly 2053 // as BLXr has a 16-bit encoding. 2054 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2055 auto *BB = CLI.CS.getParent(); 2056 bool PreferIndirect = 2057 Subtarget->isThumb() && MF.getFunction().optForMinSize() && 2058 count_if(GV->users(), [&BB](const User *U) { 2059 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2060 }) > 2; 2061 2062 if (!PreferIndirect) { 2063 isDirect = true; 2064 bool isDef = GV->isStrongDefinitionForLinker(); 2065 2066 // ARM call to a local ARM function is predicable. 2067 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2068 // tBX takes a register source operand. 2069 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2070 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2071 Callee = DAG.getNode( 2072 ARMISD::WrapperPIC, dl, PtrVt, 2073 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2074 Callee = DAG.getLoad( 2075 PtrVt, dl, DAG.getEntryNode(), Callee, 2076 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2077 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2078 MachineMemOperand::MOInvariant); 2079 } else if (Subtarget->isTargetCOFF()) { 2080 assert(Subtarget->isTargetWindows() && 2081 "Windows is the only supported COFF target"); 2082 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2083 ? ARMII::MO_DLLIMPORT 2084 : ARMII::MO_NO_FLAG; 2085 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2086 TargetFlags); 2087 if (GV->hasDLLImportStorageClass()) 2088 Callee = 2089 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2090 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2091 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2092 } else { 2093 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2094 } 2095 } 2096 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2097 isDirect = true; 2098 // tBX takes a register source operand. 2099 const char *Sym = S->getSymbol(); 2100 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2101 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2102 ARMConstantPoolValue *CPV = 2103 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2104 ARMPCLabelIndex, 4); 2105 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2106 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2107 Callee = DAG.getLoad( 2108 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2109 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2110 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2111 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2112 } else { 2113 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2114 } 2115 } 2116 2117 // FIXME: handle tail calls differently. 2118 unsigned CallOpc; 2119 if (Subtarget->isThumb()) { 2120 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2121 CallOpc = ARMISD::CALL_NOLINK; 2122 else 2123 CallOpc = ARMISD::CALL; 2124 } else { 2125 if (!isDirect && !Subtarget->hasV5TOps()) 2126 CallOpc = ARMISD::CALL_NOLINK; 2127 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2128 // Emit regular call when code size is the priority 2129 !MF.getFunction().optForMinSize()) 2130 // "mov lr, pc; b _foo" to avoid confusing the RSP 2131 CallOpc = ARMISD::CALL_NOLINK; 2132 else 2133 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2134 } 2135 2136 std::vector<SDValue> Ops; 2137 Ops.push_back(Chain); 2138 Ops.push_back(Callee); 2139 2140 // Add argument registers to the end of the list so that they are known live 2141 // into the call. 2142 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2143 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2144 RegsToPass[i].second.getValueType())); 2145 2146 // Add a register mask operand representing the call-preserved registers. 2147 if (!isTailCall) { 2148 const uint32_t *Mask; 2149 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2150 if (isThisReturn) { 2151 // For 'this' returns, use the R0-preserving mask if applicable 2152 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2153 if (!Mask) { 2154 // Set isThisReturn to false if the calling convention is not one that 2155 // allows 'returned' to be modeled in this way, so LowerCallResult does 2156 // not try to pass 'this' straight through 2157 isThisReturn = false; 2158 Mask = ARI->getCallPreservedMask(MF, CallConv); 2159 } 2160 } else 2161 Mask = ARI->getCallPreservedMask(MF, CallConv); 2162 2163 assert(Mask && "Missing call preserved mask for calling convention"); 2164 Ops.push_back(DAG.getRegisterMask(Mask)); 2165 } 2166 2167 if (InFlag.getNode()) 2168 Ops.push_back(InFlag); 2169 2170 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2171 if (isTailCall) { 2172 MF.getFrameInfo().setHasTailCall(); 2173 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2174 } 2175 2176 // Returns a chain and a flag for retval copy to use. 2177 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2178 InFlag = Chain.getValue(1); 2179 2180 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2181 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2182 if (!Ins.empty()) 2183 InFlag = Chain.getValue(1); 2184 2185 // Handle result values, copying them out of physregs into vregs that we 2186 // return. 2187 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2188 InVals, isThisReturn, 2189 isThisReturn ? OutVals[0] : SDValue()); 2190 } 2191 2192 /// HandleByVal - Every parameter *after* a byval parameter is passed 2193 /// on the stack. Remember the next parameter register to allocate, 2194 /// and then confiscate the rest of the parameter registers to insure 2195 /// this. 2196 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2197 unsigned Align) const { 2198 // Byval (as with any stack) slots are always at least 4 byte aligned. 2199 Align = std::max(Align, 4U); 2200 2201 unsigned Reg = State->AllocateReg(GPRArgRegs); 2202 if (!Reg) 2203 return; 2204 2205 unsigned AlignInRegs = Align / 4; 2206 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2207 for (unsigned i = 0; i < Waste; ++i) 2208 Reg = State->AllocateReg(GPRArgRegs); 2209 2210 if (!Reg) 2211 return; 2212 2213 unsigned Excess = 4 * (ARM::R4 - Reg); 2214 2215 // Special case when NSAA != SP and parameter size greater than size of 2216 // all remained GPR regs. In that case we can't split parameter, we must 2217 // send it to stack. We also must set NCRN to R4, so waste all 2218 // remained registers. 2219 const unsigned NSAAOffset = State->getNextStackOffset(); 2220 if (NSAAOffset != 0 && Size > Excess) { 2221 while (State->AllocateReg(GPRArgRegs)) 2222 ; 2223 return; 2224 } 2225 2226 // First register for byval parameter is the first register that wasn't 2227 // allocated before this method call, so it would be "reg". 2228 // If parameter is small enough to be saved in range [reg, r4), then 2229 // the end (first after last) register would be reg + param-size-in-regs, 2230 // else parameter would be splitted between registers and stack, 2231 // end register would be r4 in this case. 2232 unsigned ByValRegBegin = Reg; 2233 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2234 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2235 // Note, first register is allocated in the beginning of function already, 2236 // allocate remained amount of registers we need. 2237 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2238 State->AllocateReg(GPRArgRegs); 2239 // A byval parameter that is split between registers and memory needs its 2240 // size truncated here. 2241 // In the case where the entire structure fits in registers, we set the 2242 // size in memory to zero. 2243 Size = std::max<int>(Size - Excess, 0); 2244 } 2245 2246 /// MatchingStackOffset - Return true if the given stack call argument is 2247 /// already available in the same position (relatively) of the caller's 2248 /// incoming argument stack. 2249 static 2250 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2251 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2252 const TargetInstrInfo *TII) { 2253 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2254 int FI = std::numeric_limits<int>::max(); 2255 if (Arg.getOpcode() == ISD::CopyFromReg) { 2256 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2257 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2258 return false; 2259 MachineInstr *Def = MRI->getVRegDef(VR); 2260 if (!Def) 2261 return false; 2262 if (!Flags.isByVal()) { 2263 if (!TII->isLoadFromStackSlot(*Def, FI)) 2264 return false; 2265 } else { 2266 return false; 2267 } 2268 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2269 if (Flags.isByVal()) 2270 // ByVal argument is passed in as a pointer but it's now being 2271 // dereferenced. e.g. 2272 // define @foo(%struct.X* %A) { 2273 // tail call @bar(%struct.X* byval %A) 2274 // } 2275 return false; 2276 SDValue Ptr = Ld->getBasePtr(); 2277 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2278 if (!FINode) 2279 return false; 2280 FI = FINode->getIndex(); 2281 } else 2282 return false; 2283 2284 assert(FI != std::numeric_limits<int>::max()); 2285 if (!MFI.isFixedObjectIndex(FI)) 2286 return false; 2287 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2288 } 2289 2290 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2291 /// for tail call optimization. Targets which want to do tail call 2292 /// optimization should implement this function. 2293 bool 2294 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2295 CallingConv::ID CalleeCC, 2296 bool isVarArg, 2297 bool isCalleeStructRet, 2298 bool isCallerStructRet, 2299 const SmallVectorImpl<ISD::OutputArg> &Outs, 2300 const SmallVectorImpl<SDValue> &OutVals, 2301 const SmallVectorImpl<ISD::InputArg> &Ins, 2302 SelectionDAG& DAG) const { 2303 MachineFunction &MF = DAG.getMachineFunction(); 2304 const Function &CallerF = MF.getFunction(); 2305 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2306 2307 assert(Subtarget->supportsTailCall()); 2308 2309 // Tail calls to function pointers cannot be optimized for Thumb1 if the args 2310 // to the call take up r0-r3. The reason is that there are no legal registers 2311 // left to hold the pointer to the function to be called. 2312 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2313 !isa<GlobalAddressSDNode>(Callee.getNode())) 2314 return false; 2315 2316 // Look for obvious safe cases to perform tail call optimization that do not 2317 // require ABI changes. This is what gcc calls sibcall. 2318 2319 // Exception-handling functions need a special set of instructions to indicate 2320 // a return to the hardware. Tail-calling another function would probably 2321 // break this. 2322 if (CallerF.hasFnAttribute("interrupt")) 2323 return false; 2324 2325 // Also avoid sibcall optimization if either caller or callee uses struct 2326 // return semantics. 2327 if (isCalleeStructRet || isCallerStructRet) 2328 return false; 2329 2330 // Externally-defined functions with weak linkage should not be 2331 // tail-called on ARM when the OS does not support dynamic 2332 // pre-emption of symbols, as the AAELF spec requires normal calls 2333 // to undefined weak functions to be replaced with a NOP or jump to the 2334 // next instruction. The behaviour of branch instructions in this 2335 // situation (as used for tail calls) is implementation-defined, so we 2336 // cannot rely on the linker replacing the tail call with a return. 2337 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2338 const GlobalValue *GV = G->getGlobal(); 2339 const Triple &TT = getTargetMachine().getTargetTriple(); 2340 if (GV->hasExternalWeakLinkage() && 2341 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2342 return false; 2343 } 2344 2345 // Check that the call results are passed in the same way. 2346 LLVMContext &C = *DAG.getContext(); 2347 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2348 CCAssignFnForReturn(CalleeCC, isVarArg), 2349 CCAssignFnForReturn(CallerCC, isVarArg))) 2350 return false; 2351 // The callee has to preserve all registers the caller needs to preserve. 2352 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2353 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2354 if (CalleeCC != CallerCC) { 2355 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2356 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2357 return false; 2358 } 2359 2360 // If Caller's vararg or byval argument has been split between registers and 2361 // stack, do not perform tail call, since part of the argument is in caller's 2362 // local frame. 2363 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2364 if (AFI_Caller->getArgRegsSaveSize()) 2365 return false; 2366 2367 // If the callee takes no arguments then go on to check the results of the 2368 // call. 2369 if (!Outs.empty()) { 2370 // Check if stack adjustment is needed. For now, do not do this if any 2371 // argument is passed on the stack. 2372 SmallVector<CCValAssign, 16> ArgLocs; 2373 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2374 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2375 if (CCInfo.getNextStackOffset()) { 2376 // Check if the arguments are already laid out in the right way as 2377 // the caller's fixed stack objects. 2378 MachineFrameInfo &MFI = MF.getFrameInfo(); 2379 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2380 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2381 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2382 i != e; 2383 ++i, ++realArgIdx) { 2384 CCValAssign &VA = ArgLocs[i]; 2385 EVT RegVT = VA.getLocVT(); 2386 SDValue Arg = OutVals[realArgIdx]; 2387 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2388 if (VA.getLocInfo() == CCValAssign::Indirect) 2389 return false; 2390 if (VA.needsCustom()) { 2391 // f64 and vector types are split into multiple registers or 2392 // register/stack-slot combinations. The types will not match 2393 // the registers; give up on memory f64 refs until we figure 2394 // out what to do about this. 2395 if (!VA.isRegLoc()) 2396 return false; 2397 if (!ArgLocs[++i].isRegLoc()) 2398 return false; 2399 if (RegVT == MVT::v2f64) { 2400 if (!ArgLocs[++i].isRegLoc()) 2401 return false; 2402 if (!ArgLocs[++i].isRegLoc()) 2403 return false; 2404 } 2405 } else if (!VA.isRegLoc()) { 2406 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2407 MFI, MRI, TII)) 2408 return false; 2409 } 2410 } 2411 } 2412 2413 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2414 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2415 return false; 2416 } 2417 2418 return true; 2419 } 2420 2421 bool 2422 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2423 MachineFunction &MF, bool isVarArg, 2424 const SmallVectorImpl<ISD::OutputArg> &Outs, 2425 LLVMContext &Context) const { 2426 SmallVector<CCValAssign, 16> RVLocs; 2427 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2428 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2429 } 2430 2431 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2432 const SDLoc &DL, SelectionDAG &DAG) { 2433 const MachineFunction &MF = DAG.getMachineFunction(); 2434 const Function &F = MF.getFunction(); 2435 2436 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2437 2438 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2439 // version of the "preferred return address". These offsets affect the return 2440 // instruction if this is a return from PL1 without hypervisor extensions. 2441 // IRQ/FIQ: +4 "subs pc, lr, #4" 2442 // SWI: 0 "subs pc, lr, #0" 2443 // ABORT: +4 "subs pc, lr, #4" 2444 // UNDEF: +4/+2 "subs pc, lr, #0" 2445 // UNDEF varies depending on where the exception came from ARM or Thumb 2446 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2447 2448 int64_t LROffset; 2449 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2450 IntKind == "ABORT") 2451 LROffset = 4; 2452 else if (IntKind == "SWI" || IntKind == "UNDEF") 2453 LROffset = 0; 2454 else 2455 report_fatal_error("Unsupported interrupt attribute. If present, value " 2456 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2457 2458 RetOps.insert(RetOps.begin() + 1, 2459 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2460 2461 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2462 } 2463 2464 SDValue 2465 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2466 bool isVarArg, 2467 const SmallVectorImpl<ISD::OutputArg> &Outs, 2468 const SmallVectorImpl<SDValue> &OutVals, 2469 const SDLoc &dl, SelectionDAG &DAG) const { 2470 // CCValAssign - represent the assignment of the return value to a location. 2471 SmallVector<CCValAssign, 16> RVLocs; 2472 2473 // CCState - Info about the registers and stack slots. 2474 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2475 *DAG.getContext()); 2476 2477 // Analyze outgoing return values. 2478 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2479 2480 SDValue Flag; 2481 SmallVector<SDValue, 4> RetOps; 2482 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2483 bool isLittleEndian = Subtarget->isLittle(); 2484 2485 MachineFunction &MF = DAG.getMachineFunction(); 2486 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2487 AFI->setReturnRegsCount(RVLocs.size()); 2488 2489 // Copy the result values into the output registers. 2490 for (unsigned i = 0, realRVLocIdx = 0; 2491 i != RVLocs.size(); 2492 ++i, ++realRVLocIdx) { 2493 CCValAssign &VA = RVLocs[i]; 2494 assert(VA.isRegLoc() && "Can only return in registers!"); 2495 2496 SDValue Arg = OutVals[realRVLocIdx]; 2497 bool ReturnF16 = false; 2498 2499 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2500 // Half-precision return values can be returned like this: 2501 // 2502 // t11 f16 = fadd ... 2503 // t12: i16 = bitcast t11 2504 // t13: i32 = zero_extend t12 2505 // t14: f32 = bitcast t13 <~~~~~~~ Arg 2506 // 2507 // to avoid code generation for bitcasts, we simply set Arg to the node 2508 // that produces the f16 value, t11 in this case. 2509 // 2510 if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) { 2511 SDValue ZE = Arg.getOperand(0); 2512 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2513 SDValue BC = ZE.getOperand(0); 2514 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2515 Arg = BC.getOperand(0); 2516 ReturnF16 = true; 2517 } 2518 } 2519 } 2520 } 2521 2522 switch (VA.getLocInfo()) { 2523 default: llvm_unreachable("Unknown loc info!"); 2524 case CCValAssign::Full: break; 2525 case CCValAssign::BCvt: 2526 if (!ReturnF16) 2527 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2528 break; 2529 } 2530 2531 if (VA.needsCustom()) { 2532 if (VA.getLocVT() == MVT::v2f64) { 2533 // Extract the first half and return it in two registers. 2534 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2535 DAG.getConstant(0, dl, MVT::i32)); 2536 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2537 DAG.getVTList(MVT::i32, MVT::i32), Half); 2538 2539 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2540 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2541 Flag); 2542 Flag = Chain.getValue(1); 2543 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2544 VA = RVLocs[++i]; // skip ahead to next loc 2545 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2546 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2547 Flag); 2548 Flag = Chain.getValue(1); 2549 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2550 VA = RVLocs[++i]; // skip ahead to next loc 2551 2552 // Extract the 2nd half and fall through to handle it as an f64 value. 2553 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2554 DAG.getConstant(1, dl, MVT::i32)); 2555 } 2556 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2557 // available. 2558 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2559 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2560 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2561 fmrrd.getValue(isLittleEndian ? 0 : 1), 2562 Flag); 2563 Flag = Chain.getValue(1); 2564 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2565 VA = RVLocs[++i]; // skip ahead to next loc 2566 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2567 fmrrd.getValue(isLittleEndian ? 1 : 0), 2568 Flag); 2569 } else 2570 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2571 2572 // Guarantee that all emitted copies are 2573 // stuck together, avoiding something bad. 2574 Flag = Chain.getValue(1); 2575 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2576 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2577 } 2578 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2579 const MCPhysReg *I = 2580 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2581 if (I) { 2582 for (; *I; ++I) { 2583 if (ARM::GPRRegClass.contains(*I)) 2584 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2585 else if (ARM::DPRRegClass.contains(*I)) 2586 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2587 else 2588 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2589 } 2590 } 2591 2592 // Update chain and glue. 2593 RetOps[0] = Chain; 2594 if (Flag.getNode()) 2595 RetOps.push_back(Flag); 2596 2597 // CPUs which aren't M-class use a special sequence to return from 2598 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2599 // though we use "subs pc, lr, #N"). 2600 // 2601 // M-class CPUs actually use a normal return sequence with a special 2602 // (hardware-provided) value in LR, so the normal code path works. 2603 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2604 !Subtarget->isMClass()) { 2605 if (Subtarget->isThumb1Only()) 2606 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2607 return LowerInterruptReturn(RetOps, dl, DAG); 2608 } 2609 2610 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2611 } 2612 2613 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2614 if (N->getNumValues() != 1) 2615 return false; 2616 if (!N->hasNUsesOfValue(1, 0)) 2617 return false; 2618 2619 SDValue TCChain = Chain; 2620 SDNode *Copy = *N->use_begin(); 2621 if (Copy->getOpcode() == ISD::CopyToReg) { 2622 // If the copy has a glue operand, we conservatively assume it isn't safe to 2623 // perform a tail call. 2624 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2625 return false; 2626 TCChain = Copy->getOperand(0); 2627 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2628 SDNode *VMov = Copy; 2629 // f64 returned in a pair of GPRs. 2630 SmallPtrSet<SDNode*, 2> Copies; 2631 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2632 UI != UE; ++UI) { 2633 if (UI->getOpcode() != ISD::CopyToReg) 2634 return false; 2635 Copies.insert(*UI); 2636 } 2637 if (Copies.size() > 2) 2638 return false; 2639 2640 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2641 UI != UE; ++UI) { 2642 SDValue UseChain = UI->getOperand(0); 2643 if (Copies.count(UseChain.getNode())) 2644 // Second CopyToReg 2645 Copy = *UI; 2646 else { 2647 // We are at the top of this chain. 2648 // If the copy has a glue operand, we conservatively assume it 2649 // isn't safe to perform a tail call. 2650 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2651 return false; 2652 // First CopyToReg 2653 TCChain = UseChain; 2654 } 2655 } 2656 } else if (Copy->getOpcode() == ISD::BITCAST) { 2657 // f32 returned in a single GPR. 2658 if (!Copy->hasOneUse()) 2659 return false; 2660 Copy = *Copy->use_begin(); 2661 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2662 return false; 2663 // If the copy has a glue operand, we conservatively assume it isn't safe to 2664 // perform a tail call. 2665 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2666 return false; 2667 TCChain = Copy->getOperand(0); 2668 } else { 2669 return false; 2670 } 2671 2672 bool HasRet = false; 2673 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2674 UI != UE; ++UI) { 2675 if (UI->getOpcode() != ARMISD::RET_FLAG && 2676 UI->getOpcode() != ARMISD::INTRET_FLAG) 2677 return false; 2678 HasRet = true; 2679 } 2680 2681 if (!HasRet) 2682 return false; 2683 2684 Chain = TCChain; 2685 return true; 2686 } 2687 2688 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2689 if (!Subtarget->supportsTailCall()) 2690 return false; 2691 2692 auto Attr = 2693 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2694 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2695 return false; 2696 2697 return true; 2698 } 2699 2700 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2701 // and pass the lower and high parts through. 2702 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2703 SDLoc DL(Op); 2704 SDValue WriteValue = Op->getOperand(2); 2705 2706 // This function is only supposed to be called for i64 type argument. 2707 assert(WriteValue.getValueType() == MVT::i64 2708 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2709 2710 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2711 DAG.getConstant(0, DL, MVT::i32)); 2712 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2713 DAG.getConstant(1, DL, MVT::i32)); 2714 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2715 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2716 } 2717 2718 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2719 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2720 // one of the above mentioned nodes. It has to be wrapped because otherwise 2721 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2722 // be used to form addressing mode. These wrapped nodes will be selected 2723 // into MOVi. 2724 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2725 SelectionDAG &DAG) const { 2726 EVT PtrVT = Op.getValueType(); 2727 // FIXME there is no actual debug info here 2728 SDLoc dl(Op); 2729 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2730 SDValue Res; 2731 2732 // When generating execute-only code Constant Pools must be promoted to the 2733 // global data section. It's a bit ugly that we can't share them across basic 2734 // blocks, but this way we guarantee that execute-only behaves correct with 2735 // position-independent addressing modes. 2736 if (Subtarget->genExecuteOnly()) { 2737 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2738 auto T = const_cast<Type*>(CP->getType()); 2739 auto C = const_cast<Constant*>(CP->getConstVal()); 2740 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2741 getFunction().getParent()); 2742 auto GV = new GlobalVariable( 2743 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2744 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2745 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2746 Twine(AFI->createPICLabelUId()) 2747 ); 2748 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2749 dl, PtrVT); 2750 return LowerGlobalAddress(GA, DAG); 2751 } 2752 2753 if (CP->isMachineConstantPoolEntry()) 2754 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2755 CP->getAlignment()); 2756 else 2757 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2758 CP->getAlignment()); 2759 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2760 } 2761 2762 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2763 return MachineJumpTableInfo::EK_Inline; 2764 } 2765 2766 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2767 SelectionDAG &DAG) const { 2768 MachineFunction &MF = DAG.getMachineFunction(); 2769 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2770 unsigned ARMPCLabelIndex = 0; 2771 SDLoc DL(Op); 2772 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2773 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2774 SDValue CPAddr; 2775 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2776 if (!IsPositionIndependent) { 2777 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2778 } else { 2779 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2780 ARMPCLabelIndex = AFI->createPICLabelUId(); 2781 ARMConstantPoolValue *CPV = 2782 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2783 ARMCP::CPBlockAddress, PCAdj); 2784 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2785 } 2786 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2787 SDValue Result = DAG.getLoad( 2788 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2789 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2790 if (!IsPositionIndependent) 2791 return Result; 2792 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2793 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2794 } 2795 2796 /// Convert a TLS address reference into the correct sequence of loads 2797 /// and calls to compute the variable's address for Darwin, and return an 2798 /// SDValue containing the final node. 2799 2800 /// Darwin only has one TLS scheme which must be capable of dealing with the 2801 /// fully general situation, in the worst case. This means: 2802 /// + "extern __thread" declaration. 2803 /// + Defined in a possibly unknown dynamic library. 2804 /// 2805 /// The general system is that each __thread variable has a [3 x i32] descriptor 2806 /// which contains information used by the runtime to calculate the address. The 2807 /// only part of this the compiler needs to know about is the first word, which 2808 /// contains a function pointer that must be called with the address of the 2809 /// entire descriptor in "r0". 2810 /// 2811 /// Since this descriptor may be in a different unit, in general access must 2812 /// proceed along the usual ARM rules. A common sequence to produce is: 2813 /// 2814 /// movw rT1, :lower16:_var$non_lazy_ptr 2815 /// movt rT1, :upper16:_var$non_lazy_ptr 2816 /// ldr r0, [rT1] 2817 /// ldr rT2, [r0] 2818 /// blx rT2 2819 /// [...address now in r0...] 2820 SDValue 2821 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2822 SelectionDAG &DAG) const { 2823 assert(Subtarget->isTargetDarwin() && 2824 "This function expects a Darwin target"); 2825 SDLoc DL(Op); 2826 2827 // First step is to get the address of the actua global symbol. This is where 2828 // the TLS descriptor lives. 2829 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2830 2831 // The first entry in the descriptor is a function pointer that we must call 2832 // to obtain the address of the variable. 2833 SDValue Chain = DAG.getEntryNode(); 2834 SDValue FuncTLVGet = DAG.getLoad( 2835 MVT::i32, DL, Chain, DescAddr, 2836 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2837 /* Alignment = */ 4, 2838 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2839 MachineMemOperand::MOInvariant); 2840 Chain = FuncTLVGet.getValue(1); 2841 2842 MachineFunction &F = DAG.getMachineFunction(); 2843 MachineFrameInfo &MFI = F.getFrameInfo(); 2844 MFI.setAdjustsStack(true); 2845 2846 // TLS calls preserve all registers except those that absolutely must be 2847 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2848 // silly). 2849 auto TRI = 2850 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 2851 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2852 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2853 2854 // Finally, we can make the call. This is just a degenerate version of a 2855 // normal AArch64 call node: r0 takes the address of the descriptor, and 2856 // returns the address of the variable in this thread. 2857 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2858 Chain = 2859 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2860 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2861 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2862 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2863 } 2864 2865 SDValue 2866 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2867 SelectionDAG &DAG) const { 2868 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2869 2870 SDValue Chain = DAG.getEntryNode(); 2871 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2872 SDLoc DL(Op); 2873 2874 // Load the current TEB (thread environment block) 2875 SDValue Ops[] = {Chain, 2876 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2877 DAG.getConstant(15, DL, MVT::i32), 2878 DAG.getConstant(0, DL, MVT::i32), 2879 DAG.getConstant(13, DL, MVT::i32), 2880 DAG.getConstant(0, DL, MVT::i32), 2881 DAG.getConstant(2, DL, MVT::i32)}; 2882 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2883 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2884 2885 SDValue TEB = CurrentTEB.getValue(0); 2886 Chain = CurrentTEB.getValue(1); 2887 2888 // Load the ThreadLocalStoragePointer from the TEB 2889 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2890 SDValue TLSArray = 2891 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2892 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2893 2894 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2895 // offset into the TLSArray. 2896 2897 // Load the TLS index from the C runtime 2898 SDValue TLSIndex = 2899 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2900 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2901 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2902 2903 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2904 DAG.getConstant(2, DL, MVT::i32)); 2905 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2906 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2907 MachinePointerInfo()); 2908 2909 // Get the offset of the start of the .tls section (section base) 2910 const auto *GA = cast<GlobalAddressSDNode>(Op); 2911 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2912 SDValue Offset = DAG.getLoad( 2913 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2914 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2915 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2916 2917 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2918 } 2919 2920 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2921 SDValue 2922 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2923 SelectionDAG &DAG) const { 2924 SDLoc dl(GA); 2925 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2926 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2927 MachineFunction &MF = DAG.getMachineFunction(); 2928 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2929 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2930 ARMConstantPoolValue *CPV = 2931 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2932 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2933 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2934 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2935 Argument = DAG.getLoad( 2936 PtrVT, dl, DAG.getEntryNode(), Argument, 2937 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2938 SDValue Chain = Argument.getValue(1); 2939 2940 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2941 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2942 2943 // call __tls_get_addr. 2944 ArgListTy Args; 2945 ArgListEntry Entry; 2946 Entry.Node = Argument; 2947 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2948 Args.push_back(Entry); 2949 2950 // FIXME: is there useful debug info available here? 2951 TargetLowering::CallLoweringInfo CLI(DAG); 2952 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2953 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2954 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2955 2956 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2957 return CallResult.first; 2958 } 2959 2960 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2961 // "local exec" model. 2962 SDValue 2963 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2964 SelectionDAG &DAG, 2965 TLSModel::Model model) const { 2966 const GlobalValue *GV = GA->getGlobal(); 2967 SDLoc dl(GA); 2968 SDValue Offset; 2969 SDValue Chain = DAG.getEntryNode(); 2970 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2971 // Get the Thread Pointer 2972 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2973 2974 if (model == TLSModel::InitialExec) { 2975 MachineFunction &MF = DAG.getMachineFunction(); 2976 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2977 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2978 // Initial exec model. 2979 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2980 ARMConstantPoolValue *CPV = 2981 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2982 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2983 true); 2984 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2985 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2986 Offset = DAG.getLoad( 2987 PtrVT, dl, Chain, Offset, 2988 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2989 Chain = Offset.getValue(1); 2990 2991 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2992 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2993 2994 Offset = DAG.getLoad( 2995 PtrVT, dl, Chain, Offset, 2996 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2997 } else { 2998 // local exec model 2999 assert(model == TLSModel::LocalExec); 3000 ARMConstantPoolValue *CPV = 3001 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 3002 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3003 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 3004 Offset = DAG.getLoad( 3005 PtrVT, dl, Chain, Offset, 3006 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3007 } 3008 3009 // The address of the thread local variable is the add of the thread 3010 // pointer with the offset of the variable. 3011 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3012 } 3013 3014 SDValue 3015 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3016 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3017 if (DAG.getTarget().useEmulatedTLS()) 3018 return LowerToTLSEmulatedModel(GA, DAG); 3019 3020 if (Subtarget->isTargetDarwin()) 3021 return LowerGlobalTLSAddressDarwin(Op, DAG); 3022 3023 if (Subtarget->isTargetWindows()) 3024 return LowerGlobalTLSAddressWindows(Op, DAG); 3025 3026 // TODO: implement the "local dynamic" model 3027 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3028 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3029 3030 switch (model) { 3031 case TLSModel::GeneralDynamic: 3032 case TLSModel::LocalDynamic: 3033 return LowerToTLSGeneralDynamicModel(GA, DAG); 3034 case TLSModel::InitialExec: 3035 case TLSModel::LocalExec: 3036 return LowerToTLSExecModels(GA, DAG, model); 3037 } 3038 llvm_unreachable("bogus TLS model"); 3039 } 3040 3041 /// Return true if all users of V are within function F, looking through 3042 /// ConstantExprs. 3043 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3044 SmallVector<const User*,4> Worklist; 3045 for (auto *U : V->users()) 3046 Worklist.push_back(U); 3047 while (!Worklist.empty()) { 3048 auto *U = Worklist.pop_back_val(); 3049 if (isa<ConstantExpr>(U)) { 3050 for (auto *UU : U->users()) 3051 Worklist.push_back(UU); 3052 continue; 3053 } 3054 3055 auto *I = dyn_cast<Instruction>(U); 3056 if (!I || I->getParent()->getParent() != F) 3057 return false; 3058 } 3059 return true; 3060 } 3061 3062 /// Return true if all users of V are within some (any) function, looking through 3063 /// ConstantExprs. In other words, are there any global constant users? 3064 static bool allUsersAreInFunctions(const Value *V) { 3065 SmallVector<const User*,4> Worklist; 3066 for (auto *U : V->users()) 3067 Worklist.push_back(U); 3068 while (!Worklist.empty()) { 3069 auto *U = Worklist.pop_back_val(); 3070 if (isa<ConstantExpr>(U)) { 3071 for (auto *UU : U->users()) 3072 Worklist.push_back(UU); 3073 continue; 3074 } 3075 3076 if (!isa<Instruction>(U)) 3077 return false; 3078 } 3079 return true; 3080 } 3081 3082 // Return true if T is an integer, float or an array/vector of either. 3083 static bool isSimpleType(Type *T) { 3084 if (T->isIntegerTy() || T->isFloatingPointTy()) 3085 return true; 3086 Type *SubT = nullptr; 3087 if (T->isArrayTy()) 3088 SubT = T->getArrayElementType(); 3089 else if (T->isVectorTy()) 3090 SubT = T->getVectorElementType(); 3091 else 3092 return false; 3093 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 3094 } 3095 3096 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 3097 EVT PtrVT, const SDLoc &dl) { 3098 // If we're creating a pool entry for a constant global with unnamed address, 3099 // and the global is small enough, we can emit it inline into the constant pool 3100 // to save ourselves an indirection. 3101 // 3102 // This is a win if the constant is only used in one function (so it doesn't 3103 // need to be duplicated) or duplicating the constant wouldn't increase code 3104 // size (implying the constant is no larger than 4 bytes). 3105 const Function &F = DAG.getMachineFunction().getFunction(); 3106 3107 // We rely on this decision to inline being idemopotent and unrelated to the 3108 // use-site. We know that if we inline a variable at one use site, we'll 3109 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3110 // doesn't know about this optimization, so bail out if it's enabled else 3111 // we could decide to inline here (and thus never emit the GV) but require 3112 // the GV from fast-isel generated code. 3113 if (!EnableConstpoolPromotion || 3114 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3115 return SDValue(); 3116 3117 auto *GVar = dyn_cast<GlobalVariable>(GV); 3118 if (!GVar || !GVar->hasInitializer() || 3119 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3120 !GVar->hasLocalLinkage()) 3121 return SDValue(); 3122 3123 // Ensure that we don't try and inline any type that contains pointers. If 3124 // we inline a value that contains relocations, we move the relocations from 3125 // .data to .text which is not ideal. 3126 auto *Init = GVar->getInitializer(); 3127 if (!isSimpleType(Init->getType())) 3128 return SDValue(); 3129 3130 // The constant islands pass can only really deal with alignment requests 3131 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3132 // any type wanting greater alignment requirements than 4 bytes. We also 3133 // can only promote constants that are multiples of 4 bytes in size or 3134 // are paddable to a multiple of 4. Currently we only try and pad constants 3135 // that are strings for simplicity. 3136 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3137 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3138 unsigned Align = GVar->getAlignment(); 3139 unsigned RequiredPadding = 4 - (Size % 4); 3140 bool PaddingPossible = 3141 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3142 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3143 Size == 0) 3144 return SDValue(); 3145 3146 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3147 MachineFunction &MF = DAG.getMachineFunction(); 3148 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3149 3150 // We can't bloat the constant pool too much, else the ConstantIslands pass 3151 // may fail to converge. If we haven't promoted this global yet (it may have 3152 // multiple uses), and promoting it would increase the constant pool size (Sz 3153 // > 4), ensure we have space to do so up to MaxTotal. 3154 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3155 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3156 ConstpoolPromotionMaxTotal) 3157 return SDValue(); 3158 3159 // This is only valid if all users are in a single function OR it has users 3160 // in multiple functions but it no larger than a pointer. We also check if 3161 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3162 // address taken. 3163 if (!allUsersAreInFunction(GVar, &F) && 3164 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3165 return SDValue(); 3166 3167 // We're going to inline this global. Pad it out if needed. 3168 if (RequiredPadding != 4) { 3169 StringRef S = CDAInit->getAsString(); 3170 3171 SmallVector<uint8_t,16> V(S.size()); 3172 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3173 while (RequiredPadding--) 3174 V.push_back(0); 3175 Init = ConstantDataArray::get(*DAG.getContext(), V); 3176 } 3177 3178 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3179 SDValue CPAddr = 3180 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3181 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3182 AFI->markGlobalAsPromotedToConstantPool(GVar); 3183 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3184 PaddedSize - 4); 3185 } 3186 ++NumConstpoolPromoted; 3187 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3188 } 3189 3190 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3191 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3192 GV = GA->getBaseObject(); 3193 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3194 isa<Function>(GV); 3195 } 3196 3197 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3198 SelectionDAG &DAG) const { 3199 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3200 default: llvm_unreachable("unknown object format"); 3201 case Triple::COFF: 3202 return LowerGlobalAddressWindows(Op, DAG); 3203 case Triple::ELF: 3204 return LowerGlobalAddressELF(Op, DAG); 3205 case Triple::MachO: 3206 return LowerGlobalAddressDarwin(Op, DAG); 3207 } 3208 } 3209 3210 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3211 SelectionDAG &DAG) const { 3212 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3213 SDLoc dl(Op); 3214 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3215 const TargetMachine &TM = getTargetMachine(); 3216 bool IsRO = isReadOnly(GV); 3217 3218 // promoteToConstantPool only if not generating XO text section 3219 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3220 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3221 return V; 3222 3223 if (isPositionIndependent()) { 3224 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3225 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3226 UseGOT_PREL ? ARMII::MO_GOT : 0); 3227 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3228 if (UseGOT_PREL) 3229 Result = 3230 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3231 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3232 return Result; 3233 } else if (Subtarget->isROPI() && IsRO) { 3234 // PC-relative. 3235 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3236 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3237 return Result; 3238 } else if (Subtarget->isRWPI() && !IsRO) { 3239 // SB-relative. 3240 SDValue RelAddr; 3241 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3242 ++NumMovwMovt; 3243 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3244 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3245 } else { // use literal pool for address constant 3246 ARMConstantPoolValue *CPV = 3247 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3248 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3249 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3250 RelAddr = DAG.getLoad( 3251 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3252 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3253 } 3254 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3255 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3256 return Result; 3257 } 3258 3259 // If we have T2 ops, we can materialize the address directly via movt/movw 3260 // pair. This is always cheaper. 3261 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3262 ++NumMovwMovt; 3263 // FIXME: Once remat is capable of dealing with instructions with register 3264 // operands, expand this into two nodes. 3265 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3266 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3267 } else { 3268 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3269 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3270 return DAG.getLoad( 3271 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3272 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3273 } 3274 } 3275 3276 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3277 SelectionDAG &DAG) const { 3278 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3279 "ROPI/RWPI not currently supported for Darwin"); 3280 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3281 SDLoc dl(Op); 3282 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3283 3284 if (Subtarget->useMovt(DAG.getMachineFunction())) 3285 ++NumMovwMovt; 3286 3287 // FIXME: Once remat is capable of dealing with instructions with register 3288 // operands, expand this into multiple nodes 3289 unsigned Wrapper = 3290 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3291 3292 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3293 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3294 3295 if (Subtarget->isGVIndirectSymbol(GV)) 3296 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3297 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3298 return Result; 3299 } 3300 3301 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3302 SelectionDAG &DAG) const { 3303 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3304 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3305 "Windows on ARM expects to use movw/movt"); 3306 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3307 "ROPI/RWPI not currently supported for Windows"); 3308 3309 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3310 const ARMII::TOF TargetFlags = 3311 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3312 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3313 SDValue Result; 3314 SDLoc DL(Op); 3315 3316 ++NumMovwMovt; 3317 3318 // FIXME: Once remat is capable of dealing with instructions with register 3319 // operands, expand this into two nodes. 3320 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3321 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3322 TargetFlags)); 3323 if (GV->hasDLLImportStorageClass()) 3324 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3325 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3326 return Result; 3327 } 3328 3329 SDValue 3330 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3331 SDLoc dl(Op); 3332 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3333 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3334 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3335 Op.getOperand(1), Val); 3336 } 3337 3338 SDValue 3339 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3340 SDLoc dl(Op); 3341 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3342 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3343 } 3344 3345 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3346 SelectionDAG &DAG) const { 3347 SDLoc dl(Op); 3348 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3349 Op.getOperand(0)); 3350 } 3351 3352 SDValue 3353 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3354 const ARMSubtarget *Subtarget) const { 3355 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3356 SDLoc dl(Op); 3357 switch (IntNo) { 3358 default: return SDValue(); // Don't custom lower most intrinsics. 3359 case Intrinsic::thread_pointer: { 3360 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3361 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3362 } 3363 case Intrinsic::eh_sjlj_lsda: { 3364 MachineFunction &MF = DAG.getMachineFunction(); 3365 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3366 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3367 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3368 SDValue CPAddr; 3369 bool IsPositionIndependent = isPositionIndependent(); 3370 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3371 ARMConstantPoolValue *CPV = 3372 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3373 ARMCP::CPLSDA, PCAdj); 3374 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3375 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3376 SDValue Result = DAG.getLoad( 3377 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3378 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3379 3380 if (IsPositionIndependent) { 3381 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3382 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3383 } 3384 return Result; 3385 } 3386 case Intrinsic::arm_neon_vabs: 3387 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3388 Op.getOperand(1)); 3389 case Intrinsic::arm_neon_vmulls: 3390 case Intrinsic::arm_neon_vmullu: { 3391 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3392 ? ARMISD::VMULLs : ARMISD::VMULLu; 3393 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3394 Op.getOperand(1), Op.getOperand(2)); 3395 } 3396 case Intrinsic::arm_neon_vminnm: 3397 case Intrinsic::arm_neon_vmaxnm: { 3398 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3399 ? ISD::FMINNUM : ISD::FMAXNUM; 3400 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3401 Op.getOperand(1), Op.getOperand(2)); 3402 } 3403 case Intrinsic::arm_neon_vminu: 3404 case Intrinsic::arm_neon_vmaxu: { 3405 if (Op.getValueType().isFloatingPoint()) 3406 return SDValue(); 3407 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3408 ? ISD::UMIN : ISD::UMAX; 3409 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3410 Op.getOperand(1), Op.getOperand(2)); 3411 } 3412 case Intrinsic::arm_neon_vmins: 3413 case Intrinsic::arm_neon_vmaxs: { 3414 // v{min,max}s is overloaded between signed integers and floats. 3415 if (!Op.getValueType().isFloatingPoint()) { 3416 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3417 ? ISD::SMIN : ISD::SMAX; 3418 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3419 Op.getOperand(1), Op.getOperand(2)); 3420 } 3421 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3422 ? ISD::FMINNAN : ISD::FMAXNAN; 3423 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3424 Op.getOperand(1), Op.getOperand(2)); 3425 } 3426 case Intrinsic::arm_neon_vtbl1: 3427 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3428 Op.getOperand(1), Op.getOperand(2)); 3429 case Intrinsic::arm_neon_vtbl2: 3430 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3431 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3432 } 3433 } 3434 3435 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3436 const ARMSubtarget *Subtarget) { 3437 SDLoc dl(Op); 3438 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3439 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3440 if (SSID == SyncScope::SingleThread) 3441 return Op; 3442 3443 if (!Subtarget->hasDataBarrier()) { 3444 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3445 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3446 // here. 3447 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3448 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3449 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3450 DAG.getConstant(0, dl, MVT::i32)); 3451 } 3452 3453 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3454 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3455 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3456 if (Subtarget->isMClass()) { 3457 // Only a full system barrier exists in the M-class architectures. 3458 Domain = ARM_MB::SY; 3459 } else if (Subtarget->preferISHSTBarriers() && 3460 Ord == AtomicOrdering::Release) { 3461 // Swift happens to implement ISHST barriers in a way that's compatible with 3462 // Release semantics but weaker than ISH so we'd be fools not to use 3463 // it. Beware: other processors probably don't! 3464 Domain = ARM_MB::ISHST; 3465 } 3466 3467 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3468 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3469 DAG.getConstant(Domain, dl, MVT::i32)); 3470 } 3471 3472 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3473 const ARMSubtarget *Subtarget) { 3474 // ARM pre v5TE and Thumb1 does not have preload instructions. 3475 if (!(Subtarget->isThumb2() || 3476 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3477 // Just preserve the chain. 3478 return Op.getOperand(0); 3479 3480 SDLoc dl(Op); 3481 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3482 if (!isRead && 3483 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3484 // ARMv7 with MP extension has PLDW. 3485 return Op.getOperand(0); 3486 3487 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3488 if (Subtarget->isThumb()) { 3489 // Invert the bits. 3490 isRead = ~isRead & 1; 3491 isData = ~isData & 1; 3492 } 3493 3494 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3495 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3496 DAG.getConstant(isData, dl, MVT::i32)); 3497 } 3498 3499 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3500 MachineFunction &MF = DAG.getMachineFunction(); 3501 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3502 3503 // vastart just stores the address of the VarArgsFrameIndex slot into the 3504 // memory location argument. 3505 SDLoc dl(Op); 3506 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3507 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3508 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3509 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3510 MachinePointerInfo(SV)); 3511 } 3512 3513 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3514 CCValAssign &NextVA, 3515 SDValue &Root, 3516 SelectionDAG &DAG, 3517 const SDLoc &dl) const { 3518 MachineFunction &MF = DAG.getMachineFunction(); 3519 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3520 3521 const TargetRegisterClass *RC; 3522 if (AFI->isThumb1OnlyFunction()) 3523 RC = &ARM::tGPRRegClass; 3524 else 3525 RC = &ARM::GPRRegClass; 3526 3527 // Transform the arguments stored in physical registers into virtual ones. 3528 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3529 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3530 3531 SDValue ArgValue2; 3532 if (NextVA.isMemLoc()) { 3533 MachineFrameInfo &MFI = MF.getFrameInfo(); 3534 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3535 3536 // Create load node to retrieve arguments from the stack. 3537 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3538 ArgValue2 = DAG.getLoad( 3539 MVT::i32, dl, Root, FIN, 3540 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3541 } else { 3542 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3543 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3544 } 3545 if (!Subtarget->isLittle()) 3546 std::swap (ArgValue, ArgValue2); 3547 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3548 } 3549 3550 // The remaining GPRs hold either the beginning of variable-argument 3551 // data, or the beginning of an aggregate passed by value (usually 3552 // byval). Either way, we allocate stack slots adjacent to the data 3553 // provided by our caller, and store the unallocated registers there. 3554 // If this is a variadic function, the va_list pointer will begin with 3555 // these values; otherwise, this reassembles a (byval) structure that 3556 // was split between registers and memory. 3557 // Return: The frame index registers were stored into. 3558 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3559 const SDLoc &dl, SDValue &Chain, 3560 const Value *OrigArg, 3561 unsigned InRegsParamRecordIdx, 3562 int ArgOffset, unsigned ArgSize) const { 3563 // Currently, two use-cases possible: 3564 // Case #1. Non-var-args function, and we meet first byval parameter. 3565 // Setup first unallocated register as first byval register; 3566 // eat all remained registers 3567 // (these two actions are performed by HandleByVal method). 3568 // Then, here, we initialize stack frame with 3569 // "store-reg" instructions. 3570 // Case #2. Var-args function, that doesn't contain byval parameters. 3571 // The same: eat all remained unallocated registers, 3572 // initialize stack frame. 3573 3574 MachineFunction &MF = DAG.getMachineFunction(); 3575 MachineFrameInfo &MFI = MF.getFrameInfo(); 3576 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3577 unsigned RBegin, REnd; 3578 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3579 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3580 } else { 3581 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3582 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3583 REnd = ARM::R4; 3584 } 3585 3586 if (REnd != RBegin) 3587 ArgOffset = -4 * (ARM::R4 - RBegin); 3588 3589 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3590 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3591 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3592 3593 SmallVector<SDValue, 4> MemOps; 3594 const TargetRegisterClass *RC = 3595 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3596 3597 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3598 unsigned VReg = MF.addLiveIn(Reg, RC); 3599 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3600 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3601 MachinePointerInfo(OrigArg, 4 * i)); 3602 MemOps.push_back(Store); 3603 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3604 } 3605 3606 if (!MemOps.empty()) 3607 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3608 return FrameIndex; 3609 } 3610 3611 // Setup stack frame, the va_list pointer will start from. 3612 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3613 const SDLoc &dl, SDValue &Chain, 3614 unsigned ArgOffset, 3615 unsigned TotalArgRegsSaveSize, 3616 bool ForceMutable) const { 3617 MachineFunction &MF = DAG.getMachineFunction(); 3618 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3619 3620 // Try to store any remaining integer argument regs 3621 // to their spots on the stack so that they may be loaded by dereferencing 3622 // the result of va_next. 3623 // If there is no regs to be stored, just point address after last 3624 // argument passed via stack. 3625 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3626 CCInfo.getInRegsParamsCount(), 3627 CCInfo.getNextStackOffset(), 4); 3628 AFI->setVarArgsFrameIndex(FrameIndex); 3629 } 3630 3631 SDValue ARMTargetLowering::LowerFormalArguments( 3632 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3633 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3634 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3635 MachineFunction &MF = DAG.getMachineFunction(); 3636 MachineFrameInfo &MFI = MF.getFrameInfo(); 3637 3638 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3639 3640 // Assign locations to all of the incoming arguments. 3641 SmallVector<CCValAssign, 16> ArgLocs; 3642 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3643 *DAG.getContext()); 3644 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3645 3646 SmallVector<SDValue, 16> ArgValues; 3647 SDValue ArgValue; 3648 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3649 unsigned CurArgIdx = 0; 3650 3651 // Initially ArgRegsSaveSize is zero. 3652 // Then we increase this value each time we meet byval parameter. 3653 // We also increase this value in case of varargs function. 3654 AFI->setArgRegsSaveSize(0); 3655 3656 // Calculate the amount of stack space that we need to allocate to store 3657 // byval and variadic arguments that are passed in registers. 3658 // We need to know this before we allocate the first byval or variadic 3659 // argument, as they will be allocated a stack slot below the CFA (Canonical 3660 // Frame Address, the stack pointer at entry to the function). 3661 unsigned ArgRegBegin = ARM::R4; 3662 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3663 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3664 break; 3665 3666 CCValAssign &VA = ArgLocs[i]; 3667 unsigned Index = VA.getValNo(); 3668 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3669 if (!Flags.isByVal()) 3670 continue; 3671 3672 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3673 unsigned RBegin, REnd; 3674 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3675 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3676 3677 CCInfo.nextInRegsParam(); 3678 } 3679 CCInfo.rewindByValRegsInfo(); 3680 3681 int lastInsIndex = -1; 3682 if (isVarArg && MFI.hasVAStart()) { 3683 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3684 if (RegIdx != array_lengthof(GPRArgRegs)) 3685 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3686 } 3687 3688 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3689 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3690 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3691 3692 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3693 CCValAssign &VA = ArgLocs[i]; 3694 if (Ins[VA.getValNo()].isOrigArg()) { 3695 std::advance(CurOrigArg, 3696 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3697 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3698 } 3699 // Arguments stored in registers. 3700 if (VA.isRegLoc()) { 3701 EVT RegVT = VA.getLocVT(); 3702 3703 if (VA.needsCustom()) { 3704 // f64 and vector types are split up into multiple registers or 3705 // combinations of registers and stack slots. 3706 if (VA.getLocVT() == MVT::v2f64) { 3707 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3708 Chain, DAG, dl); 3709 VA = ArgLocs[++i]; // skip ahead to next loc 3710 SDValue ArgValue2; 3711 if (VA.isMemLoc()) { 3712 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3713 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3714 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3715 MachinePointerInfo::getFixedStack( 3716 DAG.getMachineFunction(), FI)); 3717 } else { 3718 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3719 Chain, DAG, dl); 3720 } 3721 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3722 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3723 ArgValue, ArgValue1, 3724 DAG.getIntPtrConstant(0, dl)); 3725 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3726 ArgValue, ArgValue2, 3727 DAG.getIntPtrConstant(1, dl)); 3728 } else 3729 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3730 } else { 3731 const TargetRegisterClass *RC; 3732 3733 3734 if (RegVT == MVT::f16) 3735 RC = &ARM::HPRRegClass; 3736 else if (RegVT == MVT::f32) 3737 RC = &ARM::SPRRegClass; 3738 else if (RegVT == MVT::f64 || RegVT == MVT::v4f16) 3739 RC = &ARM::DPRRegClass; 3740 else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16) 3741 RC = &ARM::QPRRegClass; 3742 else if (RegVT == MVT::i32) 3743 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3744 : &ARM::GPRRegClass; 3745 else 3746 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3747 3748 // Transform the arguments in physical registers into virtual ones. 3749 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3750 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3751 } 3752 3753 // If this is an 8 or 16-bit value, it is really passed promoted 3754 // to 32 bits. Insert an assert[sz]ext to capture this, then 3755 // truncate to the right size. 3756 switch (VA.getLocInfo()) { 3757 default: llvm_unreachable("Unknown loc info!"); 3758 case CCValAssign::Full: break; 3759 case CCValAssign::BCvt: 3760 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3761 break; 3762 case CCValAssign::SExt: 3763 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3764 DAG.getValueType(VA.getValVT())); 3765 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3766 break; 3767 case CCValAssign::ZExt: 3768 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3769 DAG.getValueType(VA.getValVT())); 3770 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3771 break; 3772 } 3773 3774 InVals.push_back(ArgValue); 3775 } else { // VA.isRegLoc() 3776 // sanity check 3777 assert(VA.isMemLoc()); 3778 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3779 3780 int index = VA.getValNo(); 3781 3782 // Some Ins[] entries become multiple ArgLoc[] entries. 3783 // Process them only once. 3784 if (index != lastInsIndex) 3785 { 3786 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3787 // FIXME: For now, all byval parameter objects are marked mutable. 3788 // This can be changed with more analysis. 3789 // In case of tail call optimization mark all arguments mutable. 3790 // Since they could be overwritten by lowering of arguments in case of 3791 // a tail call. 3792 if (Flags.isByVal()) { 3793 assert(Ins[index].isOrigArg() && 3794 "Byval arguments cannot be implicit"); 3795 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3796 3797 int FrameIndex = StoreByValRegs( 3798 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3799 VA.getLocMemOffset(), Flags.getByValSize()); 3800 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3801 CCInfo.nextInRegsParam(); 3802 } else { 3803 unsigned FIOffset = VA.getLocMemOffset(); 3804 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3805 FIOffset, true); 3806 3807 // Create load nodes to retrieve arguments from the stack. 3808 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3809 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3810 MachinePointerInfo::getFixedStack( 3811 DAG.getMachineFunction(), FI))); 3812 } 3813 lastInsIndex = index; 3814 } 3815 } 3816 } 3817 3818 // varargs 3819 if (isVarArg && MFI.hasVAStart()) 3820 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3821 CCInfo.getNextStackOffset(), 3822 TotalArgRegsSaveSize); 3823 3824 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3825 3826 return Chain; 3827 } 3828 3829 /// isFloatingPointZero - Return true if this is +0.0. 3830 static bool isFloatingPointZero(SDValue Op) { 3831 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3832 return CFP->getValueAPF().isPosZero(); 3833 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3834 // Maybe this has already been legalized into the constant pool? 3835 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3836 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3837 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3838 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3839 return CFP->getValueAPF().isPosZero(); 3840 } 3841 } else if (Op->getOpcode() == ISD::BITCAST && 3842 Op->getValueType(0) == MVT::f64) { 3843 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3844 // created by LowerConstantFP(). 3845 SDValue BitcastOp = Op->getOperand(0); 3846 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3847 isNullConstant(BitcastOp->getOperand(0))) 3848 return true; 3849 } 3850 return false; 3851 } 3852 3853 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3854 /// the given operands. 3855 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3856 SDValue &ARMcc, SelectionDAG &DAG, 3857 const SDLoc &dl) const { 3858 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3859 unsigned C = RHSC->getZExtValue(); 3860 if (!isLegalICmpImmediate(C)) { 3861 // Constant does not fit, try adjusting it by one? 3862 switch (CC) { 3863 default: break; 3864 case ISD::SETLT: 3865 case ISD::SETGE: 3866 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3867 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3868 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3869 } 3870 break; 3871 case ISD::SETULT: 3872 case ISD::SETUGE: 3873 if (C != 0 && isLegalICmpImmediate(C-1)) { 3874 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3875 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3876 } 3877 break; 3878 case ISD::SETLE: 3879 case ISD::SETGT: 3880 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3881 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3882 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3883 } 3884 break; 3885 case ISD::SETULE: 3886 case ISD::SETUGT: 3887 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3888 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3889 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3890 } 3891 break; 3892 } 3893 } 3894 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 3895 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 3896 // In ARM and Thumb-2, the compare instructions can shift their second 3897 // operand. 3898 CC = ISD::getSetCCSwappedOperands(CC); 3899 std::swap(LHS, RHS); 3900 } 3901 3902 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3903 ARMISD::NodeType CompareType; 3904 switch (CondCode) { 3905 default: 3906 CompareType = ARMISD::CMP; 3907 break; 3908 case ARMCC::EQ: 3909 case ARMCC::NE: 3910 // Uses only Z Flag 3911 CompareType = ARMISD::CMPZ; 3912 break; 3913 } 3914 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3915 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3916 } 3917 3918 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3919 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3920 SelectionDAG &DAG, const SDLoc &dl, 3921 bool InvalidOnQNaN) const { 3922 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3923 SDValue Cmp; 3924 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3925 if (!isFloatingPointZero(RHS)) 3926 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3927 else 3928 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3929 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3930 } 3931 3932 /// duplicateCmp - Glue values can have only one use, so this function 3933 /// duplicates a comparison node. 3934 SDValue 3935 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3936 unsigned Opc = Cmp.getOpcode(); 3937 SDLoc DL(Cmp); 3938 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3939 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3940 3941 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3942 Cmp = Cmp.getOperand(0); 3943 Opc = Cmp.getOpcode(); 3944 if (Opc == ARMISD::CMPFP) 3945 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3946 Cmp.getOperand(1), Cmp.getOperand(2)); 3947 else { 3948 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3949 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3950 Cmp.getOperand(1)); 3951 } 3952 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3953 } 3954 3955 // This function returns three things: the arithmetic computation itself 3956 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 3957 // comparison and the condition code define the case in which the arithmetic 3958 // computation *does not* overflow. 3959 std::pair<SDValue, SDValue> 3960 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3961 SDValue &ARMcc) const { 3962 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3963 3964 SDValue Value, OverflowCmp; 3965 SDValue LHS = Op.getOperand(0); 3966 SDValue RHS = Op.getOperand(1); 3967 SDLoc dl(Op); 3968 3969 // FIXME: We are currently always generating CMPs because we don't support 3970 // generating CMN through the backend. This is not as good as the natural 3971 // CMP case because it causes a register dependency and cannot be folded 3972 // later. 3973 3974 switch (Op.getOpcode()) { 3975 default: 3976 llvm_unreachable("Unknown overflow instruction!"); 3977 case ISD::SADDO: 3978 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3979 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3980 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3981 break; 3982 case ISD::UADDO: 3983 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3984 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 3985 // We do not use it in the USUBO case as Value may not be used. 3986 Value = DAG.getNode(ARMISD::ADDC, dl, 3987 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 3988 .getValue(0); 3989 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3990 break; 3991 case ISD::SSUBO: 3992 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3993 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3994 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3995 break; 3996 case ISD::USUBO: 3997 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3998 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3999 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 4000 break; 4001 case ISD::UMULO: 4002 // We generate a UMUL_LOHI and then check if the high word is 0. 4003 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4004 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 4005 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4006 LHS, RHS); 4007 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4008 DAG.getConstant(0, dl, MVT::i32)); 4009 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4010 break; 4011 case ISD::SMULO: 4012 // We generate a SMUL_LOHI and then check if all the bits of the high word 4013 // are the same as the sign bit of the low word. 4014 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4015 Value = DAG.getNode(ISD::SMUL_LOHI, dl, 4016 DAG.getVTList(Op.getValueType(), Op.getValueType()), 4017 LHS, RHS); 4018 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 4019 DAG.getNode(ISD::SRA, dl, Op.getValueType(), 4020 Value.getValue(0), 4021 DAG.getConstant(31, dl, MVT::i32))); 4022 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4023 break; 4024 } // switch (...) 4025 4026 return std::make_pair(Value, OverflowCmp); 4027 } 4028 4029 SDValue 4030 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4031 // Let legalize expand this if it isn't a legal type yet. 4032 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4033 return SDValue(); 4034 4035 SDValue Value, OverflowCmp; 4036 SDValue ARMcc; 4037 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4038 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4039 SDLoc dl(Op); 4040 // We use 0 and 1 as false and true values. 4041 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4042 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4043 EVT VT = Op.getValueType(); 4044 4045 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4046 ARMcc, CCR, OverflowCmp); 4047 4048 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4049 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4050 } 4051 4052 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4053 SelectionDAG &DAG) { 4054 SDLoc DL(BoolCarry); 4055 EVT CarryVT = BoolCarry.getValueType(); 4056 4057 // This converts the boolean value carry into the carry flag by doing 4058 // ARMISD::SUBC Carry, 1 4059 SDValue Carry = DAG.getNode(ARMISD::SUBC, DL, 4060 DAG.getVTList(CarryVT, MVT::i32), 4061 BoolCarry, DAG.getConstant(1, DL, CarryVT)); 4062 return Carry.getValue(1); 4063 } 4064 4065 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4066 SelectionDAG &DAG) { 4067 SDLoc DL(Flags); 4068 4069 // Now convert the carry flag into a boolean carry. We do this 4070 // using ARMISD:ADDE 0, 0, Carry 4071 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4072 DAG.getConstant(0, DL, MVT::i32), 4073 DAG.getConstant(0, DL, MVT::i32), Flags); 4074 } 4075 4076 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4077 SelectionDAG &DAG) const { 4078 // Let legalize expand this if it isn't a legal type yet. 4079 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4080 return SDValue(); 4081 4082 SDValue LHS = Op.getOperand(0); 4083 SDValue RHS = Op.getOperand(1); 4084 SDLoc dl(Op); 4085 4086 EVT VT = Op.getValueType(); 4087 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4088 SDValue Value; 4089 SDValue Overflow; 4090 switch (Op.getOpcode()) { 4091 default: 4092 llvm_unreachable("Unknown overflow instruction!"); 4093 case ISD::UADDO: 4094 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4095 // Convert the carry flag into a boolean value. 4096 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4097 break; 4098 case ISD::USUBO: { 4099 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4100 // Convert the carry flag into a boolean value. 4101 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4102 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4103 // value. So compute 1 - C. 4104 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4105 DAG.getConstant(1, dl, MVT::i32), Overflow); 4106 break; 4107 } 4108 } 4109 4110 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4111 } 4112 4113 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4114 SDValue Cond = Op.getOperand(0); 4115 SDValue SelectTrue = Op.getOperand(1); 4116 SDValue SelectFalse = Op.getOperand(2); 4117 SDLoc dl(Op); 4118 unsigned Opc = Cond.getOpcode(); 4119 4120 if (Cond.getResNo() == 1 && 4121 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4122 Opc == ISD::USUBO)) { 4123 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4124 return SDValue(); 4125 4126 SDValue Value, OverflowCmp; 4127 SDValue ARMcc; 4128 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4129 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4130 EVT VT = Op.getValueType(); 4131 4132 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4133 OverflowCmp, DAG); 4134 } 4135 4136 // Convert: 4137 // 4138 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4139 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4140 // 4141 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4142 const ConstantSDNode *CMOVTrue = 4143 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4144 const ConstantSDNode *CMOVFalse = 4145 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4146 4147 if (CMOVTrue && CMOVFalse) { 4148 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4149 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4150 4151 SDValue True; 4152 SDValue False; 4153 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4154 True = SelectTrue; 4155 False = SelectFalse; 4156 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4157 True = SelectFalse; 4158 False = SelectTrue; 4159 } 4160 4161 if (True.getNode() && False.getNode()) { 4162 EVT VT = Op.getValueType(); 4163 SDValue ARMcc = Cond.getOperand(2); 4164 SDValue CCR = Cond.getOperand(3); 4165 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4166 assert(True.getValueType() == VT); 4167 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4168 } 4169 } 4170 } 4171 4172 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4173 // undefined bits before doing a full-word comparison with zero. 4174 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4175 DAG.getConstant(1, dl, Cond.getValueType())); 4176 4177 return DAG.getSelectCC(dl, Cond, 4178 DAG.getConstant(0, dl, Cond.getValueType()), 4179 SelectTrue, SelectFalse, ISD::SETNE); 4180 } 4181 4182 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4183 bool &swpCmpOps, bool &swpVselOps) { 4184 // Start by selecting the GE condition code for opcodes that return true for 4185 // 'equality' 4186 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4187 CC == ISD::SETULE) 4188 CondCode = ARMCC::GE; 4189 4190 // and GT for opcodes that return false for 'equality'. 4191 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4192 CC == ISD::SETULT) 4193 CondCode = ARMCC::GT; 4194 4195 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4196 // to swap the compare operands. 4197 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4198 CC == ISD::SETULT) 4199 swpCmpOps = true; 4200 4201 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4202 // If we have an unordered opcode, we need to swap the operands to the VSEL 4203 // instruction (effectively negating the condition). 4204 // 4205 // This also has the effect of swapping which one of 'less' or 'greater' 4206 // returns true, so we also swap the compare operands. It also switches 4207 // whether we return true for 'equality', so we compensate by picking the 4208 // opposite condition code to our original choice. 4209 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4210 CC == ISD::SETUGT) { 4211 swpCmpOps = !swpCmpOps; 4212 swpVselOps = !swpVselOps; 4213 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4214 } 4215 4216 // 'ordered' is 'anything but unordered', so use the VS condition code and 4217 // swap the VSEL operands. 4218 if (CC == ISD::SETO) { 4219 CondCode = ARMCC::VS; 4220 swpVselOps = true; 4221 } 4222 4223 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4224 // code and swap the VSEL operands. 4225 if (CC == ISD::SETUNE) { 4226 CondCode = ARMCC::EQ; 4227 swpVselOps = true; 4228 } 4229 } 4230 4231 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4232 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4233 SDValue Cmp, SelectionDAG &DAG) const { 4234 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4235 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4236 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4237 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4238 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4239 4240 SDValue TrueLow = TrueVal.getValue(0); 4241 SDValue TrueHigh = TrueVal.getValue(1); 4242 SDValue FalseLow = FalseVal.getValue(0); 4243 SDValue FalseHigh = FalseVal.getValue(1); 4244 4245 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4246 ARMcc, CCR, Cmp); 4247 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4248 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4249 4250 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4251 } else { 4252 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4253 Cmp); 4254 } 4255 } 4256 4257 static bool isGTorGE(ISD::CondCode CC) { 4258 return CC == ISD::SETGT || CC == ISD::SETGE; 4259 } 4260 4261 static bool isLTorLE(ISD::CondCode CC) { 4262 return CC == ISD::SETLT || CC == ISD::SETLE; 4263 } 4264 4265 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4266 // All of these conditions (and their <= and >= counterparts) will do: 4267 // x < k ? k : x 4268 // x > k ? x : k 4269 // k < x ? x : k 4270 // k > x ? k : x 4271 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4272 const SDValue TrueVal, const SDValue FalseVal, 4273 const ISD::CondCode CC, const SDValue K) { 4274 return (isGTorGE(CC) && 4275 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4276 (isLTorLE(CC) && 4277 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4278 } 4279 4280 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4281 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4282 const SDValue TrueVal, const SDValue FalseVal, 4283 const ISD::CondCode CC, const SDValue K) { 4284 return (isGTorGE(CC) && 4285 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4286 (isLTorLE(CC) && 4287 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4288 } 4289 4290 // Check if two chained conditionals could be converted into SSAT or USAT. 4291 // 4292 // SSAT can replace a set of two conditional selectors that bound a number to an 4293 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4294 // 4295 // x < -k ? -k : (x > k ? k : x) 4296 // x < -k ? -k : (x < k ? x : k) 4297 // x > -k ? (x > k ? k : x) : -k 4298 // x < k ? (x < -k ? -k : x) : k 4299 // etc. 4300 // 4301 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4302 // a power of 2. 4303 // 4304 // It returns true if the conversion can be done, false otherwise. 4305 // Additionally, the variable is returned in parameter V, the constant in K and 4306 // usat is set to true if the conditional represents an unsigned saturation 4307 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4308 uint64_t &K, bool &usat) { 4309 SDValue LHS1 = Op.getOperand(0); 4310 SDValue RHS1 = Op.getOperand(1); 4311 SDValue TrueVal1 = Op.getOperand(2); 4312 SDValue FalseVal1 = Op.getOperand(3); 4313 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4314 4315 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4316 if (Op2.getOpcode() != ISD::SELECT_CC) 4317 return false; 4318 4319 SDValue LHS2 = Op2.getOperand(0); 4320 SDValue RHS2 = Op2.getOperand(1); 4321 SDValue TrueVal2 = Op2.getOperand(2); 4322 SDValue FalseVal2 = Op2.getOperand(3); 4323 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4324 4325 // Find out which are the constants and which are the variables 4326 // in each conditional 4327 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4328 ? &RHS1 4329 : nullptr; 4330 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4331 ? &RHS2 4332 : nullptr; 4333 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4334 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4335 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4336 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4337 4338 // We must detect cases where the original operations worked with 16- or 4339 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4340 // must work with sign-extended values but the select operations return 4341 // the original non-extended value. 4342 SDValue V2TmpReg = V2Tmp; 4343 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4344 V2TmpReg = V2Tmp->getOperand(0); 4345 4346 // Check that the registers and the constants have the correct values 4347 // in both conditionals 4348 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4349 V2TmpReg != V2) 4350 return false; 4351 4352 // Figure out which conditional is saturating the lower/upper bound. 4353 const SDValue *LowerCheckOp = 4354 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4355 ? &Op 4356 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4357 ? &Op2 4358 : nullptr; 4359 const SDValue *UpperCheckOp = 4360 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4361 ? &Op 4362 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4363 ? &Op2 4364 : nullptr; 4365 4366 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4367 return false; 4368 4369 // Check that the constant in the lower-bound check is 4370 // the opposite of the constant in the upper-bound check 4371 // in 1's complement. 4372 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4373 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4374 int64_t PosVal = std::max(Val1, Val2); 4375 int64_t NegVal = std::min(Val1, Val2); 4376 4377 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4378 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4379 isPowerOf2_64(PosVal + 1)) { 4380 4381 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4382 if (Val1 == ~Val2) 4383 usat = false; 4384 else if (NegVal == 0) 4385 usat = true; 4386 else 4387 return false; 4388 4389 V = V2; 4390 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4391 4392 return true; 4393 } 4394 4395 return false; 4396 } 4397 4398 // Check if a condition of the type x < k ? k : x can be converted into a 4399 // bit operation instead of conditional moves. 4400 // Currently this is allowed given: 4401 // - The conditions and values match up 4402 // - k is 0 or -1 (all ones) 4403 // This function will not check the last condition, thats up to the caller 4404 // It returns true if the transformation can be made, and in such case 4405 // returns x in V, and k in SatK. 4406 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V, 4407 SDValue &SatK) 4408 { 4409 SDValue LHS = Op.getOperand(0); 4410 SDValue RHS = Op.getOperand(1); 4411 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4412 SDValue TrueVal = Op.getOperand(2); 4413 SDValue FalseVal = Op.getOperand(3); 4414 4415 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4416 ? &RHS 4417 : nullptr; 4418 4419 // No constant operation in comparison, early out 4420 if (!K) 4421 return false; 4422 4423 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4424 V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4425 SDValue VTmp = (K && *K == LHS) ? RHS : LHS; 4426 4427 // If the constant on left and right side, or variable on left and right, 4428 // does not match, early out 4429 if (*K != KTmp || V != VTmp) 4430 return false; 4431 4432 if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) { 4433 SatK = *K; 4434 return true; 4435 } 4436 4437 return false; 4438 } 4439 4440 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4441 EVT VT = Op.getValueType(); 4442 SDLoc dl(Op); 4443 4444 // Try to convert two saturating conditional selects into a single SSAT 4445 SDValue SatValue; 4446 uint64_t SatConstant; 4447 bool SatUSat; 4448 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4449 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4450 if (SatUSat) 4451 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4452 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4453 else 4454 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4455 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4456 } 4457 4458 // Try to convert expressions of the form x < k ? k : x (and similar forms) 4459 // into more efficient bit operations, which is possible when k is 0 or -1 4460 // On ARM and Thumb-2 which have flexible operand 2 this will result in 4461 // single instructions. On Thumb the shift and the bit operation will be two 4462 // instructions. 4463 // Only allow this transformation on full-width (32-bit) operations 4464 SDValue LowerSatConstant; 4465 if (VT == MVT::i32 && 4466 isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) { 4467 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue, 4468 DAG.getConstant(31, dl, VT)); 4469 if (isNullConstant(LowerSatConstant)) { 4470 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, 4471 DAG.getAllOnesConstant(dl, VT)); 4472 return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV); 4473 } else if (isAllOnesConstant(LowerSatConstant)) 4474 return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV); 4475 } 4476 4477 SDValue LHS = Op.getOperand(0); 4478 SDValue RHS = Op.getOperand(1); 4479 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4480 SDValue TrueVal = Op.getOperand(2); 4481 SDValue FalseVal = Op.getOperand(3); 4482 4483 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4484 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4485 dl); 4486 4487 // If softenSetCCOperands only returned one value, we should compare it to 4488 // zero. 4489 if (!RHS.getNode()) { 4490 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4491 CC = ISD::SETNE; 4492 } 4493 } 4494 4495 if (LHS.getValueType() == MVT::i32) { 4496 // Try to generate VSEL on ARMv8. 4497 // The VSEL instruction can't use all the usual ARM condition 4498 // codes: it only has two bits to select the condition code, so it's 4499 // constrained to use only GE, GT, VS and EQ. 4500 // 4501 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4502 // swap the operands of the previous compare instruction (effectively 4503 // inverting the compare condition, swapping 'less' and 'greater') and 4504 // sometimes need to swap the operands to the VSEL (which inverts the 4505 // condition in the sense of firing whenever the previous condition didn't) 4506 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4507 TrueVal.getValueType() == MVT::f64)) { 4508 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4509 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4510 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4511 CC = ISD::getSetCCInverse(CC, true); 4512 std::swap(TrueVal, FalseVal); 4513 } 4514 } 4515 4516 SDValue ARMcc; 4517 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4518 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4519 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4520 } 4521 4522 ARMCC::CondCodes CondCode, CondCode2; 4523 bool InvalidOnQNaN; 4524 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4525 4526 // Normalize the fp compare. If RHS is zero we keep it there so we match 4527 // CMPFPw0 instead of CMPFP. 4528 if (Subtarget->hasFPARMv8() && !isFloatingPointZero(RHS) && 4529 (TrueVal.getValueType() == MVT::f16 || 4530 TrueVal.getValueType() == MVT::f32 || 4531 TrueVal.getValueType() == MVT::f64)) { 4532 bool swpCmpOps = false; 4533 bool swpVselOps = false; 4534 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4535 4536 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4537 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4538 if (swpCmpOps) 4539 std::swap(LHS, RHS); 4540 if (swpVselOps) 4541 std::swap(TrueVal, FalseVal); 4542 } 4543 } 4544 4545 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4546 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4547 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4548 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4549 if (CondCode2 != ARMCC::AL) { 4550 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4551 // FIXME: Needs another CMP because flag can have but one use. 4552 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4553 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4554 } 4555 return Result; 4556 } 4557 4558 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4559 /// to morph to an integer compare sequence. 4560 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4561 const ARMSubtarget *Subtarget) { 4562 SDNode *N = Op.getNode(); 4563 if (!N->hasOneUse()) 4564 // Otherwise it requires moving the value from fp to integer registers. 4565 return false; 4566 if (!N->getNumValues()) 4567 return false; 4568 EVT VT = Op.getValueType(); 4569 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4570 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4571 // vmrs are very slow, e.g. cortex-a8. 4572 return false; 4573 4574 if (isFloatingPointZero(Op)) { 4575 SeenZero = true; 4576 return true; 4577 } 4578 return ISD::isNormalLoad(N); 4579 } 4580 4581 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4582 if (isFloatingPointZero(Op)) 4583 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4584 4585 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4586 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4587 Ld->getPointerInfo(), Ld->getAlignment(), 4588 Ld->getMemOperand()->getFlags()); 4589 4590 llvm_unreachable("Unknown VFP cmp argument!"); 4591 } 4592 4593 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4594 SDValue &RetVal1, SDValue &RetVal2) { 4595 SDLoc dl(Op); 4596 4597 if (isFloatingPointZero(Op)) { 4598 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4599 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4600 return; 4601 } 4602 4603 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4604 SDValue Ptr = Ld->getBasePtr(); 4605 RetVal1 = 4606 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4607 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4608 4609 EVT PtrType = Ptr.getValueType(); 4610 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4611 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4612 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4613 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4614 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4615 Ld->getMemOperand()->getFlags()); 4616 return; 4617 } 4618 4619 llvm_unreachable("Unknown VFP cmp argument!"); 4620 } 4621 4622 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4623 /// f32 and even f64 comparisons to integer ones. 4624 SDValue 4625 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4626 SDValue Chain = Op.getOperand(0); 4627 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4628 SDValue LHS = Op.getOperand(2); 4629 SDValue RHS = Op.getOperand(3); 4630 SDValue Dest = Op.getOperand(4); 4631 SDLoc dl(Op); 4632 4633 bool LHSSeenZero = false; 4634 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4635 bool RHSSeenZero = false; 4636 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4637 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4638 // If unsafe fp math optimization is enabled and there are no other uses of 4639 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4640 // to an integer comparison. 4641 if (CC == ISD::SETOEQ) 4642 CC = ISD::SETEQ; 4643 else if (CC == ISD::SETUNE) 4644 CC = ISD::SETNE; 4645 4646 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4647 SDValue ARMcc; 4648 if (LHS.getValueType() == MVT::f32) { 4649 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4650 bitcastf32Toi32(LHS, DAG), Mask); 4651 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4652 bitcastf32Toi32(RHS, DAG), Mask); 4653 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4654 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4655 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4656 Chain, Dest, ARMcc, CCR, Cmp); 4657 } 4658 4659 SDValue LHS1, LHS2; 4660 SDValue RHS1, RHS2; 4661 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4662 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4663 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4664 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4665 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4666 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4667 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4668 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4669 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4670 } 4671 4672 return SDValue(); 4673 } 4674 4675 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4676 SDValue Chain = Op.getOperand(0); 4677 SDValue Cond = Op.getOperand(1); 4678 SDValue Dest = Op.getOperand(2); 4679 SDLoc dl(Op); 4680 4681 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4682 // instruction. 4683 unsigned Opc = Cond.getOpcode(); 4684 if (Cond.getResNo() == 1 && 4685 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4686 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 4687 // Only lower legal XALUO ops. 4688 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4689 return SDValue(); 4690 4691 // The actual operation with overflow check. 4692 SDValue Value, OverflowCmp; 4693 SDValue ARMcc; 4694 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4695 4696 // Reverse the condition code. 4697 ARMCC::CondCodes CondCode = 4698 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4699 CondCode = ARMCC::getOppositeCondition(CondCode); 4700 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4701 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4702 4703 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4704 OverflowCmp); 4705 } 4706 4707 return SDValue(); 4708 } 4709 4710 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4711 SDValue Chain = Op.getOperand(0); 4712 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4713 SDValue LHS = Op.getOperand(2); 4714 SDValue RHS = Op.getOperand(3); 4715 SDValue Dest = Op.getOperand(4); 4716 SDLoc dl(Op); 4717 4718 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4719 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4720 dl); 4721 4722 // If softenSetCCOperands only returned one value, we should compare it to 4723 // zero. 4724 if (!RHS.getNode()) { 4725 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4726 CC = ISD::SETNE; 4727 } 4728 } 4729 4730 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4731 // instruction. 4732 unsigned Opc = LHS.getOpcode(); 4733 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 4734 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4735 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO) && 4736 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4737 // Only lower legal XALUO ops. 4738 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4739 return SDValue(); 4740 4741 // The actual operation with overflow check. 4742 SDValue Value, OverflowCmp; 4743 SDValue ARMcc; 4744 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 4745 4746 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 4747 // Reverse the condition code. 4748 ARMCC::CondCodes CondCode = 4749 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4750 CondCode = ARMCC::getOppositeCondition(CondCode); 4751 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4752 } 4753 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4754 4755 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4756 OverflowCmp); 4757 } 4758 4759 if (LHS.getValueType() == MVT::i32) { 4760 SDValue ARMcc; 4761 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4762 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4763 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4764 Chain, Dest, ARMcc, CCR, Cmp); 4765 } 4766 4767 if (getTargetMachine().Options.UnsafeFPMath && 4768 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4769 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4770 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4771 return Result; 4772 } 4773 4774 ARMCC::CondCodes CondCode, CondCode2; 4775 bool InvalidOnQNaN; 4776 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4777 4778 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4779 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4780 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4781 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4782 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4783 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4784 if (CondCode2 != ARMCC::AL) { 4785 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4786 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4787 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4788 } 4789 return Res; 4790 } 4791 4792 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4793 SDValue Chain = Op.getOperand(0); 4794 SDValue Table = Op.getOperand(1); 4795 SDValue Index = Op.getOperand(2); 4796 SDLoc dl(Op); 4797 4798 EVT PTy = getPointerTy(DAG.getDataLayout()); 4799 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4800 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4801 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4802 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4803 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 4804 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4805 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4806 // which does another jump to the destination. This also makes it easier 4807 // to translate it to TBB / TBH later (Thumb2 only). 4808 // FIXME: This might not work if the function is extremely large. 4809 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4810 Addr, Op.getOperand(2), JTI); 4811 } 4812 if (isPositionIndependent() || Subtarget->isROPI()) { 4813 Addr = 4814 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4815 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4816 Chain = Addr.getValue(1); 4817 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 4818 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4819 } else { 4820 Addr = 4821 DAG.getLoad(PTy, dl, Chain, Addr, 4822 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4823 Chain = Addr.getValue(1); 4824 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4825 } 4826 } 4827 4828 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4829 EVT VT = Op.getValueType(); 4830 SDLoc dl(Op); 4831 4832 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4833 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4834 return Op; 4835 return DAG.UnrollVectorOp(Op.getNode()); 4836 } 4837 4838 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4839 "Invalid type for custom lowering!"); 4840 if (VT != MVT::v4i16) 4841 return DAG.UnrollVectorOp(Op.getNode()); 4842 4843 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4844 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4845 } 4846 4847 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4848 EVT VT = Op.getValueType(); 4849 if (VT.isVector()) 4850 return LowerVectorFP_TO_INT(Op, DAG); 4851 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4852 RTLIB::Libcall LC; 4853 if (Op.getOpcode() == ISD::FP_TO_SINT) 4854 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4855 Op.getValueType()); 4856 else 4857 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4858 Op.getValueType()); 4859 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4860 /*isSigned*/ false, SDLoc(Op)).first; 4861 } 4862 4863 return Op; 4864 } 4865 4866 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4867 EVT VT = Op.getValueType(); 4868 SDLoc dl(Op); 4869 4870 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4871 if (VT.getVectorElementType() == MVT::f32) 4872 return Op; 4873 return DAG.UnrollVectorOp(Op.getNode()); 4874 } 4875 4876 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4877 "Invalid type for custom lowering!"); 4878 if (VT != MVT::v4f32) 4879 return DAG.UnrollVectorOp(Op.getNode()); 4880 4881 unsigned CastOpc; 4882 unsigned Opc; 4883 switch (Op.getOpcode()) { 4884 default: llvm_unreachable("Invalid opcode!"); 4885 case ISD::SINT_TO_FP: 4886 CastOpc = ISD::SIGN_EXTEND; 4887 Opc = ISD::SINT_TO_FP; 4888 break; 4889 case ISD::UINT_TO_FP: 4890 CastOpc = ISD::ZERO_EXTEND; 4891 Opc = ISD::UINT_TO_FP; 4892 break; 4893 } 4894 4895 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4896 return DAG.getNode(Opc, dl, VT, Op); 4897 } 4898 4899 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4900 EVT VT = Op.getValueType(); 4901 if (VT.isVector()) 4902 return LowerVectorINT_TO_FP(Op, DAG); 4903 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4904 RTLIB::Libcall LC; 4905 if (Op.getOpcode() == ISD::SINT_TO_FP) 4906 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4907 Op.getValueType()); 4908 else 4909 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4910 Op.getValueType()); 4911 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4912 /*isSigned*/ false, SDLoc(Op)).first; 4913 } 4914 4915 return Op; 4916 } 4917 4918 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4919 // Implement fcopysign with a fabs and a conditional fneg. 4920 SDValue Tmp0 = Op.getOperand(0); 4921 SDValue Tmp1 = Op.getOperand(1); 4922 SDLoc dl(Op); 4923 EVT VT = Op.getValueType(); 4924 EVT SrcVT = Tmp1.getValueType(); 4925 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4926 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4927 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4928 4929 if (UseNEON) { 4930 // Use VBSL to copy the sign bit. 4931 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4932 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4933 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4934 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4935 if (VT == MVT::f64) 4936 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4937 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4938 DAG.getConstant(32, dl, MVT::i32)); 4939 else /*if (VT == MVT::f32)*/ 4940 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4941 if (SrcVT == MVT::f32) { 4942 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4943 if (VT == MVT::f64) 4944 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4945 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4946 DAG.getConstant(32, dl, MVT::i32)); 4947 } else if (VT == MVT::f32) 4948 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4949 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4950 DAG.getConstant(32, dl, MVT::i32)); 4951 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4952 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4953 4954 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4955 dl, MVT::i32); 4956 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4957 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4958 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4959 4960 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4961 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4962 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4963 if (VT == MVT::f32) { 4964 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4965 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4966 DAG.getConstant(0, dl, MVT::i32)); 4967 } else { 4968 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4969 } 4970 4971 return Res; 4972 } 4973 4974 // Bitcast operand 1 to i32. 4975 if (SrcVT == MVT::f64) 4976 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4977 Tmp1).getValue(1); 4978 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4979 4980 // Or in the signbit with integer operations. 4981 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4982 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4983 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4984 if (VT == MVT::f32) { 4985 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4986 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4987 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4988 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4989 } 4990 4991 // f64: Or the high part with signbit and then combine two parts. 4992 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4993 Tmp0); 4994 SDValue Lo = Tmp0.getValue(0); 4995 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4996 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4997 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4998 } 4999 5000 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 5001 MachineFunction &MF = DAG.getMachineFunction(); 5002 MachineFrameInfo &MFI = MF.getFrameInfo(); 5003 MFI.setReturnAddressIsTaken(true); 5004 5005 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 5006 return SDValue(); 5007 5008 EVT VT = Op.getValueType(); 5009 SDLoc dl(Op); 5010 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5011 if (Depth) { 5012 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5013 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 5014 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 5015 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 5016 MachinePointerInfo()); 5017 } 5018 5019 // Return LR, which contains the return address. Mark it an implicit live-in. 5020 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 5021 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 5022 } 5023 5024 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 5025 const ARMBaseRegisterInfo &ARI = 5026 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 5027 MachineFunction &MF = DAG.getMachineFunction(); 5028 MachineFrameInfo &MFI = MF.getFrameInfo(); 5029 MFI.setFrameAddressIsTaken(true); 5030 5031 EVT VT = Op.getValueType(); 5032 SDLoc dl(Op); // FIXME probably not meaningful 5033 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5034 unsigned FrameReg = ARI.getFrameRegister(MF); 5035 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 5036 while (Depth--) 5037 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 5038 MachinePointerInfo()); 5039 return FrameAddr; 5040 } 5041 5042 // FIXME? Maybe this could be a TableGen attribute on some registers and 5043 // this table could be generated automatically from RegInfo. 5044 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 5045 SelectionDAG &DAG) const { 5046 unsigned Reg = StringSwitch<unsigned>(RegName) 5047 .Case("sp", ARM::SP) 5048 .Default(0); 5049 if (Reg) 5050 return Reg; 5051 report_fatal_error(Twine("Invalid register name \"" 5052 + StringRef(RegName) + "\".")); 5053 } 5054 5055 // Result is 64 bit value so split into two 32 bit values and return as a 5056 // pair of values. 5057 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5058 SelectionDAG &DAG) { 5059 SDLoc DL(N); 5060 5061 // This function is only supposed to be called for i64 type destination. 5062 assert(N->getValueType(0) == MVT::i64 5063 && "ExpandREAD_REGISTER called for non-i64 type result."); 5064 5065 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5066 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5067 N->getOperand(0), 5068 N->getOperand(1)); 5069 5070 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5071 Read.getValue(1))); 5072 Results.push_back(Read.getOperand(0)); 5073 } 5074 5075 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5076 /// When \p DstVT, the destination type of \p BC, is on the vector 5077 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5078 /// it might be possible to combine them, such that everything stays on the 5079 /// vector register bank. 5080 /// \p return The node that would replace \p BT, if the combine 5081 /// is possible. 5082 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5083 SelectionDAG &DAG) { 5084 SDValue Op = BC->getOperand(0); 5085 EVT DstVT = BC->getValueType(0); 5086 5087 // The only vector instruction that can produce a scalar (remember, 5088 // since the bitcast was about to be turned into VMOVDRR, the source 5089 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5090 // Moreover, we can do this combine only if there is one use. 5091 // Finally, if the destination type is not a vector, there is not 5092 // much point on forcing everything on the vector bank. 5093 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5094 !Op.hasOneUse()) 5095 return SDValue(); 5096 5097 // If the index is not constant, we will introduce an additional 5098 // multiply that will stick. 5099 // Give up in that case. 5100 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5101 if (!Index) 5102 return SDValue(); 5103 unsigned DstNumElt = DstVT.getVectorNumElements(); 5104 5105 // Compute the new index. 5106 const APInt &APIntIndex = Index->getAPIntValue(); 5107 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5108 NewIndex *= APIntIndex; 5109 // Check if the new constant index fits into i32. 5110 if (NewIndex.getBitWidth() > 32) 5111 return SDValue(); 5112 5113 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5114 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5115 SDLoc dl(Op); 5116 SDValue ExtractSrc = Op.getOperand(0); 5117 EVT VecVT = EVT::getVectorVT( 5118 *DAG.getContext(), DstVT.getScalarType(), 5119 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5120 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5121 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5122 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5123 } 5124 5125 /// ExpandBITCAST - If the target supports VFP, this function is called to 5126 /// expand a bit convert where either the source or destination type is i64 to 5127 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5128 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5129 /// vectors), since the legalizer won't know what to do with that. 5130 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5131 const ARMSubtarget *Subtarget) { 5132 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5133 SDLoc dl(N); 5134 SDValue Op = N->getOperand(0); 5135 5136 // This function is only supposed to be called for i64 types, either as the 5137 // source or destination of the bit convert. 5138 EVT SrcVT = Op.getValueType(); 5139 EVT DstVT = N->getValueType(0); 5140 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5141 5142 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5143 // FullFP16: half values are passed in S-registers, and we don't 5144 // need any of the bitcast and moves: 5145 // 5146 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5147 // t5: i32 = bitcast t2 5148 // t18: f16 = ARMISD::VMOVhr t5 5149 if (Op.getOpcode() != ISD::CopyFromReg || 5150 Op.getValueType() != MVT::f32) 5151 return SDValue(); 5152 5153 auto Move = N->use_begin(); 5154 if (Move->getOpcode() != ARMISD::VMOVhr) 5155 return SDValue(); 5156 5157 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5158 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5159 DAG.ReplaceAllUsesWith(*Move, &Copy); 5160 return Copy; 5161 } 5162 5163 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5164 if (!HasFullFP16) 5165 return SDValue(); 5166 // SoftFP: read half-precision arguments: 5167 // 5168 // t2: i32,ch = ... 5169 // t7: i16 = truncate t2 <~~~~ Op 5170 // t8: f16 = bitcast t7 <~~~~ N 5171 // 5172 if (Op.getOperand(0).getValueType() == MVT::i32) 5173 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5174 MVT::f16, Op.getOperand(0)); 5175 5176 return SDValue(); 5177 } 5178 5179 // Half-precision return values 5180 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5181 if (!HasFullFP16) 5182 return SDValue(); 5183 // 5184 // t11: f16 = fadd t8, t10 5185 // t12: i16 = bitcast t11 <~~~ SDNode N 5186 // t13: i32 = zero_extend t12 5187 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5188 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5189 // 5190 // transform this into: 5191 // 5192 // t20: i32 = ARMISD::VMOVrh t11 5193 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5194 // 5195 auto ZeroExtend = N->use_begin(); 5196 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5197 ZeroExtend->getValueType(0) != MVT::i32) 5198 return SDValue(); 5199 5200 auto Copy = ZeroExtend->use_begin(); 5201 if (Copy->getOpcode() == ISD::CopyToReg && 5202 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5203 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5204 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5205 return Cvt; 5206 } 5207 return SDValue(); 5208 } 5209 5210 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5211 return SDValue(); 5212 5213 // Turn i64->f64 into VMOVDRR. 5214 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5215 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5216 // if we can combine the bitcast with its source. 5217 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5218 return Val; 5219 5220 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5221 DAG.getConstant(0, dl, MVT::i32)); 5222 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5223 DAG.getConstant(1, dl, MVT::i32)); 5224 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5225 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5226 } 5227 5228 // Turn f64->i64 into VMOVRRD. 5229 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5230 SDValue Cvt; 5231 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5232 SrcVT.getVectorNumElements() > 1) 5233 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5234 DAG.getVTList(MVT::i32, MVT::i32), 5235 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5236 else 5237 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5238 DAG.getVTList(MVT::i32, MVT::i32), Op); 5239 // Merge the pieces into a single i64 value. 5240 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5241 } 5242 5243 return SDValue(); 5244 } 5245 5246 /// getZeroVector - Returns a vector of specified type with all zero elements. 5247 /// Zero vectors are used to represent vector negation and in those cases 5248 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5249 /// not support i64 elements, so sometimes the zero vectors will need to be 5250 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5251 /// zero vector. 5252 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5253 assert(VT.isVector() && "Expected a vector type"); 5254 // The canonical modified immediate encoding of a zero vector is....0! 5255 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5256 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5257 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5258 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5259 } 5260 5261 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5262 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5263 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5264 SelectionDAG &DAG) const { 5265 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5266 EVT VT = Op.getValueType(); 5267 unsigned VTBits = VT.getSizeInBits(); 5268 SDLoc dl(Op); 5269 SDValue ShOpLo = Op.getOperand(0); 5270 SDValue ShOpHi = Op.getOperand(1); 5271 SDValue ShAmt = Op.getOperand(2); 5272 SDValue ARMcc; 5273 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5274 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5275 5276 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5277 5278 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5279 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5280 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5281 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5282 DAG.getConstant(VTBits, dl, MVT::i32)); 5283 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5284 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5285 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5286 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5287 ISD::SETGE, ARMcc, DAG, dl); 5288 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5289 ARMcc, CCR, CmpLo); 5290 5291 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5292 SDValue HiBigShift = Opc == ISD::SRA 5293 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5294 DAG.getConstant(VTBits - 1, dl, VT)) 5295 : DAG.getConstant(0, dl, VT); 5296 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5297 ISD::SETGE, ARMcc, DAG, dl); 5298 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5299 ARMcc, CCR, CmpHi); 5300 5301 SDValue Ops[2] = { Lo, Hi }; 5302 return DAG.getMergeValues(Ops, dl); 5303 } 5304 5305 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5306 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5307 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5308 SelectionDAG &DAG) const { 5309 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5310 EVT VT = Op.getValueType(); 5311 unsigned VTBits = VT.getSizeInBits(); 5312 SDLoc dl(Op); 5313 SDValue ShOpLo = Op.getOperand(0); 5314 SDValue ShOpHi = Op.getOperand(1); 5315 SDValue ShAmt = Op.getOperand(2); 5316 SDValue ARMcc; 5317 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5318 5319 assert(Op.getOpcode() == ISD::SHL_PARTS); 5320 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5321 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5322 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5323 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5324 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5325 5326 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5327 DAG.getConstant(VTBits, dl, MVT::i32)); 5328 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5329 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5330 ISD::SETGE, ARMcc, DAG, dl); 5331 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5332 ARMcc, CCR, CmpHi); 5333 5334 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5335 ISD::SETGE, ARMcc, DAG, dl); 5336 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5337 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5338 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5339 5340 SDValue Ops[2] = { Lo, Hi }; 5341 return DAG.getMergeValues(Ops, dl); 5342 } 5343 5344 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5345 SelectionDAG &DAG) const { 5346 // The rounding mode is in bits 23:22 of the FPSCR. 5347 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5348 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5349 // so that the shift + and get folded into a bitfield extract. 5350 SDLoc dl(Op); 5351 SDValue Ops[] = { DAG.getEntryNode(), 5352 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5353 5354 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5355 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5356 DAG.getConstant(1U << 22, dl, MVT::i32)); 5357 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5358 DAG.getConstant(22, dl, MVT::i32)); 5359 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5360 DAG.getConstant(3, dl, MVT::i32)); 5361 } 5362 5363 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5364 const ARMSubtarget *ST) { 5365 SDLoc dl(N); 5366 EVT VT = N->getValueType(0); 5367 if (VT.isVector()) { 5368 assert(ST->hasNEON()); 5369 5370 // Compute the least significant set bit: LSB = X & -X 5371 SDValue X = N->getOperand(0); 5372 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5373 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5374 5375 EVT ElemTy = VT.getVectorElementType(); 5376 5377 if (ElemTy == MVT::i8) { 5378 // Compute with: cttz(x) = ctpop(lsb - 1) 5379 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5380 DAG.getTargetConstant(1, dl, ElemTy)); 5381 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5382 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5383 } 5384 5385 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5386 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5387 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5388 unsigned NumBits = ElemTy.getSizeInBits(); 5389 SDValue WidthMinus1 = 5390 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5391 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5392 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5393 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5394 } 5395 5396 // Compute with: cttz(x) = ctpop(lsb - 1) 5397 5398 // Since we can only compute the number of bits in a byte with vcnt.8, we 5399 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 5400 // and i64. 5401 5402 // Compute LSB - 1. 5403 SDValue Bits; 5404 if (ElemTy == MVT::i64) { 5405 // Load constant 0xffff'ffff'ffff'ffff to register. 5406 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5407 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5408 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5409 } else { 5410 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5411 DAG.getTargetConstant(1, dl, ElemTy)); 5412 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5413 } 5414 5415 // Count #bits with vcnt.8. 5416 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5417 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 5418 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 5419 5420 // Gather the #bits with vpaddl (pairwise add.) 5421 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5422 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 5423 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5424 Cnt8); 5425 if (ElemTy == MVT::i16) 5426 return Cnt16; 5427 5428 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 5429 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 5430 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5431 Cnt16); 5432 if (ElemTy == MVT::i32) 5433 return Cnt32; 5434 5435 assert(ElemTy == MVT::i64); 5436 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5437 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5438 Cnt32); 5439 return Cnt64; 5440 } 5441 5442 if (!ST->hasV6T2Ops()) 5443 return SDValue(); 5444 5445 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5446 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5447 } 5448 5449 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 5450 /// for each 16-bit element from operand, repeated. The basic idea is to 5451 /// leverage vcnt to get the 8-bit counts, gather and add the results. 5452 /// 5453 /// Trace for v4i16: 5454 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5455 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 5456 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 5457 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 5458 /// [b0 b1 b2 b3 b4 b5 b6 b7] 5459 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 5460 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 5461 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 5462 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 5463 EVT VT = N->getValueType(0); 5464 SDLoc DL(N); 5465 5466 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5467 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5468 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5469 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5470 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5471 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5472 } 5473 5474 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5475 /// bit-count for each 16-bit element from the operand. We need slightly 5476 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5477 /// 64/128-bit registers. 5478 /// 5479 /// Trace for v4i16: 5480 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5481 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5482 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5483 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5484 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5485 EVT VT = N->getValueType(0); 5486 SDLoc DL(N); 5487 5488 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5489 if (VT.is64BitVector()) { 5490 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5491 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5492 DAG.getIntPtrConstant(0, DL)); 5493 } else { 5494 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5495 BitCounts, DAG.getIntPtrConstant(0, DL)); 5496 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5497 } 5498 } 5499 5500 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5501 /// bit-count for each 32-bit element from the operand. The idea here is 5502 /// to split the vector into 16-bit elements, leverage the 16-bit count 5503 /// routine, and then combine the results. 5504 /// 5505 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5506 /// input = [v0 v1 ] (vi: 32-bit elements) 5507 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5508 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5509 /// vrev: N0 = [k1 k0 k3 k2 ] 5510 /// [k0 k1 k2 k3 ] 5511 /// N1 =+[k1 k0 k3 k2 ] 5512 /// [k0 k2 k1 k3 ] 5513 /// N2 =+[k1 k3 k0 k2 ] 5514 /// [k0 k2 k1 k3 ] 5515 /// Extended =+[k1 k3 k0 k2 ] 5516 /// [k0 k2 ] 5517 /// Extracted=+[k1 k3 ] 5518 /// 5519 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5520 EVT VT = N->getValueType(0); 5521 SDLoc DL(N); 5522 5523 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5524 5525 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5526 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5527 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5528 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5529 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5530 5531 if (VT.is64BitVector()) { 5532 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5533 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5534 DAG.getIntPtrConstant(0, DL)); 5535 } else { 5536 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5537 DAG.getIntPtrConstant(0, DL)); 5538 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5539 } 5540 } 5541 5542 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5543 const ARMSubtarget *ST) { 5544 EVT VT = N->getValueType(0); 5545 5546 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5547 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5548 VT == MVT::v4i16 || VT == MVT::v8i16) && 5549 "Unexpected type for custom ctpop lowering"); 5550 5551 if (VT.getVectorElementType() == MVT::i32) 5552 return lowerCTPOP32BitElements(N, DAG); 5553 else 5554 return lowerCTPOP16BitElements(N, DAG); 5555 } 5556 5557 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5558 const ARMSubtarget *ST) { 5559 EVT VT = N->getValueType(0); 5560 SDLoc dl(N); 5561 5562 if (!VT.isVector()) 5563 return SDValue(); 5564 5565 // Lower vector shifts on NEON to use VSHL. 5566 assert(ST->hasNEON() && "unexpected vector shift"); 5567 5568 // Left shifts translate directly to the vshiftu intrinsic. 5569 if (N->getOpcode() == ISD::SHL) 5570 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5571 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5572 MVT::i32), 5573 N->getOperand(0), N->getOperand(1)); 5574 5575 assert((N->getOpcode() == ISD::SRA || 5576 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5577 5578 // NEON uses the same intrinsics for both left and right shifts. For 5579 // right shifts, the shift amounts are negative, so negate the vector of 5580 // shift amounts. 5581 EVT ShiftVT = N->getOperand(1).getValueType(); 5582 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5583 getZeroVector(ShiftVT, DAG, dl), 5584 N->getOperand(1)); 5585 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5586 Intrinsic::arm_neon_vshifts : 5587 Intrinsic::arm_neon_vshiftu); 5588 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5589 DAG.getConstant(vshiftInt, dl, MVT::i32), 5590 N->getOperand(0), NegatedCount); 5591 } 5592 5593 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5594 const ARMSubtarget *ST) { 5595 EVT VT = N->getValueType(0); 5596 SDLoc dl(N); 5597 5598 // We can get here for a node like i32 = ISD::SHL i32, i64 5599 if (VT != MVT::i64) 5600 return SDValue(); 5601 5602 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5603 "Unknown shift to lower!"); 5604 5605 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5606 if (!isOneConstant(N->getOperand(1))) 5607 return SDValue(); 5608 5609 // If we are in thumb mode, we don't have RRX. 5610 if (ST->isThumb1Only()) return SDValue(); 5611 5612 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5613 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5614 DAG.getConstant(0, dl, MVT::i32)); 5615 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5616 DAG.getConstant(1, dl, MVT::i32)); 5617 5618 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5619 // captures the result into a carry flag. 5620 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5621 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5622 5623 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5624 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5625 5626 // Merge the pieces into a single i64 value. 5627 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5628 } 5629 5630 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5631 SDValue TmpOp0, TmpOp1; 5632 bool Invert = false; 5633 bool Swap = false; 5634 unsigned Opc = 0; 5635 5636 SDValue Op0 = Op.getOperand(0); 5637 SDValue Op1 = Op.getOperand(1); 5638 SDValue CC = Op.getOperand(2); 5639 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5640 EVT VT = Op.getValueType(); 5641 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5642 SDLoc dl(Op); 5643 5644 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5645 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5646 // Special-case integer 64-bit equality comparisons. They aren't legal, 5647 // but they can be lowered with a few vector instructions. 5648 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5649 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5650 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5651 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5652 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5653 DAG.getCondCode(ISD::SETEQ)); 5654 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5655 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5656 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5657 if (SetCCOpcode == ISD::SETNE) 5658 Merged = DAG.getNOT(dl, Merged, CmpVT); 5659 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5660 return Merged; 5661 } 5662 5663 if (CmpVT.getVectorElementType() == MVT::i64) 5664 // 64-bit comparisons are not legal in general. 5665 return SDValue(); 5666 5667 if (Op1.getValueType().isFloatingPoint()) { 5668 switch (SetCCOpcode) { 5669 default: llvm_unreachable("Illegal FP comparison"); 5670 case ISD::SETUNE: 5671 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5672 case ISD::SETOEQ: 5673 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5674 case ISD::SETOLT: 5675 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5676 case ISD::SETOGT: 5677 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5678 case ISD::SETOLE: 5679 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5680 case ISD::SETOGE: 5681 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5682 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5683 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5684 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5685 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5686 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5687 case ISD::SETONE: 5688 // Expand this to (OLT | OGT). 5689 TmpOp0 = Op0; 5690 TmpOp1 = Op1; 5691 Opc = ISD::OR; 5692 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5693 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5694 break; 5695 case ISD::SETUO: 5696 Invert = true; 5697 LLVM_FALLTHROUGH; 5698 case ISD::SETO: 5699 // Expand this to (OLT | OGE). 5700 TmpOp0 = Op0; 5701 TmpOp1 = Op1; 5702 Opc = ISD::OR; 5703 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5704 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5705 break; 5706 } 5707 } else { 5708 // Integer comparisons. 5709 switch (SetCCOpcode) { 5710 default: llvm_unreachable("Illegal integer comparison"); 5711 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5712 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5713 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5714 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5715 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5716 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5717 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5718 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5719 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5720 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5721 } 5722 5723 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5724 if (Opc == ARMISD::VCEQ) { 5725 SDValue AndOp; 5726 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5727 AndOp = Op0; 5728 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5729 AndOp = Op1; 5730 5731 // Ignore bitconvert. 5732 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5733 AndOp = AndOp.getOperand(0); 5734 5735 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5736 Opc = ARMISD::VTST; 5737 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5738 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5739 Invert = !Invert; 5740 } 5741 } 5742 } 5743 5744 if (Swap) 5745 std::swap(Op0, Op1); 5746 5747 // If one of the operands is a constant vector zero, attempt to fold the 5748 // comparison to a specialized compare-against-zero form. 5749 SDValue SingleOp; 5750 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5751 SingleOp = Op0; 5752 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5753 if (Opc == ARMISD::VCGE) 5754 Opc = ARMISD::VCLEZ; 5755 else if (Opc == ARMISD::VCGT) 5756 Opc = ARMISD::VCLTZ; 5757 SingleOp = Op1; 5758 } 5759 5760 SDValue Result; 5761 if (SingleOp.getNode()) { 5762 switch (Opc) { 5763 case ARMISD::VCEQ: 5764 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5765 case ARMISD::VCGE: 5766 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5767 case ARMISD::VCLEZ: 5768 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5769 case ARMISD::VCGT: 5770 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5771 case ARMISD::VCLTZ: 5772 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5773 default: 5774 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5775 } 5776 } else { 5777 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5778 } 5779 5780 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5781 5782 if (Invert) 5783 Result = DAG.getNOT(dl, Result, VT); 5784 5785 return Result; 5786 } 5787 5788 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) { 5789 SDValue LHS = Op.getOperand(0); 5790 SDValue RHS = Op.getOperand(1); 5791 SDValue Carry = Op.getOperand(2); 5792 SDValue Cond = Op.getOperand(3); 5793 SDLoc DL(Op); 5794 5795 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."); 5796 5797 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 5798 // have to invert the carry first. 5799 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 5800 DAG.getConstant(1, DL, MVT::i32), Carry); 5801 // This converts the boolean value carry into the carry flag. 5802 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 5803 5804 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5805 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5806 5807 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5808 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5809 SDValue ARMcc = DAG.getConstant( 5810 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5811 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5812 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5813 Cmp.getValue(1), SDValue()); 5814 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5815 CCR, Chain.getValue(1)); 5816 } 5817 5818 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5819 /// valid vector constant for a NEON instruction with a "modified immediate" 5820 /// operand (e.g., VMOV). If so, return the encoded value. 5821 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5822 unsigned SplatBitSize, SelectionDAG &DAG, 5823 const SDLoc &dl, EVT &VT, bool is128Bits, 5824 NEONModImmType type) { 5825 unsigned OpCmode, Imm; 5826 5827 // SplatBitSize is set to the smallest size that splats the vector, so a 5828 // zero vector will always have SplatBitSize == 8. However, NEON modified 5829 // immediate instructions others than VMOV do not support the 8-bit encoding 5830 // of a zero vector, and the default encoding of zero is supposed to be the 5831 // 32-bit version. 5832 if (SplatBits == 0) 5833 SplatBitSize = 32; 5834 5835 switch (SplatBitSize) { 5836 case 8: 5837 if (type != VMOVModImm) 5838 return SDValue(); 5839 // Any 1-byte value is OK. Op=0, Cmode=1110. 5840 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5841 OpCmode = 0xe; 5842 Imm = SplatBits; 5843 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5844 break; 5845 5846 case 16: 5847 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5848 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5849 if ((SplatBits & ~0xff) == 0) { 5850 // Value = 0x00nn: Op=x, Cmode=100x. 5851 OpCmode = 0x8; 5852 Imm = SplatBits; 5853 break; 5854 } 5855 if ((SplatBits & ~0xff00) == 0) { 5856 // Value = 0xnn00: Op=x, Cmode=101x. 5857 OpCmode = 0xa; 5858 Imm = SplatBits >> 8; 5859 break; 5860 } 5861 return SDValue(); 5862 5863 case 32: 5864 // NEON's 32-bit VMOV supports splat values where: 5865 // * only one byte is nonzero, or 5866 // * the least significant byte is 0xff and the second byte is nonzero, or 5867 // * the least significant 2 bytes are 0xff and the third is nonzero. 5868 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5869 if ((SplatBits & ~0xff) == 0) { 5870 // Value = 0x000000nn: Op=x, Cmode=000x. 5871 OpCmode = 0; 5872 Imm = SplatBits; 5873 break; 5874 } 5875 if ((SplatBits & ~0xff00) == 0) { 5876 // Value = 0x0000nn00: Op=x, Cmode=001x. 5877 OpCmode = 0x2; 5878 Imm = SplatBits >> 8; 5879 break; 5880 } 5881 if ((SplatBits & ~0xff0000) == 0) { 5882 // Value = 0x00nn0000: Op=x, Cmode=010x. 5883 OpCmode = 0x4; 5884 Imm = SplatBits >> 16; 5885 break; 5886 } 5887 if ((SplatBits & ~0xff000000) == 0) { 5888 // Value = 0xnn000000: Op=x, Cmode=011x. 5889 OpCmode = 0x6; 5890 Imm = SplatBits >> 24; 5891 break; 5892 } 5893 5894 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5895 if (type == OtherModImm) return SDValue(); 5896 5897 if ((SplatBits & ~0xffff) == 0 && 5898 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5899 // Value = 0x0000nnff: Op=x, Cmode=1100. 5900 OpCmode = 0xc; 5901 Imm = SplatBits >> 8; 5902 break; 5903 } 5904 5905 if ((SplatBits & ~0xffffff) == 0 && 5906 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5907 // Value = 0x00nnffff: Op=x, Cmode=1101. 5908 OpCmode = 0xd; 5909 Imm = SplatBits >> 16; 5910 break; 5911 } 5912 5913 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5914 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5915 // VMOV.I32. A (very) minor optimization would be to replicate the value 5916 // and fall through here to test for a valid 64-bit splat. But, then the 5917 // caller would also need to check and handle the change in size. 5918 return SDValue(); 5919 5920 case 64: { 5921 if (type != VMOVModImm) 5922 return SDValue(); 5923 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5924 uint64_t BitMask = 0xff; 5925 uint64_t Val = 0; 5926 unsigned ImmMask = 1; 5927 Imm = 0; 5928 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5929 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5930 Val |= BitMask; 5931 Imm |= ImmMask; 5932 } else if ((SplatBits & BitMask) != 0) { 5933 return SDValue(); 5934 } 5935 BitMask <<= 8; 5936 ImmMask <<= 1; 5937 } 5938 5939 if (DAG.getDataLayout().isBigEndian()) 5940 // swap higher and lower 32 bit word 5941 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5942 5943 // Op=1, Cmode=1110. 5944 OpCmode = 0x1e; 5945 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5946 break; 5947 } 5948 5949 default: 5950 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5951 } 5952 5953 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5954 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5955 } 5956 5957 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5958 const ARMSubtarget *ST) const { 5959 EVT VT = Op.getValueType(); 5960 bool IsDouble = (VT == MVT::f64); 5961 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5962 const APFloat &FPVal = CFP->getValueAPF(); 5963 5964 // Prevent floating-point constants from using literal loads 5965 // when execute-only is enabled. 5966 if (ST->genExecuteOnly()) { 5967 // If we can represent the constant as an immediate, don't lower it 5968 if (isFPImmLegal(FPVal, VT)) 5969 return Op; 5970 // Otherwise, construct as integer, and move to float register 5971 APInt INTVal = FPVal.bitcastToAPInt(); 5972 SDLoc DL(CFP); 5973 switch (VT.getSimpleVT().SimpleTy) { 5974 default: 5975 llvm_unreachable("Unknown floating point type!"); 5976 break; 5977 case MVT::f64: { 5978 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5979 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5980 if (!ST->isLittle()) 5981 std::swap(Lo, Hi); 5982 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5983 } 5984 case MVT::f32: 5985 return DAG.getNode(ARMISD::VMOVSR, DL, VT, 5986 DAG.getConstant(INTVal, DL, MVT::i32)); 5987 } 5988 } 5989 5990 if (!ST->hasVFP3()) 5991 return SDValue(); 5992 5993 // Use the default (constant pool) lowering for double constants when we have 5994 // an SP-only FPU 5995 if (IsDouble && Subtarget->isFPOnlySP()) 5996 return SDValue(); 5997 5998 // Try splatting with a VMOV.f32... 5999 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 6000 6001 if (ImmVal != -1) { 6002 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 6003 // We have code in place to select a valid ConstantFP already, no need to 6004 // do any mangling. 6005 return Op; 6006 } 6007 6008 // It's a float and we are trying to use NEON operations where 6009 // possible. Lower it to a splat followed by an extract. 6010 SDLoc DL(Op); 6011 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 6012 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 6013 NewVal); 6014 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 6015 DAG.getConstant(0, DL, MVT::i32)); 6016 } 6017 6018 // The rest of our options are NEON only, make sure that's allowed before 6019 // proceeding.. 6020 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 6021 return SDValue(); 6022 6023 EVT VMovVT; 6024 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 6025 6026 // It wouldn't really be worth bothering for doubles except for one very 6027 // important value, which does happen to match: 0.0. So make sure we don't do 6028 // anything stupid. 6029 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 6030 return SDValue(); 6031 6032 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 6033 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 6034 VMovVT, false, VMOVModImm); 6035 if (NewVal != SDValue()) { 6036 SDLoc DL(Op); 6037 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 6038 NewVal); 6039 if (IsDouble) 6040 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6041 6042 // It's a float: cast and extract a vector element. 6043 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6044 VecConstant); 6045 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6046 DAG.getConstant(0, DL, MVT::i32)); 6047 } 6048 6049 // Finally, try a VMVN.i32 6050 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 6051 false, VMVNModImm); 6052 if (NewVal != SDValue()) { 6053 SDLoc DL(Op); 6054 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 6055 6056 if (IsDouble) 6057 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 6058 6059 // It's a float: cast and extract a vector element. 6060 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 6061 VecConstant); 6062 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 6063 DAG.getConstant(0, DL, MVT::i32)); 6064 } 6065 6066 return SDValue(); 6067 } 6068 6069 // check if an VEXT instruction can handle the shuffle mask when the 6070 // vector sources of the shuffle are the same. 6071 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6072 unsigned NumElts = VT.getVectorNumElements(); 6073 6074 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6075 if (M[0] < 0) 6076 return false; 6077 6078 Imm = M[0]; 6079 6080 // If this is a VEXT shuffle, the immediate value is the index of the first 6081 // element. The other shuffle indices must be the successive elements after 6082 // the first one. 6083 unsigned ExpectedElt = Imm; 6084 for (unsigned i = 1; i < NumElts; ++i) { 6085 // Increment the expected index. If it wraps around, just follow it 6086 // back to index zero and keep going. 6087 ++ExpectedElt; 6088 if (ExpectedElt == NumElts) 6089 ExpectedElt = 0; 6090 6091 if (M[i] < 0) continue; // ignore UNDEF indices 6092 if (ExpectedElt != static_cast<unsigned>(M[i])) 6093 return false; 6094 } 6095 6096 return true; 6097 } 6098 6099 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6100 bool &ReverseVEXT, unsigned &Imm) { 6101 unsigned NumElts = VT.getVectorNumElements(); 6102 ReverseVEXT = false; 6103 6104 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6105 if (M[0] < 0) 6106 return false; 6107 6108 Imm = M[0]; 6109 6110 // If this is a VEXT shuffle, the immediate value is the index of the first 6111 // element. The other shuffle indices must be the successive elements after 6112 // the first one. 6113 unsigned ExpectedElt = Imm; 6114 for (unsigned i = 1; i < NumElts; ++i) { 6115 // Increment the expected index. If it wraps around, it may still be 6116 // a VEXT but the source vectors must be swapped. 6117 ExpectedElt += 1; 6118 if (ExpectedElt == NumElts * 2) { 6119 ExpectedElt = 0; 6120 ReverseVEXT = true; 6121 } 6122 6123 if (M[i] < 0) continue; // ignore UNDEF indices 6124 if (ExpectedElt != static_cast<unsigned>(M[i])) 6125 return false; 6126 } 6127 6128 // Adjust the index value if the source operands will be swapped. 6129 if (ReverseVEXT) 6130 Imm -= NumElts; 6131 6132 return true; 6133 } 6134 6135 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6136 /// instruction with the specified blocksize. (The order of the elements 6137 /// within each block of the vector is reversed.) 6138 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6139 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6140 "Only possible block sizes for VREV are: 16, 32, 64"); 6141 6142 unsigned EltSz = VT.getScalarSizeInBits(); 6143 if (EltSz == 64) 6144 return false; 6145 6146 unsigned NumElts = VT.getVectorNumElements(); 6147 unsigned BlockElts = M[0] + 1; 6148 // If the first shuffle index is UNDEF, be optimistic. 6149 if (M[0] < 0) 6150 BlockElts = BlockSize / EltSz; 6151 6152 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6153 return false; 6154 6155 for (unsigned i = 0; i < NumElts; ++i) { 6156 if (M[i] < 0) continue; // ignore UNDEF indices 6157 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6158 return false; 6159 } 6160 6161 return true; 6162 } 6163 6164 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6165 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6166 // range, then 0 is placed into the resulting vector. So pretty much any mask 6167 // of 8 elements can work here. 6168 return VT == MVT::v8i8 && M.size() == 8; 6169 } 6170 6171 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6172 unsigned Index) { 6173 if (Mask.size() == Elements * 2) 6174 return Index / Elements; 6175 return Mask[Index] == 0 ? 0 : 1; 6176 } 6177 6178 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6179 // checking that pairs of elements in the shuffle mask represent the same index 6180 // in each vector, incrementing the expected index by 2 at each step. 6181 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6182 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6183 // v2={e,f,g,h} 6184 // WhichResult gives the offset for each element in the mask based on which 6185 // of the two results it belongs to. 6186 // 6187 // The transpose can be represented either as: 6188 // result1 = shufflevector v1, v2, result1_shuffle_mask 6189 // result2 = shufflevector v1, v2, result2_shuffle_mask 6190 // where v1/v2 and the shuffle masks have the same number of elements 6191 // (here WhichResult (see below) indicates which result is being checked) 6192 // 6193 // or as: 6194 // results = shufflevector v1, v2, shuffle_mask 6195 // where both results are returned in one vector and the shuffle mask has twice 6196 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6197 // want to check the low half and high half of the shuffle mask as if it were 6198 // the other case 6199 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6200 unsigned EltSz = VT.getScalarSizeInBits(); 6201 if (EltSz == 64) 6202 return false; 6203 6204 unsigned NumElts = VT.getVectorNumElements(); 6205 if (M.size() != NumElts && M.size() != NumElts*2) 6206 return false; 6207 6208 // If the mask is twice as long as the input vector then we need to check the 6209 // upper and lower parts of the mask with a matching value for WhichResult 6210 // FIXME: A mask with only even values will be rejected in case the first 6211 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6212 // M[0] is used to determine WhichResult 6213 for (unsigned i = 0; i < M.size(); i += NumElts) { 6214 WhichResult = SelectPairHalf(NumElts, M, i); 6215 for (unsigned j = 0; j < NumElts; j += 2) { 6216 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6217 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6218 return false; 6219 } 6220 } 6221 6222 if (M.size() == NumElts*2) 6223 WhichResult = 0; 6224 6225 return true; 6226 } 6227 6228 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6229 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6230 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6231 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6232 unsigned EltSz = VT.getScalarSizeInBits(); 6233 if (EltSz == 64) 6234 return false; 6235 6236 unsigned NumElts = VT.getVectorNumElements(); 6237 if (M.size() != NumElts && M.size() != NumElts*2) 6238 return false; 6239 6240 for (unsigned i = 0; i < M.size(); i += NumElts) { 6241 WhichResult = SelectPairHalf(NumElts, M, i); 6242 for (unsigned j = 0; j < NumElts; j += 2) { 6243 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6244 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6245 return false; 6246 } 6247 } 6248 6249 if (M.size() == NumElts*2) 6250 WhichResult = 0; 6251 6252 return true; 6253 } 6254 6255 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6256 // that the mask elements are either all even and in steps of size 2 or all odd 6257 // and in steps of size 2. 6258 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6259 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6260 // v2={e,f,g,h} 6261 // Requires similar checks to that of isVTRNMask with 6262 // respect the how results are returned. 6263 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6264 unsigned EltSz = VT.getScalarSizeInBits(); 6265 if (EltSz == 64) 6266 return false; 6267 6268 unsigned NumElts = VT.getVectorNumElements(); 6269 if (M.size() != NumElts && M.size() != NumElts*2) 6270 return false; 6271 6272 for (unsigned i = 0; i < M.size(); i += NumElts) { 6273 WhichResult = SelectPairHalf(NumElts, M, i); 6274 for (unsigned j = 0; j < NumElts; ++j) { 6275 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6276 return false; 6277 } 6278 } 6279 6280 if (M.size() == NumElts*2) 6281 WhichResult = 0; 6282 6283 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6284 if (VT.is64BitVector() && EltSz == 32) 6285 return false; 6286 6287 return true; 6288 } 6289 6290 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6291 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6292 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6293 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6294 unsigned EltSz = VT.getScalarSizeInBits(); 6295 if (EltSz == 64) 6296 return false; 6297 6298 unsigned NumElts = VT.getVectorNumElements(); 6299 if (M.size() != NumElts && M.size() != NumElts*2) 6300 return false; 6301 6302 unsigned Half = NumElts / 2; 6303 for (unsigned i = 0; i < M.size(); i += NumElts) { 6304 WhichResult = SelectPairHalf(NumElts, M, i); 6305 for (unsigned j = 0; j < NumElts; j += Half) { 6306 unsigned Idx = WhichResult; 6307 for (unsigned k = 0; k < Half; ++k) { 6308 int MIdx = M[i + j + k]; 6309 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6310 return false; 6311 Idx += 2; 6312 } 6313 } 6314 } 6315 6316 if (M.size() == NumElts*2) 6317 WhichResult = 0; 6318 6319 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6320 if (VT.is64BitVector() && EltSz == 32) 6321 return false; 6322 6323 return true; 6324 } 6325 6326 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6327 // that pairs of elements of the shufflemask represent the same index in each 6328 // vector incrementing sequentially through the vectors. 6329 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6330 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6331 // v2={e,f,g,h} 6332 // Requires similar checks to that of isVTRNMask with respect the how results 6333 // are returned. 6334 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6335 unsigned EltSz = VT.getScalarSizeInBits(); 6336 if (EltSz == 64) 6337 return false; 6338 6339 unsigned NumElts = VT.getVectorNumElements(); 6340 if (M.size() != NumElts && M.size() != NumElts*2) 6341 return false; 6342 6343 for (unsigned i = 0; i < M.size(); i += NumElts) { 6344 WhichResult = SelectPairHalf(NumElts, M, i); 6345 unsigned Idx = WhichResult * NumElts / 2; 6346 for (unsigned j = 0; j < NumElts; j += 2) { 6347 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6348 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6349 return false; 6350 Idx += 1; 6351 } 6352 } 6353 6354 if (M.size() == NumElts*2) 6355 WhichResult = 0; 6356 6357 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6358 if (VT.is64BitVector() && EltSz == 32) 6359 return false; 6360 6361 return true; 6362 } 6363 6364 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6365 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6366 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6367 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6368 unsigned EltSz = VT.getScalarSizeInBits(); 6369 if (EltSz == 64) 6370 return false; 6371 6372 unsigned NumElts = VT.getVectorNumElements(); 6373 if (M.size() != NumElts && M.size() != NumElts*2) 6374 return false; 6375 6376 for (unsigned i = 0; i < M.size(); i += NumElts) { 6377 WhichResult = SelectPairHalf(NumElts, M, i); 6378 unsigned Idx = WhichResult * NumElts / 2; 6379 for (unsigned j = 0; j < NumElts; j += 2) { 6380 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6381 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6382 return false; 6383 Idx += 1; 6384 } 6385 } 6386 6387 if (M.size() == NumElts*2) 6388 WhichResult = 0; 6389 6390 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6391 if (VT.is64BitVector() && EltSz == 32) 6392 return false; 6393 6394 return true; 6395 } 6396 6397 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6398 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6399 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6400 unsigned &WhichResult, 6401 bool &isV_UNDEF) { 6402 isV_UNDEF = false; 6403 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6404 return ARMISD::VTRN; 6405 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6406 return ARMISD::VUZP; 6407 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6408 return ARMISD::VZIP; 6409 6410 isV_UNDEF = true; 6411 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6412 return ARMISD::VTRN; 6413 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6414 return ARMISD::VUZP; 6415 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6416 return ARMISD::VZIP; 6417 6418 return 0; 6419 } 6420 6421 /// \return true if this is a reverse operation on an vector. 6422 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6423 unsigned NumElts = VT.getVectorNumElements(); 6424 // Make sure the mask has the right size. 6425 if (NumElts != M.size()) 6426 return false; 6427 6428 // Look for <15, ..., 3, -1, 1, 0>. 6429 for (unsigned i = 0; i != NumElts; ++i) 6430 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6431 return false; 6432 6433 return true; 6434 } 6435 6436 // If N is an integer constant that can be moved into a register in one 6437 // instruction, return an SDValue of such a constant (will become a MOV 6438 // instruction). Otherwise return null. 6439 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6440 const ARMSubtarget *ST, const SDLoc &dl) { 6441 uint64_t Val; 6442 if (!isa<ConstantSDNode>(N)) 6443 return SDValue(); 6444 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6445 6446 if (ST->isThumb1Only()) { 6447 if (Val <= 255 || ~Val <= 255) 6448 return DAG.getConstant(Val, dl, MVT::i32); 6449 } else { 6450 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6451 return DAG.getConstant(Val, dl, MVT::i32); 6452 } 6453 return SDValue(); 6454 } 6455 6456 // If this is a case we can't handle, return null and let the default 6457 // expansion code take care of it. 6458 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6459 const ARMSubtarget *ST) const { 6460 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6461 SDLoc dl(Op); 6462 EVT VT = Op.getValueType(); 6463 6464 APInt SplatBits, SplatUndef; 6465 unsigned SplatBitSize; 6466 bool HasAnyUndefs; 6467 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6468 if (SplatUndef.isAllOnesValue()) 6469 return DAG.getUNDEF(VT); 6470 6471 if (SplatBitSize <= 64) { 6472 // Check if an immediate VMOV works. 6473 EVT VmovVT; 6474 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6475 SplatUndef.getZExtValue(), SplatBitSize, 6476 DAG, dl, VmovVT, VT.is128BitVector(), 6477 VMOVModImm); 6478 if (Val.getNode()) { 6479 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6480 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6481 } 6482 6483 // Try an immediate VMVN. 6484 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6485 Val = isNEONModifiedImm(NegatedImm, 6486 SplatUndef.getZExtValue(), SplatBitSize, 6487 DAG, dl, VmovVT, VT.is128BitVector(), 6488 VMVNModImm); 6489 if (Val.getNode()) { 6490 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6491 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6492 } 6493 6494 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6495 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6496 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6497 if (ImmVal != -1) { 6498 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6499 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6500 } 6501 } 6502 } 6503 } 6504 6505 // Scan through the operands to see if only one value is used. 6506 // 6507 // As an optimisation, even if more than one value is used it may be more 6508 // profitable to splat with one value then change some lanes. 6509 // 6510 // Heuristically we decide to do this if the vector has a "dominant" value, 6511 // defined as splatted to more than half of the lanes. 6512 unsigned NumElts = VT.getVectorNumElements(); 6513 bool isOnlyLowElement = true; 6514 bool usesOnlyOneValue = true; 6515 bool hasDominantValue = false; 6516 bool isConstant = true; 6517 6518 // Map of the number of times a particular SDValue appears in the 6519 // element list. 6520 DenseMap<SDValue, unsigned> ValueCounts; 6521 SDValue Value; 6522 for (unsigned i = 0; i < NumElts; ++i) { 6523 SDValue V = Op.getOperand(i); 6524 if (V.isUndef()) 6525 continue; 6526 if (i > 0) 6527 isOnlyLowElement = false; 6528 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6529 isConstant = false; 6530 6531 ValueCounts.insert(std::make_pair(V, 0)); 6532 unsigned &Count = ValueCounts[V]; 6533 6534 // Is this value dominant? (takes up more than half of the lanes) 6535 if (++Count > (NumElts / 2)) { 6536 hasDominantValue = true; 6537 Value = V; 6538 } 6539 } 6540 if (ValueCounts.size() != 1) 6541 usesOnlyOneValue = false; 6542 if (!Value.getNode() && !ValueCounts.empty()) 6543 Value = ValueCounts.begin()->first; 6544 6545 if (ValueCounts.empty()) 6546 return DAG.getUNDEF(VT); 6547 6548 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6549 // Keep going if we are hitting this case. 6550 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6551 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6552 6553 unsigned EltSize = VT.getScalarSizeInBits(); 6554 6555 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6556 // i32 and try again. 6557 if (hasDominantValue && EltSize <= 32) { 6558 if (!isConstant) { 6559 SDValue N; 6560 6561 // If we are VDUPing a value that comes directly from a vector, that will 6562 // cause an unnecessary move to and from a GPR, where instead we could 6563 // just use VDUPLANE. We can only do this if the lane being extracted 6564 // is at a constant index, as the VDUP from lane instructions only have 6565 // constant-index forms. 6566 ConstantSDNode *constIndex; 6567 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6568 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6569 // We need to create a new undef vector to use for the VDUPLANE if the 6570 // size of the vector from which we get the value is different than the 6571 // size of the vector that we need to create. We will insert the element 6572 // such that the register coalescer will remove unnecessary copies. 6573 if (VT != Value->getOperand(0).getValueType()) { 6574 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6575 VT.getVectorNumElements(); 6576 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6577 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6578 Value, DAG.getConstant(index, dl, MVT::i32)), 6579 DAG.getConstant(index, dl, MVT::i32)); 6580 } else 6581 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6582 Value->getOperand(0), Value->getOperand(1)); 6583 } else 6584 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6585 6586 if (!usesOnlyOneValue) { 6587 // The dominant value was splatted as 'N', but we now have to insert 6588 // all differing elements. 6589 for (unsigned I = 0; I < NumElts; ++I) { 6590 if (Op.getOperand(I) == Value) 6591 continue; 6592 SmallVector<SDValue, 3> Ops; 6593 Ops.push_back(N); 6594 Ops.push_back(Op.getOperand(I)); 6595 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6596 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6597 } 6598 } 6599 return N; 6600 } 6601 if (VT.getVectorElementType().isFloatingPoint()) { 6602 SmallVector<SDValue, 8> Ops; 6603 for (unsigned i = 0; i < NumElts; ++i) 6604 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6605 Op.getOperand(i))); 6606 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6607 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6608 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6609 if (Val.getNode()) 6610 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6611 } 6612 if (usesOnlyOneValue) { 6613 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6614 if (isConstant && Val.getNode()) 6615 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6616 } 6617 } 6618 6619 // If all elements are constants and the case above didn't get hit, fall back 6620 // to the default expansion, which will generate a load from the constant 6621 // pool. 6622 if (isConstant) 6623 return SDValue(); 6624 6625 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6626 if (NumElts >= 4) { 6627 SDValue shuffle = ReconstructShuffle(Op, DAG); 6628 if (shuffle != SDValue()) 6629 return shuffle; 6630 } 6631 6632 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6633 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6634 // into two 64-bit vectors; we might discover a better way to lower it. 6635 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6636 EVT ExtVT = VT.getVectorElementType(); 6637 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6638 SDValue Lower = 6639 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6640 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6641 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6642 SDValue Upper = DAG.getBuildVector( 6643 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6644 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6645 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6646 if (Lower && Upper) 6647 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6648 } 6649 6650 // Vectors with 32- or 64-bit elements can be built by directly assigning 6651 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6652 // will be legalized. 6653 if (EltSize >= 32) { 6654 // Do the expansion with floating-point types, since that is what the VFP 6655 // registers are defined to use, and since i64 is not legal. 6656 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6657 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6658 SmallVector<SDValue, 8> Ops; 6659 for (unsigned i = 0; i < NumElts; ++i) 6660 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6661 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6662 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6663 } 6664 6665 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6666 // know the default expansion would otherwise fall back on something even 6667 // worse. For a vector with one or two non-undef values, that's 6668 // scalar_to_vector for the elements followed by a shuffle (provided the 6669 // shuffle is valid for the target) and materialization element by element 6670 // on the stack followed by a load for everything else. 6671 if (!isConstant && !usesOnlyOneValue) { 6672 SDValue Vec = DAG.getUNDEF(VT); 6673 for (unsigned i = 0 ; i < NumElts; ++i) { 6674 SDValue V = Op.getOperand(i); 6675 if (V.isUndef()) 6676 continue; 6677 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6678 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6679 } 6680 return Vec; 6681 } 6682 6683 return SDValue(); 6684 } 6685 6686 // Gather data to see if the operation can be modelled as a 6687 // shuffle in combination with VEXTs. 6688 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6689 SelectionDAG &DAG) const { 6690 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6691 SDLoc dl(Op); 6692 EVT VT = Op.getValueType(); 6693 unsigned NumElts = VT.getVectorNumElements(); 6694 6695 struct ShuffleSourceInfo { 6696 SDValue Vec; 6697 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6698 unsigned MaxElt = 0; 6699 6700 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6701 // be compatible with the shuffle we intend to construct. As a result 6702 // ShuffleVec will be some sliding window into the original Vec. 6703 SDValue ShuffleVec; 6704 6705 // Code should guarantee that element i in Vec starts at element "WindowBase 6706 // + i * WindowScale in ShuffleVec". 6707 int WindowBase = 0; 6708 int WindowScale = 1; 6709 6710 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6711 6712 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6713 }; 6714 6715 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6716 // node. 6717 SmallVector<ShuffleSourceInfo, 2> Sources; 6718 for (unsigned i = 0; i < NumElts; ++i) { 6719 SDValue V = Op.getOperand(i); 6720 if (V.isUndef()) 6721 continue; 6722 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6723 // A shuffle can only come from building a vector from various 6724 // elements of other vectors. 6725 return SDValue(); 6726 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6727 // Furthermore, shuffles require a constant mask, whereas extractelts 6728 // accept variable indices. 6729 return SDValue(); 6730 } 6731 6732 // Add this element source to the list if it's not already there. 6733 SDValue SourceVec = V.getOperand(0); 6734 auto Source = llvm::find(Sources, SourceVec); 6735 if (Source == Sources.end()) 6736 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6737 6738 // Update the minimum and maximum lane number seen. 6739 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6740 Source->MinElt = std::min(Source->MinElt, EltNo); 6741 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6742 } 6743 6744 // Currently only do something sane when at most two source vectors 6745 // are involved. 6746 if (Sources.size() > 2) 6747 return SDValue(); 6748 6749 // Find out the smallest element size among result and two sources, and use 6750 // it as element size to build the shuffle_vector. 6751 EVT SmallestEltTy = VT.getVectorElementType(); 6752 for (auto &Source : Sources) { 6753 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6754 if (SrcEltTy.bitsLT(SmallestEltTy)) 6755 SmallestEltTy = SrcEltTy; 6756 } 6757 unsigned ResMultiplier = 6758 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6759 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6760 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6761 6762 // If the source vector is too wide or too narrow, we may nevertheless be able 6763 // to construct a compatible shuffle either by concatenating it with UNDEF or 6764 // extracting a suitable range of elements. 6765 for (auto &Src : Sources) { 6766 EVT SrcVT = Src.ShuffleVec.getValueType(); 6767 6768 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6769 continue; 6770 6771 // This stage of the search produces a source with the same element type as 6772 // the original, but with a total width matching the BUILD_VECTOR output. 6773 EVT EltVT = SrcVT.getVectorElementType(); 6774 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6775 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6776 6777 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6778 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6779 return SDValue(); 6780 // We can pad out the smaller vector for free, so if it's part of a 6781 // shuffle... 6782 Src.ShuffleVec = 6783 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6784 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6785 continue; 6786 } 6787 6788 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6789 return SDValue(); 6790 6791 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6792 // Span too large for a VEXT to cope 6793 return SDValue(); 6794 } 6795 6796 if (Src.MinElt >= NumSrcElts) { 6797 // The extraction can just take the second half 6798 Src.ShuffleVec = 6799 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6800 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6801 Src.WindowBase = -NumSrcElts; 6802 } else if (Src.MaxElt < NumSrcElts) { 6803 // The extraction can just take the first half 6804 Src.ShuffleVec = 6805 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6806 DAG.getConstant(0, dl, MVT::i32)); 6807 } else { 6808 // An actual VEXT is needed 6809 SDValue VEXTSrc1 = 6810 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6811 DAG.getConstant(0, dl, MVT::i32)); 6812 SDValue VEXTSrc2 = 6813 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6814 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6815 6816 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6817 VEXTSrc2, 6818 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6819 Src.WindowBase = -Src.MinElt; 6820 } 6821 } 6822 6823 // Another possible incompatibility occurs from the vector element types. We 6824 // can fix this by bitcasting the source vectors to the same type we intend 6825 // for the shuffle. 6826 for (auto &Src : Sources) { 6827 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6828 if (SrcEltTy == SmallestEltTy) 6829 continue; 6830 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6831 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6832 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6833 Src.WindowBase *= Src.WindowScale; 6834 } 6835 6836 // Final sanity check before we try to actually produce a shuffle. 6837 LLVM_DEBUG(for (auto Src 6838 : Sources) 6839 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 6840 6841 // The stars all align, our next step is to produce the mask for the shuffle. 6842 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6843 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6844 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6845 SDValue Entry = Op.getOperand(i); 6846 if (Entry.isUndef()) 6847 continue; 6848 6849 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6850 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6851 6852 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6853 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6854 // segment. 6855 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6856 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6857 VT.getScalarSizeInBits()); 6858 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6859 6860 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6861 // starting at the appropriate offset. 6862 int *LaneMask = &Mask[i * ResMultiplier]; 6863 6864 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6865 ExtractBase += NumElts * (Src - Sources.begin()); 6866 for (int j = 0; j < LanesDefined; ++j) 6867 LaneMask[j] = ExtractBase + j; 6868 } 6869 6870 // Final check before we try to produce nonsense... 6871 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6872 return SDValue(); 6873 6874 // We can't handle more than two sources. This should have already 6875 // been checked before this point. 6876 assert(Sources.size() <= 2 && "Too many sources!"); 6877 6878 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6879 for (unsigned i = 0; i < Sources.size(); ++i) 6880 ShuffleOps[i] = Sources[i].ShuffleVec; 6881 6882 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6883 ShuffleOps[1], Mask); 6884 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6885 } 6886 6887 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6888 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6889 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6890 /// are assumed to be legal. 6891 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 6892 if (VT.getVectorNumElements() == 4 && 6893 (VT.is128BitVector() || VT.is64BitVector())) { 6894 unsigned PFIndexes[4]; 6895 for (unsigned i = 0; i != 4; ++i) { 6896 if (M[i] < 0) 6897 PFIndexes[i] = 8; 6898 else 6899 PFIndexes[i] = M[i]; 6900 } 6901 6902 // Compute the index in the perfect shuffle table. 6903 unsigned PFTableIndex = 6904 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6905 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6906 unsigned Cost = (PFEntry >> 30); 6907 6908 if (Cost <= 4) 6909 return true; 6910 } 6911 6912 bool ReverseVEXT, isV_UNDEF; 6913 unsigned Imm, WhichResult; 6914 6915 unsigned EltSize = VT.getScalarSizeInBits(); 6916 return (EltSize >= 32 || 6917 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6918 isVREVMask(M, VT, 64) || 6919 isVREVMask(M, VT, 32) || 6920 isVREVMask(M, VT, 16) || 6921 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6922 isVTBLMask(M, VT) || 6923 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6924 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6925 } 6926 6927 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6928 /// the specified operations to build the shuffle. 6929 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6930 SDValue RHS, SelectionDAG &DAG, 6931 const SDLoc &dl) { 6932 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6933 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6934 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6935 6936 enum { 6937 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6938 OP_VREV, 6939 OP_VDUP0, 6940 OP_VDUP1, 6941 OP_VDUP2, 6942 OP_VDUP3, 6943 OP_VEXT1, 6944 OP_VEXT2, 6945 OP_VEXT3, 6946 OP_VUZPL, // VUZP, left result 6947 OP_VUZPR, // VUZP, right result 6948 OP_VZIPL, // VZIP, left result 6949 OP_VZIPR, // VZIP, right result 6950 OP_VTRNL, // VTRN, left result 6951 OP_VTRNR // VTRN, right result 6952 }; 6953 6954 if (OpNum == OP_COPY) { 6955 if (LHSID == (1*9+2)*9+3) return LHS; 6956 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6957 return RHS; 6958 } 6959 6960 SDValue OpLHS, OpRHS; 6961 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6962 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6963 EVT VT = OpLHS.getValueType(); 6964 6965 switch (OpNum) { 6966 default: llvm_unreachable("Unknown shuffle opcode!"); 6967 case OP_VREV: 6968 // VREV divides the vector in half and swaps within the half. 6969 if (VT.getVectorElementType() == MVT::i32 || 6970 VT.getVectorElementType() == MVT::f32) 6971 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6972 // vrev <4 x i16> -> VREV32 6973 if (VT.getVectorElementType() == MVT::i16) 6974 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6975 // vrev <4 x i8> -> VREV16 6976 assert(VT.getVectorElementType() == MVT::i8); 6977 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6978 case OP_VDUP0: 6979 case OP_VDUP1: 6980 case OP_VDUP2: 6981 case OP_VDUP3: 6982 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6983 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6984 case OP_VEXT1: 6985 case OP_VEXT2: 6986 case OP_VEXT3: 6987 return DAG.getNode(ARMISD::VEXT, dl, VT, 6988 OpLHS, OpRHS, 6989 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6990 case OP_VUZPL: 6991 case OP_VUZPR: 6992 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6993 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6994 case OP_VZIPL: 6995 case OP_VZIPR: 6996 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6997 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6998 case OP_VTRNL: 6999 case OP_VTRNR: 7000 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 7001 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 7002 } 7003 } 7004 7005 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 7006 ArrayRef<int> ShuffleMask, 7007 SelectionDAG &DAG) { 7008 // Check to see if we can use the VTBL instruction. 7009 SDValue V1 = Op.getOperand(0); 7010 SDValue V2 = Op.getOperand(1); 7011 SDLoc DL(Op); 7012 7013 SmallVector<SDValue, 8> VTBLMask; 7014 for (ArrayRef<int>::iterator 7015 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 7016 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 7017 7018 if (V2.getNode()->isUndef()) 7019 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 7020 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7021 7022 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 7023 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 7024 } 7025 7026 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 7027 SelectionDAG &DAG) { 7028 SDLoc DL(Op); 7029 SDValue OpLHS = Op.getOperand(0); 7030 EVT VT = OpLHS.getValueType(); 7031 7032 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 7033 "Expect an v8i16/v16i8 type"); 7034 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 7035 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 7036 // extract the first 8 bytes into the top double word and the last 8 bytes 7037 // into the bottom double word. The v8i16 case is similar. 7038 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 7039 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 7040 DAG.getConstant(ExtractNum, DL, MVT::i32)); 7041 } 7042 7043 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 7044 SDValue V1 = Op.getOperand(0); 7045 SDValue V2 = Op.getOperand(1); 7046 SDLoc dl(Op); 7047 EVT VT = Op.getValueType(); 7048 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7049 7050 // Convert shuffles that are directly supported on NEON to target-specific 7051 // DAG nodes, instead of keeping them as shuffles and matching them again 7052 // during code selection. This is more efficient and avoids the possibility 7053 // of inconsistencies between legalization and selection. 7054 // FIXME: floating-point vectors should be canonicalized to integer vectors 7055 // of the same time so that they get CSEd properly. 7056 ArrayRef<int> ShuffleMask = SVN->getMask(); 7057 7058 unsigned EltSize = VT.getScalarSizeInBits(); 7059 if (EltSize <= 32) { 7060 if (SVN->isSplat()) { 7061 int Lane = SVN->getSplatIndex(); 7062 // If this is undef splat, generate it via "just" vdup, if possible. 7063 if (Lane == -1) Lane = 0; 7064 7065 // Test if V1 is a SCALAR_TO_VECTOR. 7066 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 7067 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7068 } 7069 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7070 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 7071 // reaches it). 7072 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 7073 !isa<ConstantSDNode>(V1.getOperand(0))) { 7074 bool IsScalarToVector = true; 7075 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 7076 if (!V1.getOperand(i).isUndef()) { 7077 IsScalarToVector = false; 7078 break; 7079 } 7080 if (IsScalarToVector) 7081 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7082 } 7083 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7084 DAG.getConstant(Lane, dl, MVT::i32)); 7085 } 7086 7087 bool ReverseVEXT; 7088 unsigned Imm; 7089 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7090 if (ReverseVEXT) 7091 std::swap(V1, V2); 7092 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7093 DAG.getConstant(Imm, dl, MVT::i32)); 7094 } 7095 7096 if (isVREVMask(ShuffleMask, VT, 64)) 7097 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7098 if (isVREVMask(ShuffleMask, VT, 32)) 7099 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7100 if (isVREVMask(ShuffleMask, VT, 16)) 7101 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7102 7103 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7104 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7105 DAG.getConstant(Imm, dl, MVT::i32)); 7106 } 7107 7108 // Check for Neon shuffles that modify both input vectors in place. 7109 // If both results are used, i.e., if there are two shuffles with the same 7110 // source operands and with masks corresponding to both results of one of 7111 // these operations, DAG memoization will ensure that a single node is 7112 // used for both shuffles. 7113 unsigned WhichResult; 7114 bool isV_UNDEF; 7115 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7116 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7117 if (isV_UNDEF) 7118 V2 = V1; 7119 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7120 .getValue(WhichResult); 7121 } 7122 7123 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7124 // shuffles that produce a result larger than their operands with: 7125 // shuffle(concat(v1, undef), concat(v2, undef)) 7126 // -> 7127 // shuffle(concat(v1, v2), undef) 7128 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7129 // 7130 // This is useful in the general case, but there are special cases where 7131 // native shuffles produce larger results: the two-result ops. 7132 // 7133 // Look through the concat when lowering them: 7134 // shuffle(concat(v1, v2), undef) 7135 // -> 7136 // concat(VZIP(v1, v2):0, :1) 7137 // 7138 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7139 SDValue SubV1 = V1->getOperand(0); 7140 SDValue SubV2 = V1->getOperand(1); 7141 EVT SubVT = SubV1.getValueType(); 7142 7143 // We expect these to have been canonicalized to -1. 7144 assert(llvm::all_of(ShuffleMask, [&](int i) { 7145 return i < (int)VT.getVectorNumElements(); 7146 }) && "Unexpected shuffle index into UNDEF operand!"); 7147 7148 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7149 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7150 if (isV_UNDEF) 7151 SubV2 = SubV1; 7152 assert((WhichResult == 0) && 7153 "In-place shuffle of concat can only have one result!"); 7154 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7155 SubV1, SubV2); 7156 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7157 Res.getValue(1)); 7158 } 7159 } 7160 } 7161 7162 // If the shuffle is not directly supported and it has 4 elements, use 7163 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7164 unsigned NumElts = VT.getVectorNumElements(); 7165 if (NumElts == 4) { 7166 unsigned PFIndexes[4]; 7167 for (unsigned i = 0; i != 4; ++i) { 7168 if (ShuffleMask[i] < 0) 7169 PFIndexes[i] = 8; 7170 else 7171 PFIndexes[i] = ShuffleMask[i]; 7172 } 7173 7174 // Compute the index in the perfect shuffle table. 7175 unsigned PFTableIndex = 7176 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7177 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7178 unsigned Cost = (PFEntry >> 30); 7179 7180 if (Cost <= 4) 7181 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7182 } 7183 7184 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7185 if (EltSize >= 32) { 7186 // Do the expansion with floating-point types, since that is what the VFP 7187 // registers are defined to use, and since i64 is not legal. 7188 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7189 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7190 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7191 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7192 SmallVector<SDValue, 8> Ops; 7193 for (unsigned i = 0; i < NumElts; ++i) { 7194 if (ShuffleMask[i] < 0) 7195 Ops.push_back(DAG.getUNDEF(EltVT)); 7196 else 7197 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7198 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7199 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7200 dl, MVT::i32))); 7201 } 7202 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7203 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7204 } 7205 7206 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7207 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7208 7209 if (VT == MVT::v8i8) 7210 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7211 return NewOp; 7212 7213 return SDValue(); 7214 } 7215 7216 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7217 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7218 SDValue Lane = Op.getOperand(2); 7219 if (!isa<ConstantSDNode>(Lane)) 7220 return SDValue(); 7221 7222 return Op; 7223 } 7224 7225 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7226 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7227 SDValue Lane = Op.getOperand(1); 7228 if (!isa<ConstantSDNode>(Lane)) 7229 return SDValue(); 7230 7231 SDValue Vec = Op.getOperand(0); 7232 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7233 SDLoc dl(Op); 7234 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7235 } 7236 7237 return Op; 7238 } 7239 7240 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 7241 // The only time a CONCAT_VECTORS operation can have legal types is when 7242 // two 64-bit vectors are concatenated to a 128-bit vector. 7243 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7244 "unexpected CONCAT_VECTORS"); 7245 SDLoc dl(Op); 7246 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7247 SDValue Op0 = Op.getOperand(0); 7248 SDValue Op1 = Op.getOperand(1); 7249 if (!Op0.isUndef()) 7250 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7251 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7252 DAG.getIntPtrConstant(0, dl)); 7253 if (!Op1.isUndef()) 7254 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7255 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7256 DAG.getIntPtrConstant(1, dl)); 7257 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7258 } 7259 7260 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7261 /// element has been zero/sign-extended, depending on the isSigned parameter, 7262 /// from an integer type half its size. 7263 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7264 bool isSigned) { 7265 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7266 EVT VT = N->getValueType(0); 7267 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7268 SDNode *BVN = N->getOperand(0).getNode(); 7269 if (BVN->getValueType(0) != MVT::v4i32 || 7270 BVN->getOpcode() != ISD::BUILD_VECTOR) 7271 return false; 7272 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7273 unsigned HiElt = 1 - LoElt; 7274 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7275 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7276 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7277 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7278 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7279 return false; 7280 if (isSigned) { 7281 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7282 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7283 return true; 7284 } else { 7285 if (Hi0->isNullValue() && Hi1->isNullValue()) 7286 return true; 7287 } 7288 return false; 7289 } 7290 7291 if (N->getOpcode() != ISD::BUILD_VECTOR) 7292 return false; 7293 7294 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7295 SDNode *Elt = N->getOperand(i).getNode(); 7296 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 7297 unsigned EltSize = VT.getScalarSizeInBits(); 7298 unsigned HalfSize = EltSize / 2; 7299 if (isSigned) { 7300 if (!isIntN(HalfSize, C->getSExtValue())) 7301 return false; 7302 } else { 7303 if (!isUIntN(HalfSize, C->getZExtValue())) 7304 return false; 7305 } 7306 continue; 7307 } 7308 return false; 7309 } 7310 7311 return true; 7312 } 7313 7314 /// isSignExtended - Check if a node is a vector value that is sign-extended 7315 /// or a constant BUILD_VECTOR with sign-extended elements. 7316 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7317 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7318 return true; 7319 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7320 return true; 7321 return false; 7322 } 7323 7324 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7325 /// or a constant BUILD_VECTOR with zero-extended elements. 7326 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7327 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7328 return true; 7329 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7330 return true; 7331 return false; 7332 } 7333 7334 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7335 if (OrigVT.getSizeInBits() >= 64) 7336 return OrigVT; 7337 7338 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7339 7340 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7341 switch (OrigSimpleTy) { 7342 default: llvm_unreachable("Unexpected Vector Type"); 7343 case MVT::v2i8: 7344 case MVT::v2i16: 7345 return MVT::v2i32; 7346 case MVT::v4i8: 7347 return MVT::v4i16; 7348 } 7349 } 7350 7351 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7352 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7353 /// We insert the required extension here to get the vector to fill a D register. 7354 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7355 const EVT &OrigTy, 7356 const EVT &ExtTy, 7357 unsigned ExtOpcode) { 7358 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7359 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7360 // 64-bits we need to insert a new extension so that it will be 64-bits. 7361 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7362 if (OrigTy.getSizeInBits() >= 64) 7363 return N; 7364 7365 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7366 EVT NewVT = getExtensionTo64Bits(OrigTy); 7367 7368 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7369 } 7370 7371 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7372 /// does not do any sign/zero extension. If the original vector is less 7373 /// than 64 bits, an appropriate extension will be added after the load to 7374 /// reach a total size of 64 bits. We have to add the extension separately 7375 /// because ARM does not have a sign/zero extending load for vectors. 7376 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7377 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7378 7379 // The load already has the right type. 7380 if (ExtendedTy == LD->getMemoryVT()) 7381 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7382 LD->getBasePtr(), LD->getPointerInfo(), 7383 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7384 7385 // We need to create a zextload/sextload. We cannot just create a load 7386 // followed by a zext/zext node because LowerMUL is also run during normal 7387 // operation legalization where we can't create illegal types. 7388 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7389 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7390 LD->getMemoryVT(), LD->getAlignment(), 7391 LD->getMemOperand()->getFlags()); 7392 } 7393 7394 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7395 /// extending load, or BUILD_VECTOR with extended elements, return the 7396 /// unextended value. The unextended vector should be 64 bits so that it can 7397 /// be used as an operand to a VMULL instruction. If the original vector size 7398 /// before extension is less than 64 bits we add a an extension to resize 7399 /// the vector to 64 bits. 7400 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7401 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7402 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7403 N->getOperand(0)->getValueType(0), 7404 N->getValueType(0), 7405 N->getOpcode()); 7406 7407 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7408 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7409 "Expected extending load"); 7410 7411 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7412 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7413 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7414 SDValue extLoad = 7415 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7416 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7417 7418 return newLoad; 7419 } 7420 7421 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7422 // have been legalized as a BITCAST from v4i32. 7423 if (N->getOpcode() == ISD::BITCAST) { 7424 SDNode *BVN = N->getOperand(0).getNode(); 7425 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7426 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7427 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7428 return DAG.getBuildVector( 7429 MVT::v2i32, SDLoc(N), 7430 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7431 } 7432 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7433 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7434 EVT VT = N->getValueType(0); 7435 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7436 unsigned NumElts = VT.getVectorNumElements(); 7437 MVT TruncVT = MVT::getIntegerVT(EltSize); 7438 SmallVector<SDValue, 8> Ops; 7439 SDLoc dl(N); 7440 for (unsigned i = 0; i != NumElts; ++i) { 7441 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7442 const APInt &CInt = C->getAPIntValue(); 7443 // Element types smaller than 32 bits are not legal, so use i32 elements. 7444 // The values are implicitly truncated so sext vs. zext doesn't matter. 7445 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7446 } 7447 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7448 } 7449 7450 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7451 unsigned Opcode = N->getOpcode(); 7452 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7453 SDNode *N0 = N->getOperand(0).getNode(); 7454 SDNode *N1 = N->getOperand(1).getNode(); 7455 return N0->hasOneUse() && N1->hasOneUse() && 7456 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7457 } 7458 return false; 7459 } 7460 7461 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7462 unsigned Opcode = N->getOpcode(); 7463 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7464 SDNode *N0 = N->getOperand(0).getNode(); 7465 SDNode *N1 = N->getOperand(1).getNode(); 7466 return N0->hasOneUse() && N1->hasOneUse() && 7467 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7468 } 7469 return false; 7470 } 7471 7472 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7473 // Multiplications are only custom-lowered for 128-bit vectors so that 7474 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7475 EVT VT = Op.getValueType(); 7476 assert(VT.is128BitVector() && VT.isInteger() && 7477 "unexpected type for custom-lowering ISD::MUL"); 7478 SDNode *N0 = Op.getOperand(0).getNode(); 7479 SDNode *N1 = Op.getOperand(1).getNode(); 7480 unsigned NewOpc = 0; 7481 bool isMLA = false; 7482 bool isN0SExt = isSignExtended(N0, DAG); 7483 bool isN1SExt = isSignExtended(N1, DAG); 7484 if (isN0SExt && isN1SExt) 7485 NewOpc = ARMISD::VMULLs; 7486 else { 7487 bool isN0ZExt = isZeroExtended(N0, DAG); 7488 bool isN1ZExt = isZeroExtended(N1, DAG); 7489 if (isN0ZExt && isN1ZExt) 7490 NewOpc = ARMISD::VMULLu; 7491 else if (isN1SExt || isN1ZExt) { 7492 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7493 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7494 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7495 NewOpc = ARMISD::VMULLs; 7496 isMLA = true; 7497 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7498 NewOpc = ARMISD::VMULLu; 7499 isMLA = true; 7500 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7501 std::swap(N0, N1); 7502 NewOpc = ARMISD::VMULLu; 7503 isMLA = true; 7504 } 7505 } 7506 7507 if (!NewOpc) { 7508 if (VT == MVT::v2i64) 7509 // Fall through to expand this. It is not legal. 7510 return SDValue(); 7511 else 7512 // Other vector multiplications are legal. 7513 return Op; 7514 } 7515 } 7516 7517 // Legalize to a VMULL instruction. 7518 SDLoc DL(Op); 7519 SDValue Op0; 7520 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7521 if (!isMLA) { 7522 Op0 = SkipExtensionForVMULL(N0, DAG); 7523 assert(Op0.getValueType().is64BitVector() && 7524 Op1.getValueType().is64BitVector() && 7525 "unexpected types for extended operands to VMULL"); 7526 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7527 } 7528 7529 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7530 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7531 // vmull q0, d4, d6 7532 // vmlal q0, d5, d6 7533 // is faster than 7534 // vaddl q0, d4, d5 7535 // vmovl q1, d6 7536 // vmul q0, q0, q1 7537 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7538 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7539 EVT Op1VT = Op1.getValueType(); 7540 return DAG.getNode(N0->getOpcode(), DL, VT, 7541 DAG.getNode(NewOpc, DL, VT, 7542 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7543 DAG.getNode(NewOpc, DL, VT, 7544 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7545 } 7546 7547 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7548 SelectionDAG &DAG) { 7549 // TODO: Should this propagate fast-math-flags? 7550 7551 // Convert to float 7552 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7553 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7554 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7555 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7556 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7557 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7558 // Get reciprocal estimate. 7559 // float4 recip = vrecpeq_f32(yf); 7560 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7561 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7562 Y); 7563 // Because char has a smaller range than uchar, we can actually get away 7564 // without any newton steps. This requires that we use a weird bias 7565 // of 0xb000, however (again, this has been exhaustively tested). 7566 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7567 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7568 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7569 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7570 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7571 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7572 // Convert back to short. 7573 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7574 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7575 return X; 7576 } 7577 7578 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7579 SelectionDAG &DAG) { 7580 // TODO: Should this propagate fast-math-flags? 7581 7582 SDValue N2; 7583 // Convert to float. 7584 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7585 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7586 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7587 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7588 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7589 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7590 7591 // Use reciprocal estimate and one refinement step. 7592 // float4 recip = vrecpeq_f32(yf); 7593 // recip *= vrecpsq_f32(yf, recip); 7594 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7595 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7596 N1); 7597 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7598 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7599 N1, N2); 7600 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7601 // Because short has a smaller range than ushort, we can actually get away 7602 // with only a single newton step. This requires that we use a weird bias 7603 // of 89, however (again, this has been exhaustively tested). 7604 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7605 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7606 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7607 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7608 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7609 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7610 // Convert back to integer and return. 7611 // return vmovn_s32(vcvt_s32_f32(result)); 7612 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7613 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7614 return N0; 7615 } 7616 7617 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7618 EVT VT = Op.getValueType(); 7619 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7620 "unexpected type for custom-lowering ISD::SDIV"); 7621 7622 SDLoc dl(Op); 7623 SDValue N0 = Op.getOperand(0); 7624 SDValue N1 = Op.getOperand(1); 7625 SDValue N2, N3; 7626 7627 if (VT == MVT::v8i8) { 7628 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7629 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7630 7631 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7632 DAG.getIntPtrConstant(4, dl)); 7633 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7634 DAG.getIntPtrConstant(4, dl)); 7635 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7636 DAG.getIntPtrConstant(0, dl)); 7637 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7638 DAG.getIntPtrConstant(0, dl)); 7639 7640 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7641 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7642 7643 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7644 N0 = LowerCONCAT_VECTORS(N0, DAG); 7645 7646 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7647 return N0; 7648 } 7649 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7650 } 7651 7652 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7653 // TODO: Should this propagate fast-math-flags? 7654 EVT VT = Op.getValueType(); 7655 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7656 "unexpected type for custom-lowering ISD::UDIV"); 7657 7658 SDLoc dl(Op); 7659 SDValue N0 = Op.getOperand(0); 7660 SDValue N1 = Op.getOperand(1); 7661 SDValue N2, N3; 7662 7663 if (VT == MVT::v8i8) { 7664 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7665 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7666 7667 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7668 DAG.getIntPtrConstant(4, dl)); 7669 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7670 DAG.getIntPtrConstant(4, dl)); 7671 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7672 DAG.getIntPtrConstant(0, dl)); 7673 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7674 DAG.getIntPtrConstant(0, dl)); 7675 7676 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7677 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7678 7679 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7680 N0 = LowerCONCAT_VECTORS(N0, DAG); 7681 7682 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7683 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7684 MVT::i32), 7685 N0); 7686 return N0; 7687 } 7688 7689 // v4i16 sdiv ... Convert to float. 7690 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7691 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7692 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7693 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7694 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7695 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7696 7697 // Use reciprocal estimate and two refinement steps. 7698 // float4 recip = vrecpeq_f32(yf); 7699 // recip *= vrecpsq_f32(yf, recip); 7700 // recip *= vrecpsq_f32(yf, recip); 7701 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7702 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7703 BN1); 7704 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7705 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7706 BN1, N2); 7707 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7708 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7709 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7710 BN1, N2); 7711 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7712 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7713 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7714 // and that it will never cause us to return an answer too large). 7715 // float4 result = as_float4(as_int4(xf*recip) + 2); 7716 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7717 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7718 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7719 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7720 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7721 // Convert back to integer and return. 7722 // return vmovn_u32(vcvt_s32_f32(result)); 7723 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7724 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7725 return N0; 7726 } 7727 7728 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 7729 SDNode *N = Op.getNode(); 7730 EVT VT = N->getValueType(0); 7731 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7732 7733 SDValue Carry = Op.getOperand(2); 7734 7735 SDLoc DL(Op); 7736 7737 SDValue Result; 7738 if (Op.getOpcode() == ISD::ADDCARRY) { 7739 // This converts the boolean value carry into the carry flag. 7740 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7741 7742 // Do the addition proper using the carry flag we wanted. 7743 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 7744 Op.getOperand(1), Carry); 7745 7746 // Now convert the carry flag into a boolean value. 7747 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7748 } else { 7749 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 7750 // have to invert the carry first. 7751 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7752 DAG.getConstant(1, DL, MVT::i32), Carry); 7753 // This converts the boolean value carry into the carry flag. 7754 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7755 7756 // Do the subtraction proper using the carry flag we wanted. 7757 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 7758 Op.getOperand(1), Carry); 7759 7760 // Now convert the carry flag into a boolean value. 7761 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7762 // But the carry returned by ARMISD::SUBE is not a borrow as expected 7763 // by ISD::SUBCARRY, so compute 1 - C. 7764 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7765 DAG.getConstant(1, DL, MVT::i32), Carry); 7766 } 7767 7768 // Return both values. 7769 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 7770 } 7771 7772 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7773 assert(Subtarget->isTargetDarwin()); 7774 7775 // For iOS, we want to call an alternative entry point: __sincos_stret, 7776 // return values are passed via sret. 7777 SDLoc dl(Op); 7778 SDValue Arg = Op.getOperand(0); 7779 EVT ArgVT = Arg.getValueType(); 7780 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7781 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7782 7783 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7784 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7785 7786 // Pair of floats / doubles used to pass the result. 7787 Type *RetTy = StructType::get(ArgTy, ArgTy); 7788 auto &DL = DAG.getDataLayout(); 7789 7790 ArgListTy Args; 7791 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7792 SDValue SRet; 7793 if (ShouldUseSRet) { 7794 // Create stack object for sret. 7795 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7796 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7797 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7798 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7799 7800 ArgListEntry Entry; 7801 Entry.Node = SRet; 7802 Entry.Ty = RetTy->getPointerTo(); 7803 Entry.IsSExt = false; 7804 Entry.IsZExt = false; 7805 Entry.IsSRet = true; 7806 Args.push_back(Entry); 7807 RetTy = Type::getVoidTy(*DAG.getContext()); 7808 } 7809 7810 ArgListEntry Entry; 7811 Entry.Node = Arg; 7812 Entry.Ty = ArgTy; 7813 Entry.IsSExt = false; 7814 Entry.IsZExt = false; 7815 Args.push_back(Entry); 7816 7817 RTLIB::Libcall LC = 7818 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 7819 const char *LibcallName = getLibcallName(LC); 7820 CallingConv::ID CC = getLibcallCallingConv(LC); 7821 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7822 7823 TargetLowering::CallLoweringInfo CLI(DAG); 7824 CLI.setDebugLoc(dl) 7825 .setChain(DAG.getEntryNode()) 7826 .setCallee(CC, RetTy, Callee, std::move(Args)) 7827 .setDiscardResult(ShouldUseSRet); 7828 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7829 7830 if (!ShouldUseSRet) 7831 return CallResult.first; 7832 7833 SDValue LoadSin = 7834 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7835 7836 // Address of cos field. 7837 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7838 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7839 SDValue LoadCos = 7840 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7841 7842 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7843 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7844 LoadSin.getValue(0), LoadCos.getValue(0)); 7845 } 7846 7847 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7848 bool Signed, 7849 SDValue &Chain) const { 7850 EVT VT = Op.getValueType(); 7851 assert((VT == MVT::i32 || VT == MVT::i64) && 7852 "unexpected type for custom lowering DIV"); 7853 SDLoc dl(Op); 7854 7855 const auto &DL = DAG.getDataLayout(); 7856 const auto &TLI = DAG.getTargetLoweringInfo(); 7857 7858 const char *Name = nullptr; 7859 if (Signed) 7860 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7861 else 7862 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7863 7864 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7865 7866 ARMTargetLowering::ArgListTy Args; 7867 7868 for (auto AI : {1, 0}) { 7869 ArgListEntry Arg; 7870 Arg.Node = Op.getOperand(AI); 7871 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7872 Args.push_back(Arg); 7873 } 7874 7875 CallLoweringInfo CLI(DAG); 7876 CLI.setDebugLoc(dl) 7877 .setChain(Chain) 7878 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7879 ES, std::move(Args)); 7880 7881 return LowerCallTo(CLI).first; 7882 } 7883 7884 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7885 bool Signed) const { 7886 assert(Op.getValueType() == MVT::i32 && 7887 "unexpected type for custom lowering DIV"); 7888 SDLoc dl(Op); 7889 7890 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7891 DAG.getEntryNode(), Op.getOperand(1)); 7892 7893 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7894 } 7895 7896 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7897 SDLoc DL(N); 7898 SDValue Op = N->getOperand(1); 7899 if (N->getValueType(0) == MVT::i32) 7900 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7901 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7902 DAG.getConstant(0, DL, MVT::i32)); 7903 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7904 DAG.getConstant(1, DL, MVT::i32)); 7905 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7906 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7907 } 7908 7909 void ARMTargetLowering::ExpandDIV_Windows( 7910 SDValue Op, SelectionDAG &DAG, bool Signed, 7911 SmallVectorImpl<SDValue> &Results) const { 7912 const auto &DL = DAG.getDataLayout(); 7913 const auto &TLI = DAG.getTargetLoweringInfo(); 7914 7915 assert(Op.getValueType() == MVT::i64 && 7916 "unexpected type for custom lowering DIV"); 7917 SDLoc dl(Op); 7918 7919 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7920 7921 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7922 7923 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7924 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7925 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7926 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7927 7928 Results.push_back(Lower); 7929 Results.push_back(Upper); 7930 } 7931 7932 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7933 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7934 // Acquire/Release load/store is not legal for targets without a dmb or 7935 // equivalent available. 7936 return SDValue(); 7937 7938 // Monotonic load/store is legal for all targets. 7939 return Op; 7940 } 7941 7942 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7943 SmallVectorImpl<SDValue> &Results, 7944 SelectionDAG &DAG, 7945 const ARMSubtarget *Subtarget) { 7946 SDLoc DL(N); 7947 // Under Power Management extensions, the cycle-count is: 7948 // mrc p15, #0, <Rt>, c9, c13, #0 7949 SDValue Ops[] = { N->getOperand(0), // Chain 7950 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7951 DAG.getConstant(15, DL, MVT::i32), 7952 DAG.getConstant(0, DL, MVT::i32), 7953 DAG.getConstant(9, DL, MVT::i32), 7954 DAG.getConstant(13, DL, MVT::i32), 7955 DAG.getConstant(0, DL, MVT::i32) 7956 }; 7957 7958 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7959 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7960 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7961 DAG.getConstant(0, DL, MVT::i32))); 7962 Results.push_back(Cycles32.getValue(1)); 7963 } 7964 7965 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7966 SDLoc dl(V.getNode()); 7967 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7968 SDValue VHi = DAG.getAnyExtOrTrunc( 7969 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7970 dl, MVT::i32); 7971 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7972 if (isBigEndian) 7973 std::swap (VLo, VHi); 7974 SDValue RegClass = 7975 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7976 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7977 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7978 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7979 return SDValue( 7980 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7981 } 7982 7983 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7984 SmallVectorImpl<SDValue> & Results, 7985 SelectionDAG &DAG) { 7986 assert(N->getValueType(0) == MVT::i64 && 7987 "AtomicCmpSwap on types less than 64 should be legal"); 7988 SDValue Ops[] = {N->getOperand(1), 7989 createGPRPairNode(DAG, N->getOperand(2)), 7990 createGPRPairNode(DAG, N->getOperand(3)), 7991 N->getOperand(0)}; 7992 SDNode *CmpSwap = DAG.getMachineNode( 7993 ARM::CMP_SWAP_64, SDLoc(N), 7994 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7995 7996 MachineFunction &MF = DAG.getMachineFunction(); 7997 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7998 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7999 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 8000 8001 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 8002 8003 Results.push_back( 8004 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 8005 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8006 Results.push_back( 8007 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 8008 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 8009 Results.push_back(SDValue(CmpSwap, 2)); 8010 } 8011 8012 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 8013 SelectionDAG &DAG) { 8014 const auto &TLI = DAG.getTargetLoweringInfo(); 8015 8016 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 8017 "Custom lowering is MSVCRT specific!"); 8018 8019 SDLoc dl(Op); 8020 SDValue Val = Op.getOperand(0); 8021 MVT Ty = Val->getSimpleValueType(0); 8022 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 8023 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 8024 TLI.getPointerTy(DAG.getDataLayout())); 8025 8026 TargetLowering::ArgListTy Args; 8027 TargetLowering::ArgListEntry Entry; 8028 8029 Entry.Node = Val; 8030 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8031 Entry.IsZExt = true; 8032 Args.push_back(Entry); 8033 8034 Entry.Node = Exponent; 8035 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 8036 Entry.IsZExt = true; 8037 Args.push_back(Entry); 8038 8039 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 8040 8041 // In the in-chain to the call is the entry node If we are emitting a 8042 // tailcall, the chain will be mutated if the node has a non-entry input 8043 // chain. 8044 SDValue InChain = DAG.getEntryNode(); 8045 SDValue TCChain = InChain; 8046 8047 const Function &F = DAG.getMachineFunction().getFunction(); 8048 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8049 F.getReturnType() == LCRTy; 8050 if (IsTC) 8051 InChain = TCChain; 8052 8053 TargetLowering::CallLoweringInfo CLI(DAG); 8054 CLI.setDebugLoc(dl) 8055 .setChain(InChain) 8056 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8057 .setTailCall(IsTC); 8058 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8059 8060 // Return the chain (the DAG root) if it is a tail call 8061 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8062 } 8063 8064 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8065 LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8066 switch (Op.getOpcode()) { 8067 default: llvm_unreachable("Don't know how to custom lower this!"); 8068 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8069 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8070 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8071 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8072 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8073 case ISD::SELECT: return LowerSELECT(Op, DAG); 8074 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8075 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8076 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8077 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8078 case ISD::VASTART: return LowerVASTART(Op, DAG); 8079 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8080 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8081 case ISD::SINT_TO_FP: 8082 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8083 case ISD::FP_TO_SINT: 8084 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8085 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8086 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8087 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8088 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8089 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8090 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8091 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8092 Subtarget); 8093 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8094 case ISD::SHL: 8095 case ISD::SRL: 8096 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8097 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8098 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8099 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8100 case ISD::SRL_PARTS: 8101 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8102 case ISD::CTTZ: 8103 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8104 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8105 case ISD::SETCC: return LowerVSETCC(Op, DAG); 8106 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG); 8107 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8108 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8109 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 8110 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8111 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 8112 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 8113 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8114 case ISD::MUL: return LowerMUL(Op, DAG); 8115 case ISD::SDIV: 8116 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8117 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8118 return LowerSDIV(Op, DAG); 8119 case ISD::UDIV: 8120 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8121 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8122 return LowerUDIV(Op, DAG); 8123 case ISD::ADDCARRY: 8124 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8125 case ISD::SADDO: 8126 case ISD::SSUBO: 8127 return LowerSignedALUO(Op, DAG); 8128 case ISD::UADDO: 8129 case ISD::USUBO: 8130 return LowerUnsignedALUO(Op, DAG); 8131 case ISD::ATOMIC_LOAD: 8132 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8133 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8134 case ISD::SDIVREM: 8135 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8136 case ISD::DYNAMIC_STACKALLOC: 8137 if (Subtarget->isTargetWindows()) 8138 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8139 llvm_unreachable("Don't know how to custom lower this!"); 8140 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8141 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8142 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8143 case ARMISD::WIN__DBZCHK: return SDValue(); 8144 } 8145 } 8146 8147 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8148 SelectionDAG &DAG) { 8149 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8150 unsigned Opc = 0; 8151 if (IntNo == Intrinsic::arm_smlald) 8152 Opc = ARMISD::SMLALD; 8153 else if (IntNo == Intrinsic::arm_smlaldx) 8154 Opc = ARMISD::SMLALDX; 8155 else if (IntNo == Intrinsic::arm_smlsld) 8156 Opc = ARMISD::SMLSLD; 8157 else if (IntNo == Intrinsic::arm_smlsldx) 8158 Opc = ARMISD::SMLSLDX; 8159 else 8160 return; 8161 8162 SDLoc dl(N); 8163 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8164 N->getOperand(3), 8165 DAG.getConstant(0, dl, MVT::i32)); 8166 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8167 N->getOperand(3), 8168 DAG.getConstant(1, dl, MVT::i32)); 8169 8170 SDValue LongMul = DAG.getNode(Opc, dl, 8171 DAG.getVTList(MVT::i32, MVT::i32), 8172 N->getOperand(1), N->getOperand(2), 8173 Lo, Hi); 8174 Results.push_back(LongMul.getValue(0)); 8175 Results.push_back(LongMul.getValue(1)); 8176 } 8177 8178 /// ReplaceNodeResults - Replace the results of node with an illegal result 8179 /// type with new values built out of custom code. 8180 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8181 SmallVectorImpl<SDValue> &Results, 8182 SelectionDAG &DAG) const { 8183 SDValue Res; 8184 switch (N->getOpcode()) { 8185 default: 8186 llvm_unreachable("Don't know how to custom expand this!"); 8187 case ISD::READ_REGISTER: 8188 ExpandREAD_REGISTER(N, Results, DAG); 8189 break; 8190 case ISD::BITCAST: 8191 Res = ExpandBITCAST(N, DAG, Subtarget); 8192 break; 8193 case ISD::SRL: 8194 case ISD::SRA: 8195 Res = Expand64BitShift(N, DAG, Subtarget); 8196 break; 8197 case ISD::SREM: 8198 case ISD::UREM: 8199 Res = LowerREM(N, DAG); 8200 break; 8201 case ISD::SDIVREM: 8202 case ISD::UDIVREM: 8203 Res = LowerDivRem(SDValue(N, 0), DAG); 8204 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 8205 Results.push_back(Res.getValue(0)); 8206 Results.push_back(Res.getValue(1)); 8207 return; 8208 case ISD::READCYCLECOUNTER: 8209 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8210 return; 8211 case ISD::UDIV: 8212 case ISD::SDIV: 8213 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8214 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8215 Results); 8216 case ISD::ATOMIC_CMP_SWAP: 8217 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8218 return; 8219 case ISD::INTRINSIC_WO_CHAIN: 8220 return ReplaceLongIntrinsic(N, Results, DAG); 8221 } 8222 if (Res.getNode()) 8223 Results.push_back(Res); 8224 } 8225 8226 //===----------------------------------------------------------------------===// 8227 // ARM Scheduler Hooks 8228 //===----------------------------------------------------------------------===// 8229 8230 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8231 /// registers the function context. 8232 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8233 MachineBasicBlock *MBB, 8234 MachineBasicBlock *DispatchBB, 8235 int FI) const { 8236 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8237 "ROPI/RWPI not currently supported with SjLj"); 8238 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8239 DebugLoc dl = MI.getDebugLoc(); 8240 MachineFunction *MF = MBB->getParent(); 8241 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8242 MachineConstantPool *MCP = MF->getConstantPool(); 8243 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8244 const Function &F = MF->getFunction(); 8245 8246 bool isThumb = Subtarget->isThumb(); 8247 bool isThumb2 = Subtarget->isThumb2(); 8248 8249 unsigned PCLabelId = AFI->createPICLabelUId(); 8250 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 8251 ARMConstantPoolValue *CPV = 8252 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 8253 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 8254 8255 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 8256 : &ARM::GPRRegClass; 8257 8258 // Grab constant pool and fixed stack memory operands. 8259 MachineMemOperand *CPMMO = 8260 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 8261 MachineMemOperand::MOLoad, 4, 4); 8262 8263 MachineMemOperand *FIMMOSt = 8264 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 8265 MachineMemOperand::MOStore, 4, 4); 8266 8267 // Load the address of the dispatch MBB into the jump buffer. 8268 if (isThumb2) { 8269 // Incoming value: jbuf 8270 // ldr.n r5, LCPI1_1 8271 // orr r5, r5, #1 8272 // add r5, pc 8273 // str r5, [$jbuf, #+4] ; &jbuf[1] 8274 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8275 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 8276 .addConstantPoolIndex(CPI) 8277 .addMemOperand(CPMMO) 8278 .add(predOps(ARMCC::AL)); 8279 // Set the low bit because of thumb mode. 8280 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8281 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 8282 .addReg(NewVReg1, RegState::Kill) 8283 .addImm(0x01) 8284 .add(predOps(ARMCC::AL)) 8285 .add(condCodeOp()); 8286 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8287 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8288 .addReg(NewVReg2, RegState::Kill) 8289 .addImm(PCLabelId); 8290 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8291 .addReg(NewVReg3, RegState::Kill) 8292 .addFrameIndex(FI) 8293 .addImm(36) // &jbuf[1] :: pc 8294 .addMemOperand(FIMMOSt) 8295 .add(predOps(ARMCC::AL)); 8296 } else if (isThumb) { 8297 // Incoming value: jbuf 8298 // ldr.n r1, LCPI1_4 8299 // add r1, pc 8300 // mov r2, #1 8301 // orrs r1, r2 8302 // add r2, $jbuf, #+4 ; &jbuf[1] 8303 // str r1, [r2] 8304 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8305 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8306 .addConstantPoolIndex(CPI) 8307 .addMemOperand(CPMMO) 8308 .add(predOps(ARMCC::AL)); 8309 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8310 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8311 .addReg(NewVReg1, RegState::Kill) 8312 .addImm(PCLabelId); 8313 // Set the low bit because of thumb mode. 8314 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8315 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8316 .addReg(ARM::CPSR, RegState::Define) 8317 .addImm(1) 8318 .add(predOps(ARMCC::AL)); 8319 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8320 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8321 .addReg(ARM::CPSR, RegState::Define) 8322 .addReg(NewVReg2, RegState::Kill) 8323 .addReg(NewVReg3, RegState::Kill) 8324 .add(predOps(ARMCC::AL)); 8325 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8326 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8327 .addFrameIndex(FI) 8328 .addImm(36); // &jbuf[1] :: pc 8329 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8330 .addReg(NewVReg4, RegState::Kill) 8331 .addReg(NewVReg5, RegState::Kill) 8332 .addImm(0) 8333 .addMemOperand(FIMMOSt) 8334 .add(predOps(ARMCC::AL)); 8335 } else { 8336 // Incoming value: jbuf 8337 // ldr r1, LCPI1_1 8338 // add r1, pc, r1 8339 // str r1, [$jbuf, #+4] ; &jbuf[1] 8340 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8341 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8342 .addConstantPoolIndex(CPI) 8343 .addImm(0) 8344 .addMemOperand(CPMMO) 8345 .add(predOps(ARMCC::AL)); 8346 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8347 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8348 .addReg(NewVReg1, RegState::Kill) 8349 .addImm(PCLabelId) 8350 .add(predOps(ARMCC::AL)); 8351 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8352 .addReg(NewVReg2, RegState::Kill) 8353 .addFrameIndex(FI) 8354 .addImm(36) // &jbuf[1] :: pc 8355 .addMemOperand(FIMMOSt) 8356 .add(predOps(ARMCC::AL)); 8357 } 8358 } 8359 8360 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8361 MachineBasicBlock *MBB) const { 8362 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8363 DebugLoc dl = MI.getDebugLoc(); 8364 MachineFunction *MF = MBB->getParent(); 8365 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8366 MachineFrameInfo &MFI = MF->getFrameInfo(); 8367 int FI = MFI.getFunctionContextIndex(); 8368 8369 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8370 : &ARM::GPRnopcRegClass; 8371 8372 // Get a mapping of the call site numbers to all of the landing pads they're 8373 // associated with. 8374 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8375 unsigned MaxCSNum = 0; 8376 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8377 ++BB) { 8378 if (!BB->isEHPad()) continue; 8379 8380 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8381 // pad. 8382 for (MachineBasicBlock::iterator 8383 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8384 if (!II->isEHLabel()) continue; 8385 8386 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8387 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8388 8389 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8390 for (SmallVectorImpl<unsigned>::iterator 8391 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8392 CSI != CSE; ++CSI) { 8393 CallSiteNumToLPad[*CSI].push_back(&*BB); 8394 MaxCSNum = std::max(MaxCSNum, *CSI); 8395 } 8396 break; 8397 } 8398 } 8399 8400 // Get an ordered list of the machine basic blocks for the jump table. 8401 std::vector<MachineBasicBlock*> LPadList; 8402 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8403 LPadList.reserve(CallSiteNumToLPad.size()); 8404 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8405 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8406 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8407 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8408 LPadList.push_back(*II); 8409 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8410 } 8411 } 8412 8413 assert(!LPadList.empty() && 8414 "No landing pad destinations for the dispatch jump table!"); 8415 8416 // Create the jump table and associated information. 8417 MachineJumpTableInfo *JTI = 8418 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8419 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8420 8421 // Create the MBBs for the dispatch code. 8422 8423 // Shove the dispatch's address into the return slot in the function context. 8424 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8425 DispatchBB->setIsEHPad(); 8426 8427 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8428 unsigned trap_opcode; 8429 if (Subtarget->isThumb()) 8430 trap_opcode = ARM::tTRAP; 8431 else 8432 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8433 8434 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8435 DispatchBB->addSuccessor(TrapBB); 8436 8437 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8438 DispatchBB->addSuccessor(DispContBB); 8439 8440 // Insert and MBBs. 8441 MF->insert(MF->end(), DispatchBB); 8442 MF->insert(MF->end(), DispContBB); 8443 MF->insert(MF->end(), TrapBB); 8444 8445 // Insert code into the entry block that creates and registers the function 8446 // context. 8447 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8448 8449 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8450 MachinePointerInfo::getFixedStack(*MF, FI), 8451 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8452 8453 MachineInstrBuilder MIB; 8454 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8455 8456 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8457 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8458 8459 // Add a register mask with no preserved registers. This results in all 8460 // registers being marked as clobbered. This can't work if the dispatch block 8461 // is in a Thumb1 function and is linked with ARM code which uses the FP 8462 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8463 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8464 8465 bool IsPositionIndependent = isPositionIndependent(); 8466 unsigned NumLPads = LPadList.size(); 8467 if (Subtarget->isThumb2()) { 8468 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8469 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8470 .addFrameIndex(FI) 8471 .addImm(4) 8472 .addMemOperand(FIMMOLd) 8473 .add(predOps(ARMCC::AL)); 8474 8475 if (NumLPads < 256) { 8476 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8477 .addReg(NewVReg1) 8478 .addImm(LPadList.size()) 8479 .add(predOps(ARMCC::AL)); 8480 } else { 8481 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8482 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8483 .addImm(NumLPads & 0xFFFF) 8484 .add(predOps(ARMCC::AL)); 8485 8486 unsigned VReg2 = VReg1; 8487 if ((NumLPads & 0xFFFF0000) != 0) { 8488 VReg2 = MRI->createVirtualRegister(TRC); 8489 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8490 .addReg(VReg1) 8491 .addImm(NumLPads >> 16) 8492 .add(predOps(ARMCC::AL)); 8493 } 8494 8495 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8496 .addReg(NewVReg1) 8497 .addReg(VReg2) 8498 .add(predOps(ARMCC::AL)); 8499 } 8500 8501 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8502 .addMBB(TrapBB) 8503 .addImm(ARMCC::HI) 8504 .addReg(ARM::CPSR); 8505 8506 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8507 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8508 .addJumpTableIndex(MJTI) 8509 .add(predOps(ARMCC::AL)); 8510 8511 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8512 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8513 .addReg(NewVReg3, RegState::Kill) 8514 .addReg(NewVReg1) 8515 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8516 .add(predOps(ARMCC::AL)) 8517 .add(condCodeOp()); 8518 8519 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8520 .addReg(NewVReg4, RegState::Kill) 8521 .addReg(NewVReg1) 8522 .addJumpTableIndex(MJTI); 8523 } else if (Subtarget->isThumb()) { 8524 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8525 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8526 .addFrameIndex(FI) 8527 .addImm(1) 8528 .addMemOperand(FIMMOLd) 8529 .add(predOps(ARMCC::AL)); 8530 8531 if (NumLPads < 256) { 8532 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8533 .addReg(NewVReg1) 8534 .addImm(NumLPads) 8535 .add(predOps(ARMCC::AL)); 8536 } else { 8537 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8538 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8539 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8540 8541 // MachineConstantPool wants an explicit alignment. 8542 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8543 if (Align == 0) 8544 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8545 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8546 8547 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8548 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8549 .addReg(VReg1, RegState::Define) 8550 .addConstantPoolIndex(Idx) 8551 .add(predOps(ARMCC::AL)); 8552 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8553 .addReg(NewVReg1) 8554 .addReg(VReg1) 8555 .add(predOps(ARMCC::AL)); 8556 } 8557 8558 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8559 .addMBB(TrapBB) 8560 .addImm(ARMCC::HI) 8561 .addReg(ARM::CPSR); 8562 8563 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8564 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8565 .addReg(ARM::CPSR, RegState::Define) 8566 .addReg(NewVReg1) 8567 .addImm(2) 8568 .add(predOps(ARMCC::AL)); 8569 8570 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8571 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8572 .addJumpTableIndex(MJTI) 8573 .add(predOps(ARMCC::AL)); 8574 8575 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8576 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8577 .addReg(ARM::CPSR, RegState::Define) 8578 .addReg(NewVReg2, RegState::Kill) 8579 .addReg(NewVReg3) 8580 .add(predOps(ARMCC::AL)); 8581 8582 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8583 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8584 8585 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8586 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8587 .addReg(NewVReg4, RegState::Kill) 8588 .addImm(0) 8589 .addMemOperand(JTMMOLd) 8590 .add(predOps(ARMCC::AL)); 8591 8592 unsigned NewVReg6 = NewVReg5; 8593 if (IsPositionIndependent) { 8594 NewVReg6 = MRI->createVirtualRegister(TRC); 8595 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8596 .addReg(ARM::CPSR, RegState::Define) 8597 .addReg(NewVReg5, RegState::Kill) 8598 .addReg(NewVReg3) 8599 .add(predOps(ARMCC::AL)); 8600 } 8601 8602 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8603 .addReg(NewVReg6, RegState::Kill) 8604 .addJumpTableIndex(MJTI); 8605 } else { 8606 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8607 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8608 .addFrameIndex(FI) 8609 .addImm(4) 8610 .addMemOperand(FIMMOLd) 8611 .add(predOps(ARMCC::AL)); 8612 8613 if (NumLPads < 256) { 8614 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8615 .addReg(NewVReg1) 8616 .addImm(NumLPads) 8617 .add(predOps(ARMCC::AL)); 8618 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8619 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8620 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8621 .addImm(NumLPads & 0xFFFF) 8622 .add(predOps(ARMCC::AL)); 8623 8624 unsigned VReg2 = VReg1; 8625 if ((NumLPads & 0xFFFF0000) != 0) { 8626 VReg2 = MRI->createVirtualRegister(TRC); 8627 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8628 .addReg(VReg1) 8629 .addImm(NumLPads >> 16) 8630 .add(predOps(ARMCC::AL)); 8631 } 8632 8633 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8634 .addReg(NewVReg1) 8635 .addReg(VReg2) 8636 .add(predOps(ARMCC::AL)); 8637 } else { 8638 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8639 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8640 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8641 8642 // MachineConstantPool wants an explicit alignment. 8643 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8644 if (Align == 0) 8645 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8646 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8647 8648 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8649 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8650 .addReg(VReg1, RegState::Define) 8651 .addConstantPoolIndex(Idx) 8652 .addImm(0) 8653 .add(predOps(ARMCC::AL)); 8654 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8655 .addReg(NewVReg1) 8656 .addReg(VReg1, RegState::Kill) 8657 .add(predOps(ARMCC::AL)); 8658 } 8659 8660 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8661 .addMBB(TrapBB) 8662 .addImm(ARMCC::HI) 8663 .addReg(ARM::CPSR); 8664 8665 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8666 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8667 .addReg(NewVReg1) 8668 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8669 .add(predOps(ARMCC::AL)) 8670 .add(condCodeOp()); 8671 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8672 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8673 .addJumpTableIndex(MJTI) 8674 .add(predOps(ARMCC::AL)); 8675 8676 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8677 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8678 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8679 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8680 .addReg(NewVReg3, RegState::Kill) 8681 .addReg(NewVReg4) 8682 .addImm(0) 8683 .addMemOperand(JTMMOLd) 8684 .add(predOps(ARMCC::AL)); 8685 8686 if (IsPositionIndependent) { 8687 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8688 .addReg(NewVReg5, RegState::Kill) 8689 .addReg(NewVReg4) 8690 .addJumpTableIndex(MJTI); 8691 } else { 8692 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8693 .addReg(NewVReg5, RegState::Kill) 8694 .addJumpTableIndex(MJTI); 8695 } 8696 } 8697 8698 // Add the jump table entries as successors to the MBB. 8699 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8700 for (std::vector<MachineBasicBlock*>::iterator 8701 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8702 MachineBasicBlock *CurMBB = *I; 8703 if (SeenMBBs.insert(CurMBB).second) 8704 DispContBB->addSuccessor(CurMBB); 8705 } 8706 8707 // N.B. the order the invoke BBs are processed in doesn't matter here. 8708 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8709 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8710 for (MachineBasicBlock *BB : InvokeBBs) { 8711 8712 // Remove the landing pad successor from the invoke block and replace it 8713 // with the new dispatch block. 8714 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8715 BB->succ_end()); 8716 while (!Successors.empty()) { 8717 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8718 if (SMBB->isEHPad()) { 8719 BB->removeSuccessor(SMBB); 8720 MBBLPads.push_back(SMBB); 8721 } 8722 } 8723 8724 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8725 BB->normalizeSuccProbs(); 8726 8727 // Find the invoke call and mark all of the callee-saved registers as 8728 // 'implicit defined' so that they're spilled. This prevents code from 8729 // moving instructions to before the EH block, where they will never be 8730 // executed. 8731 for (MachineBasicBlock::reverse_iterator 8732 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8733 if (!II->isCall()) continue; 8734 8735 DenseMap<unsigned, bool> DefRegs; 8736 for (MachineInstr::mop_iterator 8737 OI = II->operands_begin(), OE = II->operands_end(); 8738 OI != OE; ++OI) { 8739 if (!OI->isReg()) continue; 8740 DefRegs[OI->getReg()] = true; 8741 } 8742 8743 MachineInstrBuilder MIB(*MF, &*II); 8744 8745 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8746 unsigned Reg = SavedRegs[i]; 8747 if (Subtarget->isThumb2() && 8748 !ARM::tGPRRegClass.contains(Reg) && 8749 !ARM::hGPRRegClass.contains(Reg)) 8750 continue; 8751 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8752 continue; 8753 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8754 continue; 8755 if (!DefRegs[Reg]) 8756 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8757 } 8758 8759 break; 8760 } 8761 } 8762 8763 // Mark all former landing pads as non-landing pads. The dispatch is the only 8764 // landing pad now. 8765 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8766 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8767 (*I)->setIsEHPad(false); 8768 8769 // The instruction is gone now. 8770 MI.eraseFromParent(); 8771 } 8772 8773 static 8774 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8775 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8776 E = MBB->succ_end(); I != E; ++I) 8777 if (*I != Succ) 8778 return *I; 8779 llvm_unreachable("Expecting a BB with two successors!"); 8780 } 8781 8782 /// Return the load opcode for a given load size. If load size >= 8, 8783 /// neon opcode will be returned. 8784 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8785 if (LdSize >= 8) 8786 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8787 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8788 if (IsThumb1) 8789 return LdSize == 4 ? ARM::tLDRi 8790 : LdSize == 2 ? ARM::tLDRHi 8791 : LdSize == 1 ? ARM::tLDRBi : 0; 8792 if (IsThumb2) 8793 return LdSize == 4 ? ARM::t2LDR_POST 8794 : LdSize == 2 ? ARM::t2LDRH_POST 8795 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8796 return LdSize == 4 ? ARM::LDR_POST_IMM 8797 : LdSize == 2 ? ARM::LDRH_POST 8798 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8799 } 8800 8801 /// Return the store opcode for a given store size. If store size >= 8, 8802 /// neon opcode will be returned. 8803 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8804 if (StSize >= 8) 8805 return StSize == 16 ? ARM::VST1q32wb_fixed 8806 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8807 if (IsThumb1) 8808 return StSize == 4 ? ARM::tSTRi 8809 : StSize == 2 ? ARM::tSTRHi 8810 : StSize == 1 ? ARM::tSTRBi : 0; 8811 if (IsThumb2) 8812 return StSize == 4 ? ARM::t2STR_POST 8813 : StSize == 2 ? ARM::t2STRH_POST 8814 : StSize == 1 ? ARM::t2STRB_POST : 0; 8815 return StSize == 4 ? ARM::STR_POST_IMM 8816 : StSize == 2 ? ARM::STRH_POST 8817 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8818 } 8819 8820 /// Emit a post-increment load operation with given size. The instructions 8821 /// will be added to BB at Pos. 8822 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8823 const TargetInstrInfo *TII, const DebugLoc &dl, 8824 unsigned LdSize, unsigned Data, unsigned AddrIn, 8825 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8826 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8827 assert(LdOpc != 0 && "Should have a load opcode"); 8828 if (LdSize >= 8) { 8829 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8830 .addReg(AddrOut, RegState::Define) 8831 .addReg(AddrIn) 8832 .addImm(0) 8833 .add(predOps(ARMCC::AL)); 8834 } else if (IsThumb1) { 8835 // load + update AddrIn 8836 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8837 .addReg(AddrIn) 8838 .addImm(0) 8839 .add(predOps(ARMCC::AL)); 8840 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8841 .add(t1CondCodeOp()) 8842 .addReg(AddrIn) 8843 .addImm(LdSize) 8844 .add(predOps(ARMCC::AL)); 8845 } else if (IsThumb2) { 8846 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8847 .addReg(AddrOut, RegState::Define) 8848 .addReg(AddrIn) 8849 .addImm(LdSize) 8850 .add(predOps(ARMCC::AL)); 8851 } else { // arm 8852 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8853 .addReg(AddrOut, RegState::Define) 8854 .addReg(AddrIn) 8855 .addReg(0) 8856 .addImm(LdSize) 8857 .add(predOps(ARMCC::AL)); 8858 } 8859 } 8860 8861 /// Emit a post-increment store operation with given size. The instructions 8862 /// will be added to BB at Pos. 8863 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8864 const TargetInstrInfo *TII, const DebugLoc &dl, 8865 unsigned StSize, unsigned Data, unsigned AddrIn, 8866 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8867 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8868 assert(StOpc != 0 && "Should have a store opcode"); 8869 if (StSize >= 8) { 8870 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8871 .addReg(AddrIn) 8872 .addImm(0) 8873 .addReg(Data) 8874 .add(predOps(ARMCC::AL)); 8875 } else if (IsThumb1) { 8876 // store + update AddrIn 8877 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8878 .addReg(Data) 8879 .addReg(AddrIn) 8880 .addImm(0) 8881 .add(predOps(ARMCC::AL)); 8882 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8883 .add(t1CondCodeOp()) 8884 .addReg(AddrIn) 8885 .addImm(StSize) 8886 .add(predOps(ARMCC::AL)); 8887 } else if (IsThumb2) { 8888 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8889 .addReg(Data) 8890 .addReg(AddrIn) 8891 .addImm(StSize) 8892 .add(predOps(ARMCC::AL)); 8893 } else { // arm 8894 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8895 .addReg(Data) 8896 .addReg(AddrIn) 8897 .addReg(0) 8898 .addImm(StSize) 8899 .add(predOps(ARMCC::AL)); 8900 } 8901 } 8902 8903 MachineBasicBlock * 8904 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8905 MachineBasicBlock *BB) const { 8906 // This pseudo instruction has 3 operands: dst, src, size 8907 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8908 // Otherwise, we will generate unrolled scalar copies. 8909 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8910 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8911 MachineFunction::iterator It = ++BB->getIterator(); 8912 8913 unsigned dest = MI.getOperand(0).getReg(); 8914 unsigned src = MI.getOperand(1).getReg(); 8915 unsigned SizeVal = MI.getOperand(2).getImm(); 8916 unsigned Align = MI.getOperand(3).getImm(); 8917 DebugLoc dl = MI.getDebugLoc(); 8918 8919 MachineFunction *MF = BB->getParent(); 8920 MachineRegisterInfo &MRI = MF->getRegInfo(); 8921 unsigned UnitSize = 0; 8922 const TargetRegisterClass *TRC = nullptr; 8923 const TargetRegisterClass *VecTRC = nullptr; 8924 8925 bool IsThumb1 = Subtarget->isThumb1Only(); 8926 bool IsThumb2 = Subtarget->isThumb2(); 8927 bool IsThumb = Subtarget->isThumb(); 8928 8929 if (Align & 1) { 8930 UnitSize = 1; 8931 } else if (Align & 2) { 8932 UnitSize = 2; 8933 } else { 8934 // Check whether we can use NEON instructions. 8935 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 8936 Subtarget->hasNEON()) { 8937 if ((Align % 16 == 0) && SizeVal >= 16) 8938 UnitSize = 16; 8939 else if ((Align % 8 == 0) && SizeVal >= 8) 8940 UnitSize = 8; 8941 } 8942 // Can't use NEON instructions. 8943 if (UnitSize == 0) 8944 UnitSize = 4; 8945 } 8946 8947 // Select the correct opcode and register class for unit size load/store 8948 bool IsNeon = UnitSize >= 8; 8949 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8950 if (IsNeon) 8951 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8952 : UnitSize == 8 ? &ARM::DPRRegClass 8953 : nullptr; 8954 8955 unsigned BytesLeft = SizeVal % UnitSize; 8956 unsigned LoopSize = SizeVal - BytesLeft; 8957 8958 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8959 // Use LDR and STR to copy. 8960 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8961 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8962 unsigned srcIn = src; 8963 unsigned destIn = dest; 8964 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8965 unsigned srcOut = MRI.createVirtualRegister(TRC); 8966 unsigned destOut = MRI.createVirtualRegister(TRC); 8967 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8968 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8969 IsThumb1, IsThumb2); 8970 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8971 IsThumb1, IsThumb2); 8972 srcIn = srcOut; 8973 destIn = destOut; 8974 } 8975 8976 // Handle the leftover bytes with LDRB and STRB. 8977 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8978 // [destOut] = STRB_POST(scratch, destIn, 1) 8979 for (unsigned i = 0; i < BytesLeft; i++) { 8980 unsigned srcOut = MRI.createVirtualRegister(TRC); 8981 unsigned destOut = MRI.createVirtualRegister(TRC); 8982 unsigned scratch = MRI.createVirtualRegister(TRC); 8983 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8984 IsThumb1, IsThumb2); 8985 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8986 IsThumb1, IsThumb2); 8987 srcIn = srcOut; 8988 destIn = destOut; 8989 } 8990 MI.eraseFromParent(); // The instruction is gone now. 8991 return BB; 8992 } 8993 8994 // Expand the pseudo op to a loop. 8995 // thisMBB: 8996 // ... 8997 // movw varEnd, # --> with thumb2 8998 // movt varEnd, # 8999 // ldrcp varEnd, idx --> without thumb2 9000 // fallthrough --> loopMBB 9001 // loopMBB: 9002 // PHI varPhi, varEnd, varLoop 9003 // PHI srcPhi, src, srcLoop 9004 // PHI destPhi, dst, destLoop 9005 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9006 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 9007 // subs varLoop, varPhi, #UnitSize 9008 // bne loopMBB 9009 // fallthrough --> exitMBB 9010 // exitMBB: 9011 // epilogue to handle left-over bytes 9012 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9013 // [destOut] = STRB_POST(scratch, destLoop, 1) 9014 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9015 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 9016 MF->insert(It, loopMBB); 9017 MF->insert(It, exitMBB); 9018 9019 // Transfer the remainder of BB and its successor edges to exitMBB. 9020 exitMBB->splice(exitMBB->begin(), BB, 9021 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9022 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9023 9024 // Load an immediate to varEnd. 9025 unsigned varEnd = MRI.createVirtualRegister(TRC); 9026 if (Subtarget->useMovt(*MF)) { 9027 unsigned Vtmp = varEnd; 9028 if ((LoopSize & 0xFFFF0000) != 0) 9029 Vtmp = MRI.createVirtualRegister(TRC); 9030 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 9031 .addImm(LoopSize & 0xFFFF) 9032 .add(predOps(ARMCC::AL)); 9033 9034 if ((LoopSize & 0xFFFF0000) != 0) 9035 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 9036 .addReg(Vtmp) 9037 .addImm(LoopSize >> 16) 9038 .add(predOps(ARMCC::AL)); 9039 } else { 9040 MachineConstantPool *ConstantPool = MF->getConstantPool(); 9041 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9042 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 9043 9044 // MachineConstantPool wants an explicit alignment. 9045 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9046 if (Align == 0) 9047 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9048 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9049 9050 if (IsThumb) 9051 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9052 .addReg(varEnd, RegState::Define) 9053 .addConstantPoolIndex(Idx) 9054 .add(predOps(ARMCC::AL)); 9055 else 9056 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9057 .addReg(varEnd, RegState::Define) 9058 .addConstantPoolIndex(Idx) 9059 .addImm(0) 9060 .add(predOps(ARMCC::AL)); 9061 } 9062 BB->addSuccessor(loopMBB); 9063 9064 // Generate the loop body: 9065 // varPhi = PHI(varLoop, varEnd) 9066 // srcPhi = PHI(srcLoop, src) 9067 // destPhi = PHI(destLoop, dst) 9068 MachineBasicBlock *entryBB = BB; 9069 BB = loopMBB; 9070 unsigned varLoop = MRI.createVirtualRegister(TRC); 9071 unsigned varPhi = MRI.createVirtualRegister(TRC); 9072 unsigned srcLoop = MRI.createVirtualRegister(TRC); 9073 unsigned srcPhi = MRI.createVirtualRegister(TRC); 9074 unsigned destLoop = MRI.createVirtualRegister(TRC); 9075 unsigned destPhi = MRI.createVirtualRegister(TRC); 9076 9077 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9078 .addReg(varLoop).addMBB(loopMBB) 9079 .addReg(varEnd).addMBB(entryBB); 9080 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9081 .addReg(srcLoop).addMBB(loopMBB) 9082 .addReg(src).addMBB(entryBB); 9083 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9084 .addReg(destLoop).addMBB(loopMBB) 9085 .addReg(dest).addMBB(entryBB); 9086 9087 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9088 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9089 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9090 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9091 IsThumb1, IsThumb2); 9092 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9093 IsThumb1, IsThumb2); 9094 9095 // Decrement loop variable by UnitSize. 9096 if (IsThumb1) { 9097 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9098 .add(t1CondCodeOp()) 9099 .addReg(varPhi) 9100 .addImm(UnitSize) 9101 .add(predOps(ARMCC::AL)); 9102 } else { 9103 MachineInstrBuilder MIB = 9104 BuildMI(*BB, BB->end(), dl, 9105 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9106 MIB.addReg(varPhi) 9107 .addImm(UnitSize) 9108 .add(predOps(ARMCC::AL)) 9109 .add(condCodeOp()); 9110 MIB->getOperand(5).setReg(ARM::CPSR); 9111 MIB->getOperand(5).setIsDef(true); 9112 } 9113 BuildMI(*BB, BB->end(), dl, 9114 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9115 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9116 9117 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9118 BB->addSuccessor(loopMBB); 9119 BB->addSuccessor(exitMBB); 9120 9121 // Add epilogue to handle BytesLeft. 9122 BB = exitMBB; 9123 auto StartOfExit = exitMBB->begin(); 9124 9125 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9126 // [destOut] = STRB_POST(scratch, destLoop, 1) 9127 unsigned srcIn = srcLoop; 9128 unsigned destIn = destLoop; 9129 for (unsigned i = 0; i < BytesLeft; i++) { 9130 unsigned srcOut = MRI.createVirtualRegister(TRC); 9131 unsigned destOut = MRI.createVirtualRegister(TRC); 9132 unsigned scratch = MRI.createVirtualRegister(TRC); 9133 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9134 IsThumb1, IsThumb2); 9135 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9136 IsThumb1, IsThumb2); 9137 srcIn = srcOut; 9138 destIn = destOut; 9139 } 9140 9141 MI.eraseFromParent(); // The instruction is gone now. 9142 return BB; 9143 } 9144 9145 MachineBasicBlock * 9146 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9147 MachineBasicBlock *MBB) const { 9148 const TargetMachine &TM = getTargetMachine(); 9149 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9150 DebugLoc DL = MI.getDebugLoc(); 9151 9152 assert(Subtarget->isTargetWindows() && 9153 "__chkstk is only supported on Windows"); 9154 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9155 9156 // __chkstk takes the number of words to allocate on the stack in R4, and 9157 // returns the stack adjustment in number of bytes in R4. This will not 9158 // clober any other registers (other than the obvious lr). 9159 // 9160 // Although, technically, IP should be considered a register which may be 9161 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9162 // thumb-2 environment, so there is no interworking required. As a result, we 9163 // do not expect a veneer to be emitted by the linker, clobbering IP. 9164 // 9165 // Each module receives its own copy of __chkstk, so no import thunk is 9166 // required, again, ensuring that IP is not clobbered. 9167 // 9168 // Finally, although some linkers may theoretically provide a trampoline for 9169 // out of range calls (which is quite common due to a 32M range limitation of 9170 // branches for Thumb), we can generate the long-call version via 9171 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9172 // IP. 9173 9174 switch (TM.getCodeModel()) { 9175 case CodeModel::Small: 9176 case CodeModel::Medium: 9177 case CodeModel::Kernel: 9178 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9179 .add(predOps(ARMCC::AL)) 9180 .addExternalSymbol("__chkstk") 9181 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9182 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9183 .addReg(ARM::R12, 9184 RegState::Implicit | RegState::Define | RegState::Dead) 9185 .addReg(ARM::CPSR, 9186 RegState::Implicit | RegState::Define | RegState::Dead); 9187 break; 9188 case CodeModel::Large: { 9189 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9190 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9191 9192 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 9193 .addExternalSymbol("__chkstk"); 9194 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 9195 .add(predOps(ARMCC::AL)) 9196 .addReg(Reg, RegState::Kill) 9197 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9198 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9199 .addReg(ARM::R12, 9200 RegState::Implicit | RegState::Define | RegState::Dead) 9201 .addReg(ARM::CPSR, 9202 RegState::Implicit | RegState::Define | RegState::Dead); 9203 break; 9204 } 9205 } 9206 9207 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9208 .addReg(ARM::SP, RegState::Kill) 9209 .addReg(ARM::R4, RegState::Kill) 9210 .setMIFlags(MachineInstr::FrameSetup) 9211 .add(predOps(ARMCC::AL)) 9212 .add(condCodeOp()); 9213 9214 MI.eraseFromParent(); 9215 return MBB; 9216 } 9217 9218 MachineBasicBlock * 9219 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9220 MachineBasicBlock *MBB) const { 9221 DebugLoc DL = MI.getDebugLoc(); 9222 MachineFunction *MF = MBB->getParent(); 9223 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9224 9225 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9226 MF->insert(++MBB->getIterator(), ContBB); 9227 ContBB->splice(ContBB->begin(), MBB, 9228 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9229 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9230 MBB->addSuccessor(ContBB); 9231 9232 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9233 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9234 MF->push_back(TrapBB); 9235 MBB->addSuccessor(TrapBB); 9236 9237 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9238 .addReg(MI.getOperand(0).getReg()) 9239 .addImm(0) 9240 .add(predOps(ARMCC::AL)); 9241 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 9242 .addMBB(TrapBB) 9243 .addImm(ARMCC::EQ) 9244 .addReg(ARM::CPSR); 9245 9246 MI.eraseFromParent(); 9247 return ContBB; 9248 } 9249 9250 MachineBasicBlock * 9251 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9252 MachineBasicBlock *BB) const { 9253 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9254 DebugLoc dl = MI.getDebugLoc(); 9255 bool isThumb2 = Subtarget->isThumb2(); 9256 switch (MI.getOpcode()) { 9257 default: { 9258 MI.print(errs()); 9259 llvm_unreachable("Unexpected instr type to insert"); 9260 } 9261 9262 // Thumb1 post-indexed loads are really just single-register LDMs. 9263 case ARM::tLDR_postidx: { 9264 MachineOperand Def(MI.getOperand(1)); 9265 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 9266 .add(Def) // Rn_wb 9267 .add(MI.getOperand(2)) // Rn 9268 .add(MI.getOperand(3)) // PredImm 9269 .add(MI.getOperand(4)) // PredReg 9270 .add(MI.getOperand(0)); // Rt 9271 MI.eraseFromParent(); 9272 return BB; 9273 } 9274 9275 // The Thumb2 pre-indexed stores have the same MI operands, they just 9276 // define them differently in the .td files from the isel patterns, so 9277 // they need pseudos. 9278 case ARM::t2STR_preidx: 9279 MI.setDesc(TII->get(ARM::t2STR_PRE)); 9280 return BB; 9281 case ARM::t2STRB_preidx: 9282 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 9283 return BB; 9284 case ARM::t2STRH_preidx: 9285 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9286 return BB; 9287 9288 case ARM::STRi_preidx: 9289 case ARM::STRBi_preidx: { 9290 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9291 : ARM::STRB_PRE_IMM; 9292 // Decode the offset. 9293 unsigned Offset = MI.getOperand(4).getImm(); 9294 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9295 Offset = ARM_AM::getAM2Offset(Offset); 9296 if (isSub) 9297 Offset = -Offset; 9298 9299 MachineMemOperand *MMO = *MI.memoperands_begin(); 9300 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9301 .add(MI.getOperand(0)) // Rn_wb 9302 .add(MI.getOperand(1)) // Rt 9303 .add(MI.getOperand(2)) // Rn 9304 .addImm(Offset) // offset (skip GPR==zero_reg) 9305 .add(MI.getOperand(5)) // pred 9306 .add(MI.getOperand(6)) 9307 .addMemOperand(MMO); 9308 MI.eraseFromParent(); 9309 return BB; 9310 } 9311 case ARM::STRr_preidx: 9312 case ARM::STRBr_preidx: 9313 case ARM::STRH_preidx: { 9314 unsigned NewOpc; 9315 switch (MI.getOpcode()) { 9316 default: llvm_unreachable("unexpected opcode!"); 9317 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9318 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9319 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9320 } 9321 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9322 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9323 MIB.add(MI.getOperand(i)); 9324 MI.eraseFromParent(); 9325 return BB; 9326 } 9327 9328 case ARM::tMOVCCr_pseudo: { 9329 // To "insert" a SELECT_CC instruction, we actually have to insert the 9330 // diamond control-flow pattern. The incoming instruction knows the 9331 // destination vreg to set, the condition code register to branch on, the 9332 // true/false values to select between, and a branch opcode to use. 9333 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9334 MachineFunction::iterator It = ++BB->getIterator(); 9335 9336 // thisMBB: 9337 // ... 9338 // TrueVal = ... 9339 // cmpTY ccX, r1, r2 9340 // bCC copy1MBB 9341 // fallthrough --> copy0MBB 9342 MachineBasicBlock *thisMBB = BB; 9343 MachineFunction *F = BB->getParent(); 9344 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9345 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9346 F->insert(It, copy0MBB); 9347 F->insert(It, sinkMBB); 9348 9349 // Transfer the remainder of BB and its successor edges to sinkMBB. 9350 sinkMBB->splice(sinkMBB->begin(), BB, 9351 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9352 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9353 9354 BB->addSuccessor(copy0MBB); 9355 BB->addSuccessor(sinkMBB); 9356 9357 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9358 .addMBB(sinkMBB) 9359 .addImm(MI.getOperand(3).getImm()) 9360 .addReg(MI.getOperand(4).getReg()); 9361 9362 // copy0MBB: 9363 // %FalseValue = ... 9364 // # fallthrough to sinkMBB 9365 BB = copy0MBB; 9366 9367 // Update machine-CFG edges 9368 BB->addSuccessor(sinkMBB); 9369 9370 // sinkMBB: 9371 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9372 // ... 9373 BB = sinkMBB; 9374 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9375 .addReg(MI.getOperand(1).getReg()) 9376 .addMBB(copy0MBB) 9377 .addReg(MI.getOperand(2).getReg()) 9378 .addMBB(thisMBB); 9379 9380 MI.eraseFromParent(); // The pseudo instruction is gone now. 9381 return BB; 9382 } 9383 9384 case ARM::BCCi64: 9385 case ARM::BCCZi64: { 9386 // If there is an unconditional branch to the other successor, remove it. 9387 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9388 9389 // Compare both parts that make up the double comparison separately for 9390 // equality. 9391 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9392 9393 unsigned LHS1 = MI.getOperand(1).getReg(); 9394 unsigned LHS2 = MI.getOperand(2).getReg(); 9395 if (RHSisZero) { 9396 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9397 .addReg(LHS1) 9398 .addImm(0) 9399 .add(predOps(ARMCC::AL)); 9400 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9401 .addReg(LHS2).addImm(0) 9402 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9403 } else { 9404 unsigned RHS1 = MI.getOperand(3).getReg(); 9405 unsigned RHS2 = MI.getOperand(4).getReg(); 9406 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9407 .addReg(LHS1) 9408 .addReg(RHS1) 9409 .add(predOps(ARMCC::AL)); 9410 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9411 .addReg(LHS2).addReg(RHS2) 9412 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9413 } 9414 9415 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9416 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9417 if (MI.getOperand(0).getImm() == ARMCC::NE) 9418 std::swap(destMBB, exitMBB); 9419 9420 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9421 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9422 if (isThumb2) 9423 BuildMI(BB, dl, TII->get(ARM::t2B)) 9424 .addMBB(exitMBB) 9425 .add(predOps(ARMCC::AL)); 9426 else 9427 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9428 9429 MI.eraseFromParent(); // The pseudo instruction is gone now. 9430 return BB; 9431 } 9432 9433 case ARM::Int_eh_sjlj_setjmp: 9434 case ARM::Int_eh_sjlj_setjmp_nofp: 9435 case ARM::tInt_eh_sjlj_setjmp: 9436 case ARM::t2Int_eh_sjlj_setjmp: 9437 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9438 return BB; 9439 9440 case ARM::Int_eh_sjlj_setup_dispatch: 9441 EmitSjLjDispatchBlock(MI, BB); 9442 return BB; 9443 9444 case ARM::ABS: 9445 case ARM::t2ABS: { 9446 // To insert an ABS instruction, we have to insert the 9447 // diamond control-flow pattern. The incoming instruction knows the 9448 // source vreg to test against 0, the destination vreg to set, 9449 // the condition code register to branch on, the 9450 // true/false values to select between, and a branch opcode to use. 9451 // It transforms 9452 // V1 = ABS V0 9453 // into 9454 // V2 = MOVS V0 9455 // BCC (branch to SinkBB if V0 >= 0) 9456 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9457 // SinkBB: V1 = PHI(V2, V3) 9458 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9459 MachineFunction::iterator BBI = ++BB->getIterator(); 9460 MachineFunction *Fn = BB->getParent(); 9461 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9462 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9463 Fn->insert(BBI, RSBBB); 9464 Fn->insert(BBI, SinkBB); 9465 9466 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9467 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9468 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9469 bool isThumb2 = Subtarget->isThumb2(); 9470 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9471 // In Thumb mode S must not be specified if source register is the SP or 9472 // PC and if destination register is the SP, so restrict register class 9473 unsigned NewRsbDstReg = 9474 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9475 9476 // Transfer the remainder of BB and its successor edges to sinkMBB. 9477 SinkBB->splice(SinkBB->begin(), BB, 9478 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9479 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9480 9481 BB->addSuccessor(RSBBB); 9482 BB->addSuccessor(SinkBB); 9483 9484 // fall through to SinkMBB 9485 RSBBB->addSuccessor(SinkBB); 9486 9487 // insert a cmp at the end of BB 9488 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9489 .addReg(ABSSrcReg) 9490 .addImm(0) 9491 .add(predOps(ARMCC::AL)); 9492 9493 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9494 BuildMI(BB, dl, 9495 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9496 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9497 9498 // insert rsbri in RSBBB 9499 // Note: BCC and rsbri will be converted into predicated rsbmi 9500 // by if-conversion pass 9501 BuildMI(*RSBBB, RSBBB->begin(), dl, 9502 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9503 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9504 .addImm(0) 9505 .add(predOps(ARMCC::AL)) 9506 .add(condCodeOp()); 9507 9508 // insert PHI in SinkBB, 9509 // reuse ABSDstReg to not change uses of ABS instruction 9510 BuildMI(*SinkBB, SinkBB->begin(), dl, 9511 TII->get(ARM::PHI), ABSDstReg) 9512 .addReg(NewRsbDstReg).addMBB(RSBBB) 9513 .addReg(ABSSrcReg).addMBB(BB); 9514 9515 // remove ABS instruction 9516 MI.eraseFromParent(); 9517 9518 // return last added BB 9519 return SinkBB; 9520 } 9521 case ARM::COPY_STRUCT_BYVAL_I32: 9522 ++NumLoopByVals; 9523 return EmitStructByval(MI, BB); 9524 case ARM::WIN__CHKSTK: 9525 return EmitLowered__chkstk(MI, BB); 9526 case ARM::WIN__DBZCHK: 9527 return EmitLowered__dbzchk(MI, BB); 9528 } 9529 } 9530 9531 /// Attaches vregs to MEMCPY that it will use as scratch registers 9532 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9533 /// instead of as a custom inserter because we need the use list from the SDNode. 9534 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9535 MachineInstr &MI, const SDNode *Node) { 9536 bool isThumb1 = Subtarget->isThumb1Only(); 9537 9538 DebugLoc DL = MI.getDebugLoc(); 9539 MachineFunction *MF = MI.getParent()->getParent(); 9540 MachineRegisterInfo &MRI = MF->getRegInfo(); 9541 MachineInstrBuilder MIB(*MF, MI); 9542 9543 // If the new dst/src is unused mark it as dead. 9544 if (!Node->hasAnyUseOfValue(0)) { 9545 MI.getOperand(0).setIsDead(true); 9546 } 9547 if (!Node->hasAnyUseOfValue(1)) { 9548 MI.getOperand(1).setIsDead(true); 9549 } 9550 9551 // The MEMCPY both defines and kills the scratch registers. 9552 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9553 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9554 : &ARM::GPRRegClass); 9555 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9556 } 9557 } 9558 9559 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9560 SDNode *Node) const { 9561 if (MI.getOpcode() == ARM::MEMCPY) { 9562 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9563 return; 9564 } 9565 9566 const MCInstrDesc *MCID = &MI.getDesc(); 9567 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9568 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9569 // operand is still set to noreg. If needed, set the optional operand's 9570 // register to CPSR, and remove the redundant implicit def. 9571 // 9572 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 9573 9574 // Rename pseudo opcodes. 9575 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9576 unsigned ccOutIdx; 9577 if (NewOpc) { 9578 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9579 MCID = &TII->get(NewOpc); 9580 9581 assert(MCID->getNumOperands() == 9582 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9583 && "converted opcode should be the same except for cc_out" 9584 " (and, on Thumb1, pred)"); 9585 9586 MI.setDesc(*MCID); 9587 9588 // Add the optional cc_out operand 9589 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9590 9591 // On Thumb1, move all input operands to the end, then add the predicate 9592 if (Subtarget->isThumb1Only()) { 9593 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9594 MI.addOperand(MI.getOperand(1)); 9595 MI.RemoveOperand(1); 9596 } 9597 9598 // Restore the ties 9599 for (unsigned i = MI.getNumOperands(); i--;) { 9600 const MachineOperand& op = MI.getOperand(i); 9601 if (op.isReg() && op.isUse()) { 9602 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9603 if (DefIdx != -1) 9604 MI.tieOperands(DefIdx, i); 9605 } 9606 } 9607 9608 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9609 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9610 ccOutIdx = 1; 9611 } else 9612 ccOutIdx = MCID->getNumOperands() - 1; 9613 } else 9614 ccOutIdx = MCID->getNumOperands() - 1; 9615 9616 // Any ARM instruction that sets the 's' bit should specify an optional 9617 // "cc_out" operand in the last operand position. 9618 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9619 assert(!NewOpc && "Optional cc_out operand required"); 9620 return; 9621 } 9622 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9623 // since we already have an optional CPSR def. 9624 bool definesCPSR = false; 9625 bool deadCPSR = false; 9626 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9627 ++i) { 9628 const MachineOperand &MO = MI.getOperand(i); 9629 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9630 definesCPSR = true; 9631 if (MO.isDead()) 9632 deadCPSR = true; 9633 MI.RemoveOperand(i); 9634 break; 9635 } 9636 } 9637 if (!definesCPSR) { 9638 assert(!NewOpc && "Optional cc_out operand required"); 9639 return; 9640 } 9641 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9642 if (deadCPSR) { 9643 assert(!MI.getOperand(ccOutIdx).getReg() && 9644 "expect uninitialized optional cc_out operand"); 9645 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9646 if (!Subtarget->isThumb1Only()) 9647 return; 9648 } 9649 9650 // If this instruction was defined with an optional CPSR def and its dag node 9651 // had a live implicit CPSR def, then activate the optional CPSR def. 9652 MachineOperand &MO = MI.getOperand(ccOutIdx); 9653 MO.setReg(ARM::CPSR); 9654 MO.setIsDef(true); 9655 } 9656 9657 //===----------------------------------------------------------------------===// 9658 // ARM Optimization Hooks 9659 //===----------------------------------------------------------------------===// 9660 9661 // Helper function that checks if N is a null or all ones constant. 9662 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9663 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9664 } 9665 9666 // Return true if N is conditionally 0 or all ones. 9667 // Detects these expressions where cc is an i1 value: 9668 // 9669 // (select cc 0, y) [AllOnes=0] 9670 // (select cc y, 0) [AllOnes=0] 9671 // (zext cc) [AllOnes=0] 9672 // (sext cc) [AllOnes=0/1] 9673 // (select cc -1, y) [AllOnes=1] 9674 // (select cc y, -1) [AllOnes=1] 9675 // 9676 // Invert is set when N is the null/all ones constant when CC is false. 9677 // OtherOp is set to the alternative value of N. 9678 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9679 SDValue &CC, bool &Invert, 9680 SDValue &OtherOp, 9681 SelectionDAG &DAG) { 9682 switch (N->getOpcode()) { 9683 default: return false; 9684 case ISD::SELECT: { 9685 CC = N->getOperand(0); 9686 SDValue N1 = N->getOperand(1); 9687 SDValue N2 = N->getOperand(2); 9688 if (isZeroOrAllOnes(N1, AllOnes)) { 9689 Invert = false; 9690 OtherOp = N2; 9691 return true; 9692 } 9693 if (isZeroOrAllOnes(N2, AllOnes)) { 9694 Invert = true; 9695 OtherOp = N1; 9696 return true; 9697 } 9698 return false; 9699 } 9700 case ISD::ZERO_EXTEND: 9701 // (zext cc) can never be the all ones value. 9702 if (AllOnes) 9703 return false; 9704 LLVM_FALLTHROUGH; 9705 case ISD::SIGN_EXTEND: { 9706 SDLoc dl(N); 9707 EVT VT = N->getValueType(0); 9708 CC = N->getOperand(0); 9709 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9710 return false; 9711 Invert = !AllOnes; 9712 if (AllOnes) 9713 // When looking for an AllOnes constant, N is an sext, and the 'other' 9714 // value is 0. 9715 OtherOp = DAG.getConstant(0, dl, VT); 9716 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9717 // When looking for a 0 constant, N can be zext or sext. 9718 OtherOp = DAG.getConstant(1, dl, VT); 9719 else 9720 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9721 VT); 9722 return true; 9723 } 9724 } 9725 } 9726 9727 // Combine a constant select operand into its use: 9728 // 9729 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9730 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9731 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9732 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9733 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9734 // 9735 // The transform is rejected if the select doesn't have a constant operand that 9736 // is null, or all ones when AllOnes is set. 9737 // 9738 // Also recognize sext/zext from i1: 9739 // 9740 // (add (zext cc), x) -> (select cc (add x, 1), x) 9741 // (add (sext cc), x) -> (select cc (add x, -1), x) 9742 // 9743 // These transformations eventually create predicated instructions. 9744 // 9745 // @param N The node to transform. 9746 // @param Slct The N operand that is a select. 9747 // @param OtherOp The other N operand (x above). 9748 // @param DCI Context. 9749 // @param AllOnes Require the select constant to be all ones instead of null. 9750 // @returns The new node, or SDValue() on failure. 9751 static 9752 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9753 TargetLowering::DAGCombinerInfo &DCI, 9754 bool AllOnes = false) { 9755 SelectionDAG &DAG = DCI.DAG; 9756 EVT VT = N->getValueType(0); 9757 SDValue NonConstantVal; 9758 SDValue CCOp; 9759 bool SwapSelectOps; 9760 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9761 NonConstantVal, DAG)) 9762 return SDValue(); 9763 9764 // Slct is now know to be the desired identity constant when CC is true. 9765 SDValue TrueVal = OtherOp; 9766 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9767 OtherOp, NonConstantVal); 9768 // Unless SwapSelectOps says CC should be false. 9769 if (SwapSelectOps) 9770 std::swap(TrueVal, FalseVal); 9771 9772 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9773 CCOp, TrueVal, FalseVal); 9774 } 9775 9776 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9777 static 9778 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9779 TargetLowering::DAGCombinerInfo &DCI) { 9780 SDValue N0 = N->getOperand(0); 9781 SDValue N1 = N->getOperand(1); 9782 if (N0.getNode()->hasOneUse()) 9783 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9784 return Result; 9785 if (N1.getNode()->hasOneUse()) 9786 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9787 return Result; 9788 return SDValue(); 9789 } 9790 9791 static bool IsVUZPShuffleNode(SDNode *N) { 9792 // VUZP shuffle node. 9793 if (N->getOpcode() == ARMISD::VUZP) 9794 return true; 9795 9796 // "VUZP" on i32 is an alias for VTRN. 9797 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9798 return true; 9799 9800 return false; 9801 } 9802 9803 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9804 TargetLowering::DAGCombinerInfo &DCI, 9805 const ARMSubtarget *Subtarget) { 9806 // Look for ADD(VUZP.0, VUZP.1). 9807 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9808 N0 == N1) 9809 return SDValue(); 9810 9811 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9812 if (!N->getValueType(0).is64BitVector()) 9813 return SDValue(); 9814 9815 // Generate vpadd. 9816 SelectionDAG &DAG = DCI.DAG; 9817 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9818 SDLoc dl(N); 9819 SDNode *Unzip = N0.getNode(); 9820 EVT VT = N->getValueType(0); 9821 9822 SmallVector<SDValue, 8> Ops; 9823 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9824 TLI.getPointerTy(DAG.getDataLayout()))); 9825 Ops.push_back(Unzip->getOperand(0)); 9826 Ops.push_back(Unzip->getOperand(1)); 9827 9828 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9829 } 9830 9831 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9832 TargetLowering::DAGCombinerInfo &DCI, 9833 const ARMSubtarget *Subtarget) { 9834 // Check for two extended operands. 9835 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9836 N1.getOpcode() == ISD::SIGN_EXTEND) && 9837 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9838 N1.getOpcode() == ISD::ZERO_EXTEND)) 9839 return SDValue(); 9840 9841 SDValue N00 = N0.getOperand(0); 9842 SDValue N10 = N1.getOperand(0); 9843 9844 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9845 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9846 N00 == N10) 9847 return SDValue(); 9848 9849 // We only recognize Q register paddl here; this can't be reached until 9850 // after type legalization. 9851 if (!N00.getValueType().is64BitVector() || 9852 !N0.getValueType().is128BitVector()) 9853 return SDValue(); 9854 9855 // Generate vpaddl. 9856 SelectionDAG &DAG = DCI.DAG; 9857 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9858 SDLoc dl(N); 9859 EVT VT = N->getValueType(0); 9860 9861 SmallVector<SDValue, 8> Ops; 9862 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9863 unsigned Opcode; 9864 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9865 Opcode = Intrinsic::arm_neon_vpaddls; 9866 else 9867 Opcode = Intrinsic::arm_neon_vpaddlu; 9868 Ops.push_back(DAG.getConstant(Opcode, dl, 9869 TLI.getPointerTy(DAG.getDataLayout()))); 9870 EVT ElemTy = N00.getValueType().getVectorElementType(); 9871 unsigned NumElts = VT.getVectorNumElements(); 9872 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9873 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9874 N00.getOperand(0), N00.getOperand(1)); 9875 Ops.push_back(Concat); 9876 9877 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9878 } 9879 9880 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9881 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9882 // much easier to match. 9883 static SDValue 9884 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9885 TargetLowering::DAGCombinerInfo &DCI, 9886 const ARMSubtarget *Subtarget) { 9887 // Only perform optimization if after legalize, and if NEON is available. We 9888 // also expected both operands to be BUILD_VECTORs. 9889 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9890 || N0.getOpcode() != ISD::BUILD_VECTOR 9891 || N1.getOpcode() != ISD::BUILD_VECTOR) 9892 return SDValue(); 9893 9894 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9895 EVT VT = N->getValueType(0); 9896 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9897 return SDValue(); 9898 9899 // Check that the vector operands are of the right form. 9900 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9901 // operands, where N is the size of the formed vector. 9902 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9903 // index such that we have a pair wise add pattern. 9904 9905 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9906 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9907 return SDValue(); 9908 SDValue Vec = N0->getOperand(0)->getOperand(0); 9909 SDNode *V = Vec.getNode(); 9910 unsigned nextIndex = 0; 9911 9912 // For each operands to the ADD which are BUILD_VECTORs, 9913 // check to see if each of their operands are an EXTRACT_VECTOR with 9914 // the same vector and appropriate index. 9915 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9916 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9917 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9918 9919 SDValue ExtVec0 = N0->getOperand(i); 9920 SDValue ExtVec1 = N1->getOperand(i); 9921 9922 // First operand is the vector, verify its the same. 9923 if (V != ExtVec0->getOperand(0).getNode() || 9924 V != ExtVec1->getOperand(0).getNode()) 9925 return SDValue(); 9926 9927 // Second is the constant, verify its correct. 9928 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9929 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9930 9931 // For the constant, we want to see all the even or all the odd. 9932 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9933 || C1->getZExtValue() != nextIndex+1) 9934 return SDValue(); 9935 9936 // Increment index. 9937 nextIndex+=2; 9938 } else 9939 return SDValue(); 9940 } 9941 9942 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 9943 // we're using the entire input vector, otherwise there's a size/legality 9944 // mismatch somewhere. 9945 if (nextIndex != Vec.getValueType().getVectorNumElements() || 9946 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9947 return SDValue(); 9948 9949 // Create VPADDL node. 9950 SelectionDAG &DAG = DCI.DAG; 9951 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9952 9953 SDLoc dl(N); 9954 9955 // Build operand list. 9956 SmallVector<SDValue, 8> Ops; 9957 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9958 TLI.getPointerTy(DAG.getDataLayout()))); 9959 9960 // Input is the vector. 9961 Ops.push_back(Vec); 9962 9963 // Get widened type and narrowed type. 9964 MVT widenType; 9965 unsigned numElem = VT.getVectorNumElements(); 9966 9967 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9968 switch (inputLaneType.getSimpleVT().SimpleTy) { 9969 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9970 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9971 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9972 default: 9973 llvm_unreachable("Invalid vector element type for padd optimization."); 9974 } 9975 9976 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9977 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9978 return DAG.getNode(ExtOp, dl, VT, tmp); 9979 } 9980 9981 static SDValue findMUL_LOHI(SDValue V) { 9982 if (V->getOpcode() == ISD::UMUL_LOHI || 9983 V->getOpcode() == ISD::SMUL_LOHI) 9984 return V; 9985 return SDValue(); 9986 } 9987 9988 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 9989 TargetLowering::DAGCombinerInfo &DCI, 9990 const ARMSubtarget *Subtarget) { 9991 if (Subtarget->isThumb()) { 9992 if (!Subtarget->hasDSP()) 9993 return SDValue(); 9994 } else if (!Subtarget->hasV5TEOps()) 9995 return SDValue(); 9996 9997 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 9998 // accumulates the product into a 64-bit value. The 16-bit values will 9999 // be sign extended somehow or SRA'd into 32-bit values 10000 // (addc (adde (mul 16bit, 16bit), lo), hi) 10001 SDValue Mul = AddcNode->getOperand(0); 10002 SDValue Lo = AddcNode->getOperand(1); 10003 if (Mul.getOpcode() != ISD::MUL) { 10004 Lo = AddcNode->getOperand(0); 10005 Mul = AddcNode->getOperand(1); 10006 if (Mul.getOpcode() != ISD::MUL) 10007 return SDValue(); 10008 } 10009 10010 SDValue SRA = AddeNode->getOperand(0); 10011 SDValue Hi = AddeNode->getOperand(1); 10012 if (SRA.getOpcode() != ISD::SRA) { 10013 SRA = AddeNode->getOperand(1); 10014 Hi = AddeNode->getOperand(0); 10015 if (SRA.getOpcode() != ISD::SRA) 10016 return SDValue(); 10017 } 10018 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 10019 if (Const->getZExtValue() != 31) 10020 return SDValue(); 10021 } else 10022 return SDValue(); 10023 10024 if (SRA.getOperand(0) != Mul) 10025 return SDValue(); 10026 10027 SelectionDAG &DAG = DCI.DAG; 10028 SDLoc dl(AddcNode); 10029 unsigned Opcode = 0; 10030 SDValue Op0; 10031 SDValue Op1; 10032 10033 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 10034 Opcode = ARMISD::SMLALBB; 10035 Op0 = Mul.getOperand(0); 10036 Op1 = Mul.getOperand(1); 10037 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 10038 Opcode = ARMISD::SMLALBT; 10039 Op0 = Mul.getOperand(0); 10040 Op1 = Mul.getOperand(1).getOperand(0); 10041 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10042 Opcode = ARMISD::SMLALTB; 10043 Op0 = Mul.getOperand(0).getOperand(0); 10044 Op1 = Mul.getOperand(1); 10045 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10046 Opcode = ARMISD::SMLALTT; 10047 Op0 = Mul->getOperand(0).getOperand(0); 10048 Op1 = Mul->getOperand(1).getOperand(0); 10049 } 10050 10051 if (!Op0 || !Op1) 10052 return SDValue(); 10053 10054 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10055 Op0, Op1, Lo, Hi); 10056 // Replace the ADDs' nodes uses by the MLA node's values. 10057 SDValue HiMLALResult(SMLAL.getNode(), 1); 10058 SDValue LoMLALResult(SMLAL.getNode(), 0); 10059 10060 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10061 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10062 10063 // Return original node to notify the driver to stop replacing. 10064 SDValue resNode(AddcNode, 0); 10065 return resNode; 10066 } 10067 10068 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10069 TargetLowering::DAGCombinerInfo &DCI, 10070 const ARMSubtarget *Subtarget) { 10071 // Look for multiply add opportunities. 10072 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10073 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10074 // a glue link from the first add to the second add. 10075 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10076 // a S/UMLAL instruction. 10077 // UMUL_LOHI 10078 // / :lo \ :hi 10079 // V \ [no multiline comment] 10080 // loAdd -> ADDC | 10081 // \ :carry / 10082 // V V 10083 // ADDE <- hiAdd 10084 // 10085 // In the special case where only the higher part of a signed result is used 10086 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10087 // a constant with the exact value of 0x80000000, we recognize we are dealing 10088 // with a "rounded multiply and add" (or subtract) and transform it into 10089 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10090 10091 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10092 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10093 "Expect an ADDE or SUBE"); 10094 10095 assert(AddeSubeNode->getNumOperands() == 3 && 10096 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10097 "ADDE node has the wrong inputs"); 10098 10099 // Check that we are chained to the right ADDC or SUBC node. 10100 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10101 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10102 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10103 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10104 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10105 return SDValue(); 10106 10107 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10108 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10109 10110 // Check if the two operands are from the same mul_lohi node. 10111 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10112 return SDValue(); 10113 10114 assert(AddcSubcNode->getNumValues() == 2 && 10115 AddcSubcNode->getValueType(0) == MVT::i32 && 10116 "Expect ADDC with two result values. First: i32"); 10117 10118 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10119 // maybe a SMLAL which multiplies two 16-bit values. 10120 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10121 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10122 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10123 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10124 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10125 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10126 10127 // Check for the triangle shape. 10128 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10129 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10130 10131 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10132 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10133 return SDValue(); 10134 10135 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10136 bool IsLeftOperandMUL = false; 10137 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10138 if (MULOp == SDValue()) 10139 MULOp = findMUL_LOHI(AddeSubeOp1); 10140 else 10141 IsLeftOperandMUL = true; 10142 if (MULOp == SDValue()) 10143 return SDValue(); 10144 10145 // Figure out the right opcode. 10146 unsigned Opc = MULOp->getOpcode(); 10147 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 10148 10149 // Figure out the high and low input values to the MLAL node. 10150 SDValue *HiAddSub = nullptr; 10151 SDValue *LoMul = nullptr; 10152 SDValue *LowAddSub = nullptr; 10153 10154 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 10155 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 10156 return SDValue(); 10157 10158 if (IsLeftOperandMUL) 10159 HiAddSub = &AddeSubeOp1; 10160 else 10161 HiAddSub = &AddeSubeOp0; 10162 10163 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 10164 // whose low result is fed to the ADDC/SUBC we are checking. 10165 10166 if (AddcSubcOp0 == MULOp.getValue(0)) { 10167 LoMul = &AddcSubcOp0; 10168 LowAddSub = &AddcSubcOp1; 10169 } 10170 if (AddcSubcOp1 == MULOp.getValue(0)) { 10171 LoMul = &AddcSubcOp1; 10172 LowAddSub = &AddcSubcOp0; 10173 } 10174 10175 if (!LoMul) 10176 return SDValue(); 10177 10178 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 10179 // the replacement below will create a cycle. 10180 if (AddcSubcNode == HiAddSub->getNode() || 10181 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 10182 return SDValue(); 10183 10184 // Create the merged node. 10185 SelectionDAG &DAG = DCI.DAG; 10186 10187 // Start building operand list. 10188 SmallVector<SDValue, 8> Ops; 10189 Ops.push_back(LoMul->getOperand(0)); 10190 Ops.push_back(LoMul->getOperand(1)); 10191 10192 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 10193 // the case, we must be doing signed multiplication and only use the higher 10194 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 10195 // addition or subtraction with the value of 0x800000. 10196 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 10197 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 10198 LowAddSub->getNode()->getOpcode() == ISD::Constant && 10199 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 10200 0x80000000) { 10201 Ops.push_back(*HiAddSub); 10202 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 10203 FinalOpc = ARMISD::SMMLSR; 10204 } else { 10205 FinalOpc = ARMISD::SMMLAR; 10206 } 10207 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 10208 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 10209 10210 return SDValue(AddeSubeNode, 0); 10211 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 10212 // SMMLS is generated during instruction selection and the rest of this 10213 // function can not handle the case where AddcSubcNode is a SUBC. 10214 return SDValue(); 10215 10216 // Finish building the operand list for {U/S}MLAL 10217 Ops.push_back(*LowAddSub); 10218 Ops.push_back(*HiAddSub); 10219 10220 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 10221 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10222 10223 // Replace the ADDs' nodes uses by the MLA node's values. 10224 SDValue HiMLALResult(MLALNode.getNode(), 1); 10225 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 10226 10227 SDValue LoMLALResult(MLALNode.getNode(), 0); 10228 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 10229 10230 // Return original node to notify the driver to stop replacing. 10231 return SDValue(AddeSubeNode, 0); 10232 } 10233 10234 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 10235 TargetLowering::DAGCombinerInfo &DCI, 10236 const ARMSubtarget *Subtarget) { 10237 // UMAAL is similar to UMLAL except that it adds two unsigned values. 10238 // While trying to combine for the other MLAL nodes, first search for the 10239 // chance to use UMAAL. Check if Addc uses a node which has already 10240 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 10241 // as the addend, and it's handled in PerformUMLALCombine. 10242 10243 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10244 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10245 10246 // Check that we have a glued ADDC node. 10247 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 10248 if (AddcNode->getOpcode() != ARMISD::ADDC) 10249 return SDValue(); 10250 10251 // Find the converted UMAAL or quit if it doesn't exist. 10252 SDNode *UmlalNode = nullptr; 10253 SDValue AddHi; 10254 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 10255 UmlalNode = AddcNode->getOperand(0).getNode(); 10256 AddHi = AddcNode->getOperand(1); 10257 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 10258 UmlalNode = AddcNode->getOperand(1).getNode(); 10259 AddHi = AddcNode->getOperand(0); 10260 } else { 10261 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10262 } 10263 10264 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 10265 // the ADDC as well as Zero. 10266 if (!isNullConstant(UmlalNode->getOperand(3))) 10267 return SDValue(); 10268 10269 if ((isNullConstant(AddeNode->getOperand(0)) && 10270 AddeNode->getOperand(1).getNode() == UmlalNode) || 10271 (AddeNode->getOperand(0).getNode() == UmlalNode && 10272 isNullConstant(AddeNode->getOperand(1)))) { 10273 SelectionDAG &DAG = DCI.DAG; 10274 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 10275 UmlalNode->getOperand(2), AddHi }; 10276 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 10277 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10278 10279 // Replace the ADDs' nodes uses by the UMAAL node's values. 10280 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 10281 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 10282 10283 // Return original node to notify the driver to stop replacing. 10284 return SDValue(AddeNode, 0); 10285 } 10286 return SDValue(); 10287 } 10288 10289 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 10290 const ARMSubtarget *Subtarget) { 10291 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10292 return SDValue(); 10293 10294 // Check that we have a pair of ADDC and ADDE as operands. 10295 // Both addends of the ADDE must be zero. 10296 SDNode* AddcNode = N->getOperand(2).getNode(); 10297 SDNode* AddeNode = N->getOperand(3).getNode(); 10298 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 10299 (AddeNode->getOpcode() == ARMISD::ADDE) && 10300 isNullConstant(AddeNode->getOperand(0)) && 10301 isNullConstant(AddeNode->getOperand(1)) && 10302 (AddeNode->getOperand(2).getNode() == AddcNode)) 10303 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 10304 DAG.getVTList(MVT::i32, MVT::i32), 10305 {N->getOperand(0), N->getOperand(1), 10306 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 10307 else 10308 return SDValue(); 10309 } 10310 10311 static SDValue PerformAddcSubcCombine(SDNode *N, 10312 TargetLowering::DAGCombinerInfo &DCI, 10313 const ARMSubtarget *Subtarget) { 10314 SelectionDAG &DAG(DCI.DAG); 10315 10316 if (N->getOpcode() == ARMISD::SUBC) { 10317 // (SUBC (ADDE 0, 0, C), 1) -> C 10318 SDValue LHS = N->getOperand(0); 10319 SDValue RHS = N->getOperand(1); 10320 if (LHS->getOpcode() == ARMISD::ADDE && 10321 isNullConstant(LHS->getOperand(0)) && 10322 isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) { 10323 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10324 } 10325 } 10326 10327 if (Subtarget->isThumb1Only()) { 10328 SDValue RHS = N->getOperand(1); 10329 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10330 int32_t imm = C->getSExtValue(); 10331 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10332 SDLoc DL(N); 10333 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10334 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10335 : ARMISD::ADDC; 10336 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10337 } 10338 } 10339 } 10340 10341 return SDValue(); 10342 } 10343 10344 static SDValue PerformAddeSubeCombine(SDNode *N, 10345 TargetLowering::DAGCombinerInfo &DCI, 10346 const ARMSubtarget *Subtarget) { 10347 if (Subtarget->isThumb1Only()) { 10348 SelectionDAG &DAG = DCI.DAG; 10349 SDValue RHS = N->getOperand(1); 10350 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10351 int64_t imm = C->getSExtValue(); 10352 if (imm < 0) { 10353 SDLoc DL(N); 10354 10355 // The with-carry-in form matches bitwise not instead of the negation. 10356 // Effectively, the inverse interpretation of the carry flag already 10357 // accounts for part of the negation. 10358 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10359 10360 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10361 : ARMISD::ADDE; 10362 return DAG.getNode(Opcode, DL, N->getVTList(), 10363 N->getOperand(0), RHS, N->getOperand(2)); 10364 } 10365 } 10366 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 10367 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 10368 } 10369 return SDValue(); 10370 } 10371 10372 /// PerformADDECombine - Target-specific dag combine transform from 10373 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10374 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10375 static SDValue PerformADDECombine(SDNode *N, 10376 TargetLowering::DAGCombinerInfo &DCI, 10377 const ARMSubtarget *Subtarget) { 10378 // Only ARM and Thumb2 support UMLAL/SMLAL. 10379 if (Subtarget->isThumb1Only()) 10380 return PerformAddeSubeCombine(N, DCI, Subtarget); 10381 10382 // Only perform the checks after legalize when the pattern is available. 10383 if (DCI.isBeforeLegalize()) return SDValue(); 10384 10385 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10386 } 10387 10388 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10389 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10390 /// called with the default operands, and if that fails, with commuted 10391 /// operands. 10392 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10393 TargetLowering::DAGCombinerInfo &DCI, 10394 const ARMSubtarget *Subtarget){ 10395 // Attempt to create vpadd for this add. 10396 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10397 return Result; 10398 10399 // Attempt to create vpaddl for this add. 10400 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10401 return Result; 10402 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10403 Subtarget)) 10404 return Result; 10405 10406 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10407 if (N0.getNode()->hasOneUse()) 10408 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10409 return Result; 10410 return SDValue(); 10411 } 10412 10413 static SDValue PerformSHLSimplify(SDNode *N, 10414 TargetLowering::DAGCombinerInfo &DCI, 10415 const ARMSubtarget *ST) { 10416 // Allow the generic combiner to identify potential bswaps. 10417 if (DCI.isBeforeLegalize()) 10418 return SDValue(); 10419 10420 // DAG combiner will fold: 10421 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10422 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 10423 // Other code patterns that can be also be modified have the following form: 10424 // b + ((a << 1) | 510) 10425 // b + ((a << 1) & 510) 10426 // b + ((a << 1) ^ 510) 10427 // b + ((a << 1) + 510) 10428 10429 // Many instructions can perform the shift for free, but it requires both 10430 // the operands to be registers. If c1 << c2 is too large, a mov immediate 10431 // instruction will needed. So, unfold back to the original pattern if: 10432 // - if c1 and c2 are small enough that they don't require mov imms. 10433 // - the user(s) of the node can perform an shl 10434 10435 // No shifted operands for 16-bit instructions. 10436 if (ST->isThumb() && ST->isThumb1Only()) 10437 return SDValue(); 10438 10439 // Check that all the users could perform the shl themselves. 10440 for (auto U : N->uses()) { 10441 switch(U->getOpcode()) { 10442 default: 10443 return SDValue(); 10444 case ISD::SUB: 10445 case ISD::ADD: 10446 case ISD::AND: 10447 case ISD::OR: 10448 case ISD::XOR: 10449 case ISD::SETCC: 10450 case ARMISD::CMP: 10451 // Check that the user isn't already using a constant because there 10452 // aren't any instructions that support an immediate operand and a 10453 // shifted operand. 10454 if (isa<ConstantSDNode>(U->getOperand(0)) || 10455 isa<ConstantSDNode>(U->getOperand(1))) 10456 return SDValue(); 10457 10458 // Check that it's not already using a shift. 10459 if (U->getOperand(0).getOpcode() == ISD::SHL || 10460 U->getOperand(1).getOpcode() == ISD::SHL) 10461 return SDValue(); 10462 break; 10463 } 10464 } 10465 10466 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 10467 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 10468 return SDValue(); 10469 10470 if (N->getOperand(0).getOpcode() != ISD::SHL) 10471 return SDValue(); 10472 10473 SDValue SHL = N->getOperand(0); 10474 10475 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10476 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 10477 if (!C1ShlC2 || !C2) 10478 return SDValue(); 10479 10480 APInt C2Int = C2->getAPIntValue(); 10481 APInt C1Int = C1ShlC2->getAPIntValue(); 10482 10483 // Check that performing a lshr will not lose any information. 10484 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 10485 C2Int.getBitWidth() - C2->getZExtValue()); 10486 if ((C1Int & Mask) != C1Int) 10487 return SDValue(); 10488 10489 // Shift the first constant. 10490 C1Int.lshrInPlace(C2Int); 10491 10492 // The immediates are encoded as an 8-bit value that can be rotated. 10493 auto LargeImm = [](const APInt &Imm) { 10494 unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros(); 10495 return Imm.getBitWidth() - Zeros > 8; 10496 }; 10497 10498 if (LargeImm(C1Int) || LargeImm(C2Int)) 10499 return SDValue(); 10500 10501 SelectionDAG &DAG = DCI.DAG; 10502 SDLoc dl(N); 10503 SDValue X = SHL.getOperand(0); 10504 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 10505 DAG.getConstant(C1Int, dl, MVT::i32)); 10506 // Shift left to compensate for the lshr of C1Int. 10507 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 10508 10509 LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); 10510 SHL.dump(); N->dump()); 10511 LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump()); 10512 10513 DAG.ReplaceAllUsesWith(SDValue(N, 0), Res); 10514 return SDValue(N, 0); 10515 } 10516 10517 10518 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10519 /// 10520 static SDValue PerformADDCombine(SDNode *N, 10521 TargetLowering::DAGCombinerInfo &DCI, 10522 const ARMSubtarget *Subtarget) { 10523 SDValue N0 = N->getOperand(0); 10524 SDValue N1 = N->getOperand(1); 10525 10526 // Only works one way, because it needs an immediate operand. 10527 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10528 return Result; 10529 10530 // First try with the default operand order. 10531 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10532 return Result; 10533 10534 // If that didn't work, try again with the operands commuted. 10535 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10536 } 10537 10538 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 10539 /// 10540 static SDValue PerformSUBCombine(SDNode *N, 10541 TargetLowering::DAGCombinerInfo &DCI) { 10542 SDValue N0 = N->getOperand(0); 10543 SDValue N1 = N->getOperand(1); 10544 10545 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10546 if (N1.getNode()->hasOneUse()) 10547 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 10548 return Result; 10549 10550 return SDValue(); 10551 } 10552 10553 /// PerformVMULCombine 10554 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 10555 /// special multiplier accumulator forwarding. 10556 /// vmul d3, d0, d2 10557 /// vmla d3, d1, d2 10558 /// is faster than 10559 /// vadd d3, d0, d1 10560 /// vmul d3, d3, d2 10561 // However, for (A + B) * (A + B), 10562 // vadd d2, d0, d1 10563 // vmul d3, d0, d2 10564 // vmla d3, d1, d2 10565 // is slower than 10566 // vadd d2, d0, d1 10567 // vmul d3, d2, d2 10568 static SDValue PerformVMULCombine(SDNode *N, 10569 TargetLowering::DAGCombinerInfo &DCI, 10570 const ARMSubtarget *Subtarget) { 10571 if (!Subtarget->hasVMLxForwarding()) 10572 return SDValue(); 10573 10574 SelectionDAG &DAG = DCI.DAG; 10575 SDValue N0 = N->getOperand(0); 10576 SDValue N1 = N->getOperand(1); 10577 unsigned Opcode = N0.getOpcode(); 10578 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10579 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10580 Opcode = N1.getOpcode(); 10581 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10582 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10583 return SDValue(); 10584 std::swap(N0, N1); 10585 } 10586 10587 if (N0 == N1) 10588 return SDValue(); 10589 10590 EVT VT = N->getValueType(0); 10591 SDLoc DL(N); 10592 SDValue N00 = N0->getOperand(0); 10593 SDValue N01 = N0->getOperand(1); 10594 return DAG.getNode(Opcode, DL, VT, 10595 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10596 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10597 } 10598 10599 static SDValue PerformMULCombine(SDNode *N, 10600 TargetLowering::DAGCombinerInfo &DCI, 10601 const ARMSubtarget *Subtarget) { 10602 SelectionDAG &DAG = DCI.DAG; 10603 10604 if (Subtarget->isThumb1Only()) 10605 return SDValue(); 10606 10607 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10608 return SDValue(); 10609 10610 EVT VT = N->getValueType(0); 10611 if (VT.is64BitVector() || VT.is128BitVector()) 10612 return PerformVMULCombine(N, DCI, Subtarget); 10613 if (VT != MVT::i32) 10614 return SDValue(); 10615 10616 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10617 if (!C) 10618 return SDValue(); 10619 10620 int64_t MulAmt = C->getSExtValue(); 10621 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10622 10623 ShiftAmt = ShiftAmt & (32 - 1); 10624 SDValue V = N->getOperand(0); 10625 SDLoc DL(N); 10626 10627 SDValue Res; 10628 MulAmt >>= ShiftAmt; 10629 10630 if (MulAmt >= 0) { 10631 if (isPowerOf2_32(MulAmt - 1)) { 10632 // (mul x, 2^N + 1) => (add (shl x, N), x) 10633 Res = DAG.getNode(ISD::ADD, DL, VT, 10634 V, 10635 DAG.getNode(ISD::SHL, DL, VT, 10636 V, 10637 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10638 MVT::i32))); 10639 } else if (isPowerOf2_32(MulAmt + 1)) { 10640 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10641 Res = DAG.getNode(ISD::SUB, DL, VT, 10642 DAG.getNode(ISD::SHL, DL, VT, 10643 V, 10644 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10645 MVT::i32)), 10646 V); 10647 } else 10648 return SDValue(); 10649 } else { 10650 uint64_t MulAmtAbs = -MulAmt; 10651 if (isPowerOf2_32(MulAmtAbs + 1)) { 10652 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10653 Res = DAG.getNode(ISD::SUB, DL, VT, 10654 V, 10655 DAG.getNode(ISD::SHL, DL, VT, 10656 V, 10657 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10658 MVT::i32))); 10659 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10660 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10661 Res = DAG.getNode(ISD::ADD, DL, VT, 10662 V, 10663 DAG.getNode(ISD::SHL, DL, VT, 10664 V, 10665 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10666 MVT::i32))); 10667 Res = DAG.getNode(ISD::SUB, DL, VT, 10668 DAG.getConstant(0, DL, MVT::i32), Res); 10669 } else 10670 return SDValue(); 10671 } 10672 10673 if (ShiftAmt != 0) 10674 Res = DAG.getNode(ISD::SHL, DL, VT, 10675 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10676 10677 // Do not add new nodes to DAG combiner worklist. 10678 DCI.CombineTo(N, Res, false); 10679 return SDValue(); 10680 } 10681 10682 static SDValue PerformANDCombine(SDNode *N, 10683 TargetLowering::DAGCombinerInfo &DCI, 10684 const ARMSubtarget *Subtarget) { 10685 // Attempt to use immediate-form VBIC 10686 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10687 SDLoc dl(N); 10688 EVT VT = N->getValueType(0); 10689 SelectionDAG &DAG = DCI.DAG; 10690 10691 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10692 return SDValue(); 10693 10694 APInt SplatBits, SplatUndef; 10695 unsigned SplatBitSize; 10696 bool HasAnyUndefs; 10697 if (BVN && 10698 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10699 if (SplatBitSize <= 64) { 10700 EVT VbicVT; 10701 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10702 SplatUndef.getZExtValue(), SplatBitSize, 10703 DAG, dl, VbicVT, VT.is128BitVector(), 10704 OtherModImm); 10705 if (Val.getNode()) { 10706 SDValue Input = 10707 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10708 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10709 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10710 } 10711 } 10712 } 10713 10714 if (!Subtarget->isThumb1Only()) { 10715 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10716 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10717 return Result; 10718 10719 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10720 return Result; 10721 } 10722 10723 return SDValue(); 10724 } 10725 10726 // Try combining OR nodes to SMULWB, SMULWT. 10727 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10728 TargetLowering::DAGCombinerInfo &DCI, 10729 const ARMSubtarget *Subtarget) { 10730 if (!Subtarget->hasV6Ops() || 10731 (Subtarget->isThumb() && 10732 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10733 return SDValue(); 10734 10735 SDValue SRL = OR->getOperand(0); 10736 SDValue SHL = OR->getOperand(1); 10737 10738 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10739 SRL = OR->getOperand(1); 10740 SHL = OR->getOperand(0); 10741 } 10742 if (!isSRL16(SRL) || !isSHL16(SHL)) 10743 return SDValue(); 10744 10745 // The first operands to the shifts need to be the two results from the 10746 // same smul_lohi node. 10747 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10748 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10749 return SDValue(); 10750 10751 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10752 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10753 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10754 return SDValue(); 10755 10756 // Now we have: 10757 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10758 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10759 // For SMUWB the 16-bit value will signed extended somehow. 10760 // For SMULWT only the SRA is required. 10761 // Check both sides of SMUL_LOHI 10762 SDValue OpS16 = SMULLOHI->getOperand(0); 10763 SDValue OpS32 = SMULLOHI->getOperand(1); 10764 10765 SelectionDAG &DAG = DCI.DAG; 10766 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10767 OpS16 = OpS32; 10768 OpS32 = SMULLOHI->getOperand(0); 10769 } 10770 10771 SDLoc dl(OR); 10772 unsigned Opcode = 0; 10773 if (isS16(OpS16, DAG)) 10774 Opcode = ARMISD::SMULWB; 10775 else if (isSRA16(OpS16)) { 10776 Opcode = ARMISD::SMULWT; 10777 OpS16 = OpS16->getOperand(0); 10778 } 10779 else 10780 return SDValue(); 10781 10782 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10783 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10784 return SDValue(OR, 0); 10785 } 10786 10787 static SDValue PerformORCombineToBFI(SDNode *N, 10788 TargetLowering::DAGCombinerInfo &DCI, 10789 const ARMSubtarget *Subtarget) { 10790 // BFI is only available on V6T2+ 10791 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10792 return SDValue(); 10793 10794 EVT VT = N->getValueType(0); 10795 SDValue N0 = N->getOperand(0); 10796 SDValue N1 = N->getOperand(1); 10797 SelectionDAG &DAG = DCI.DAG; 10798 SDLoc DL(N); 10799 // 1) or (and A, mask), val => ARMbfi A, val, mask 10800 // iff (val & mask) == val 10801 // 10802 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10803 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10804 // && mask == ~mask2 10805 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10806 // && ~mask == mask2 10807 // (i.e., copy a bitfield value into another bitfield of the same width) 10808 10809 if (VT != MVT::i32) 10810 return SDValue(); 10811 10812 SDValue N00 = N0.getOperand(0); 10813 10814 // The value and the mask need to be constants so we can verify this is 10815 // actually a bitfield set. If the mask is 0xffff, we can do better 10816 // via a movt instruction, so don't use BFI in that case. 10817 SDValue MaskOp = N0.getOperand(1); 10818 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10819 if (!MaskC) 10820 return SDValue(); 10821 unsigned Mask = MaskC->getZExtValue(); 10822 if (Mask == 0xffff) 10823 return SDValue(); 10824 SDValue Res; 10825 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10826 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10827 if (N1C) { 10828 unsigned Val = N1C->getZExtValue(); 10829 if ((Val & ~Mask) != Val) 10830 return SDValue(); 10831 10832 if (ARM::isBitFieldInvertedMask(Mask)) { 10833 Val >>= countTrailingZeros(~Mask); 10834 10835 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10836 DAG.getConstant(Val, DL, MVT::i32), 10837 DAG.getConstant(Mask, DL, MVT::i32)); 10838 10839 DCI.CombineTo(N, Res, false); 10840 // Return value from the original node to inform the combiner than N is 10841 // now dead. 10842 return SDValue(N, 0); 10843 } 10844 } else if (N1.getOpcode() == ISD::AND) { 10845 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10846 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10847 if (!N11C) 10848 return SDValue(); 10849 unsigned Mask2 = N11C->getZExtValue(); 10850 10851 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10852 // as is to match. 10853 if (ARM::isBitFieldInvertedMask(Mask) && 10854 (Mask == ~Mask2)) { 10855 // The pack halfword instruction works better for masks that fit it, 10856 // so use that when it's available. 10857 if (Subtarget->hasDSP() && 10858 (Mask == 0xffff || Mask == 0xffff0000)) 10859 return SDValue(); 10860 // 2a 10861 unsigned amt = countTrailingZeros(Mask2); 10862 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10863 DAG.getConstant(amt, DL, MVT::i32)); 10864 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10865 DAG.getConstant(Mask, DL, MVT::i32)); 10866 DCI.CombineTo(N, Res, false); 10867 // Return value from the original node to inform the combiner than N is 10868 // now dead. 10869 return SDValue(N, 0); 10870 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10871 (~Mask == Mask2)) { 10872 // The pack halfword instruction works better for masks that fit it, 10873 // so use that when it's available. 10874 if (Subtarget->hasDSP() && 10875 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10876 return SDValue(); 10877 // 2b 10878 unsigned lsb = countTrailingZeros(Mask); 10879 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10880 DAG.getConstant(lsb, DL, MVT::i32)); 10881 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10882 DAG.getConstant(Mask2, DL, MVT::i32)); 10883 DCI.CombineTo(N, Res, false); 10884 // Return value from the original node to inform the combiner than N is 10885 // now dead. 10886 return SDValue(N, 0); 10887 } 10888 } 10889 10890 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10891 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10892 ARM::isBitFieldInvertedMask(~Mask)) { 10893 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10894 // where lsb(mask) == #shamt and masked bits of B are known zero. 10895 SDValue ShAmt = N00.getOperand(1); 10896 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10897 unsigned LSB = countTrailingZeros(Mask); 10898 if (ShAmtC != LSB) 10899 return SDValue(); 10900 10901 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10902 DAG.getConstant(~Mask, DL, MVT::i32)); 10903 10904 DCI.CombineTo(N, Res, false); 10905 // Return value from the original node to inform the combiner than N is 10906 // now dead. 10907 return SDValue(N, 0); 10908 } 10909 10910 return SDValue(); 10911 } 10912 10913 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 10914 static SDValue PerformORCombine(SDNode *N, 10915 TargetLowering::DAGCombinerInfo &DCI, 10916 const ARMSubtarget *Subtarget) { 10917 // Attempt to use immediate-form VORR 10918 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10919 SDLoc dl(N); 10920 EVT VT = N->getValueType(0); 10921 SelectionDAG &DAG = DCI.DAG; 10922 10923 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10924 return SDValue(); 10925 10926 APInt SplatBits, SplatUndef; 10927 unsigned SplatBitSize; 10928 bool HasAnyUndefs; 10929 if (BVN && Subtarget->hasNEON() && 10930 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10931 if (SplatBitSize <= 64) { 10932 EVT VorrVT; 10933 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 10934 SplatUndef.getZExtValue(), SplatBitSize, 10935 DAG, dl, VorrVT, VT.is128BitVector(), 10936 OtherModImm); 10937 if (Val.getNode()) { 10938 SDValue Input = 10939 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 10940 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 10941 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 10942 } 10943 } 10944 } 10945 10946 if (!Subtarget->isThumb1Only()) { 10947 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10948 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10949 return Result; 10950 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 10951 return Result; 10952 } 10953 10954 SDValue N0 = N->getOperand(0); 10955 SDValue N1 = N->getOperand(1); 10956 10957 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 10958 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 10959 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10960 10961 // The code below optimizes (or (and X, Y), Z). 10962 // The AND operand needs to have a single user to make these optimizations 10963 // profitable. 10964 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 10965 return SDValue(); 10966 10967 APInt SplatUndef; 10968 unsigned SplatBitSize; 10969 bool HasAnyUndefs; 10970 10971 APInt SplatBits0, SplatBits1; 10972 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 10973 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 10974 // Ensure that the second operand of both ands are constants 10975 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 10976 HasAnyUndefs) && !HasAnyUndefs) { 10977 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 10978 HasAnyUndefs) && !HasAnyUndefs) { 10979 // Ensure that the bit width of the constants are the same and that 10980 // the splat arguments are logical inverses as per the pattern we 10981 // are trying to simplify. 10982 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 10983 SplatBits0 == ~SplatBits1) { 10984 // Canonicalize the vector type to make instruction selection 10985 // simpler. 10986 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 10987 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 10988 N0->getOperand(1), 10989 N0->getOperand(0), 10990 N1->getOperand(0)); 10991 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 10992 } 10993 } 10994 } 10995 } 10996 10997 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 10998 // reasonable. 10999 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 11000 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 11001 return Res; 11002 } 11003 11004 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11005 return Result; 11006 11007 return SDValue(); 11008 } 11009 11010 static SDValue PerformXORCombine(SDNode *N, 11011 TargetLowering::DAGCombinerInfo &DCI, 11012 const ARMSubtarget *Subtarget) { 11013 EVT VT = N->getValueType(0); 11014 SelectionDAG &DAG = DCI.DAG; 11015 11016 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11017 return SDValue(); 11018 11019 if (!Subtarget->isThumb1Only()) { 11020 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 11021 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 11022 return Result; 11023 11024 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 11025 return Result; 11026 } 11027 11028 return SDValue(); 11029 } 11030 11031 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 11032 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 11033 // their position in "to" (Rd). 11034 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 11035 assert(N->getOpcode() == ARMISD::BFI); 11036 11037 SDValue From = N->getOperand(1); 11038 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 11039 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 11040 11041 // If the Base came from a SHR #C, we can deduce that it is really testing bit 11042 // #C in the base of the SHR. 11043 if (From->getOpcode() == ISD::SRL && 11044 isa<ConstantSDNode>(From->getOperand(1))) { 11045 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 11046 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 11047 FromMask <<= Shift.getLimitedValue(31); 11048 From = From->getOperand(0); 11049 } 11050 11051 return From; 11052 } 11053 11054 // If A and B contain one contiguous set of bits, does A | B == A . B? 11055 // 11056 // Neither A nor B must be zero. 11057 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 11058 unsigned LastActiveBitInA = A.countTrailingZeros(); 11059 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 11060 return LastActiveBitInA - 1 == FirstActiveBitInB; 11061 } 11062 11063 static SDValue FindBFIToCombineWith(SDNode *N) { 11064 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 11065 // if one exists. 11066 APInt ToMask, FromMask; 11067 SDValue From = ParseBFI(N, ToMask, FromMask); 11068 SDValue To = N->getOperand(0); 11069 11070 // Now check for a compatible BFI to merge with. We can pass through BFIs that 11071 // aren't compatible, but not if they set the same bit in their destination as 11072 // we do (or that of any BFI we're going to combine with). 11073 SDValue V = To; 11074 APInt CombinedToMask = ToMask; 11075 while (V.getOpcode() == ARMISD::BFI) { 11076 APInt NewToMask, NewFromMask; 11077 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 11078 if (NewFrom != From) { 11079 // This BFI has a different base. Keep going. 11080 CombinedToMask |= NewToMask; 11081 V = V.getOperand(0); 11082 continue; 11083 } 11084 11085 // Do the written bits conflict with any we've seen so far? 11086 if ((NewToMask & CombinedToMask).getBoolValue()) 11087 // Conflicting bits - bail out because going further is unsafe. 11088 return SDValue(); 11089 11090 // Are the new bits contiguous when combined with the old bits? 11091 if (BitsProperlyConcatenate(ToMask, NewToMask) && 11092 BitsProperlyConcatenate(FromMask, NewFromMask)) 11093 return V; 11094 if (BitsProperlyConcatenate(NewToMask, ToMask) && 11095 BitsProperlyConcatenate(NewFromMask, FromMask)) 11096 return V; 11097 11098 // We've seen a write to some bits, so track it. 11099 CombinedToMask |= NewToMask; 11100 // Keep going... 11101 V = V.getOperand(0); 11102 } 11103 11104 return SDValue(); 11105 } 11106 11107 static SDValue PerformBFICombine(SDNode *N, 11108 TargetLowering::DAGCombinerInfo &DCI) { 11109 SDValue N1 = N->getOperand(1); 11110 if (N1.getOpcode() == ISD::AND) { 11111 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 11112 // the bits being cleared by the AND are not demanded by the BFI. 11113 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11114 if (!N11C) 11115 return SDValue(); 11116 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 11117 unsigned LSB = countTrailingZeros(~InvMask); 11118 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 11119 assert(Width < 11120 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 11121 "undefined behavior"); 11122 unsigned Mask = (1u << Width) - 1; 11123 unsigned Mask2 = N11C->getZExtValue(); 11124 if ((Mask & (~Mask2)) == 0) 11125 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 11126 N->getOperand(0), N1.getOperand(0), 11127 N->getOperand(2)); 11128 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 11129 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 11130 // Keep track of any consecutive bits set that all come from the same base 11131 // value. We can combine these together into a single BFI. 11132 SDValue CombineBFI = FindBFIToCombineWith(N); 11133 if (CombineBFI == SDValue()) 11134 return SDValue(); 11135 11136 // We've found a BFI. 11137 APInt ToMask1, FromMask1; 11138 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 11139 11140 APInt ToMask2, FromMask2; 11141 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 11142 assert(From1 == From2); 11143 (void)From2; 11144 11145 // First, unlink CombineBFI. 11146 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 11147 // Then create a new BFI, combining the two together. 11148 APInt NewFromMask = FromMask1 | FromMask2; 11149 APInt NewToMask = ToMask1 | ToMask2; 11150 11151 EVT VT = N->getValueType(0); 11152 SDLoc dl(N); 11153 11154 if (NewFromMask[0] == 0) 11155 From1 = DCI.DAG.getNode( 11156 ISD::SRL, dl, VT, From1, 11157 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 11158 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 11159 DCI.DAG.getConstant(~NewToMask, dl, VT)); 11160 } 11161 return SDValue(); 11162 } 11163 11164 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 11165 /// ARMISD::VMOVRRD. 11166 static SDValue PerformVMOVRRDCombine(SDNode *N, 11167 TargetLowering::DAGCombinerInfo &DCI, 11168 const ARMSubtarget *Subtarget) { 11169 // vmovrrd(vmovdrr x, y) -> x,y 11170 SDValue InDouble = N->getOperand(0); 11171 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 11172 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 11173 11174 // vmovrrd(load f64) -> (load i32), (load i32) 11175 SDNode *InNode = InDouble.getNode(); 11176 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 11177 InNode->getValueType(0) == MVT::f64 && 11178 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 11179 !cast<LoadSDNode>(InNode)->isVolatile()) { 11180 // TODO: Should this be done for non-FrameIndex operands? 11181 LoadSDNode *LD = cast<LoadSDNode>(InNode); 11182 11183 SelectionDAG &DAG = DCI.DAG; 11184 SDLoc DL(LD); 11185 SDValue BasePtr = LD->getBasePtr(); 11186 SDValue NewLD1 = 11187 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 11188 LD->getAlignment(), LD->getMemOperand()->getFlags()); 11189 11190 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11191 DAG.getConstant(4, DL, MVT::i32)); 11192 SDValue NewLD2 = DAG.getLoad( 11193 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 11194 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 11195 11196 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 11197 if (DCI.DAG.getDataLayout().isBigEndian()) 11198 std::swap (NewLD1, NewLD2); 11199 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 11200 return Result; 11201 } 11202 11203 return SDValue(); 11204 } 11205 11206 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 11207 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 11208 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 11209 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 11210 SDValue Op0 = N->getOperand(0); 11211 SDValue Op1 = N->getOperand(1); 11212 if (Op0.getOpcode() == ISD::BITCAST) 11213 Op0 = Op0.getOperand(0); 11214 if (Op1.getOpcode() == ISD::BITCAST) 11215 Op1 = Op1.getOperand(0); 11216 if (Op0.getOpcode() == ARMISD::VMOVRRD && 11217 Op0.getNode() == Op1.getNode() && 11218 Op0.getResNo() == 0 && Op1.getResNo() == 1) 11219 return DAG.getNode(ISD::BITCAST, SDLoc(N), 11220 N->getValueType(0), Op0.getOperand(0)); 11221 return SDValue(); 11222 } 11223 11224 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 11225 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 11226 /// i64 vector to have f64 elements, since the value can then be loaded 11227 /// directly into a VFP register. 11228 static bool hasNormalLoadOperand(SDNode *N) { 11229 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 11230 for (unsigned i = 0; i < NumElts; ++i) { 11231 SDNode *Elt = N->getOperand(i).getNode(); 11232 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 11233 return true; 11234 } 11235 return false; 11236 } 11237 11238 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 11239 /// ISD::BUILD_VECTOR. 11240 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 11241 TargetLowering::DAGCombinerInfo &DCI, 11242 const ARMSubtarget *Subtarget) { 11243 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 11244 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 11245 // into a pair of GPRs, which is fine when the value is used as a scalar, 11246 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 11247 SelectionDAG &DAG = DCI.DAG; 11248 if (N->getNumOperands() == 2) 11249 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 11250 return RV; 11251 11252 // Load i64 elements as f64 values so that type legalization does not split 11253 // them up into i32 values. 11254 EVT VT = N->getValueType(0); 11255 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 11256 return SDValue(); 11257 SDLoc dl(N); 11258 SmallVector<SDValue, 8> Ops; 11259 unsigned NumElts = VT.getVectorNumElements(); 11260 for (unsigned i = 0; i < NumElts; ++i) { 11261 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 11262 Ops.push_back(V); 11263 // Make the DAGCombiner fold the bitcast. 11264 DCI.AddToWorklist(V.getNode()); 11265 } 11266 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 11267 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 11268 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11269 } 11270 11271 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 11272 static SDValue 11273 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11274 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 11275 // At that time, we may have inserted bitcasts from integer to float. 11276 // If these bitcasts have survived DAGCombine, change the lowering of this 11277 // BUILD_VECTOR in something more vector friendly, i.e., that does not 11278 // force to use floating point types. 11279 11280 // Make sure we can change the type of the vector. 11281 // This is possible iff: 11282 // 1. The vector is only used in a bitcast to a integer type. I.e., 11283 // 1.1. Vector is used only once. 11284 // 1.2. Use is a bit convert to an integer type. 11285 // 2. The size of its operands are 32-bits (64-bits are not legal). 11286 EVT VT = N->getValueType(0); 11287 EVT EltVT = VT.getVectorElementType(); 11288 11289 // Check 1.1. and 2. 11290 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 11291 return SDValue(); 11292 11293 // By construction, the input type must be float. 11294 assert(EltVT == MVT::f32 && "Unexpected type!"); 11295 11296 // Check 1.2. 11297 SDNode *Use = *N->use_begin(); 11298 if (Use->getOpcode() != ISD::BITCAST || 11299 Use->getValueType(0).isFloatingPoint()) 11300 return SDValue(); 11301 11302 // Check profitability. 11303 // Model is, if more than half of the relevant operands are bitcast from 11304 // i32, turn the build_vector into a sequence of insert_vector_elt. 11305 // Relevant operands are everything that is not statically 11306 // (i.e., at compile time) bitcasted. 11307 unsigned NumOfBitCastedElts = 0; 11308 unsigned NumElts = VT.getVectorNumElements(); 11309 unsigned NumOfRelevantElts = NumElts; 11310 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 11311 SDValue Elt = N->getOperand(Idx); 11312 if (Elt->getOpcode() == ISD::BITCAST) { 11313 // Assume only bit cast to i32 will go away. 11314 if (Elt->getOperand(0).getValueType() == MVT::i32) 11315 ++NumOfBitCastedElts; 11316 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 11317 // Constants are statically casted, thus do not count them as 11318 // relevant operands. 11319 --NumOfRelevantElts; 11320 } 11321 11322 // Check if more than half of the elements require a non-free bitcast. 11323 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 11324 return SDValue(); 11325 11326 SelectionDAG &DAG = DCI.DAG; 11327 // Create the new vector type. 11328 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 11329 // Check if the type is legal. 11330 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11331 if (!TLI.isTypeLegal(VecVT)) 11332 return SDValue(); 11333 11334 // Combine: 11335 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 11336 // => BITCAST INSERT_VECTOR_ELT 11337 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 11338 // (BITCAST EN), N. 11339 SDValue Vec = DAG.getUNDEF(VecVT); 11340 SDLoc dl(N); 11341 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 11342 SDValue V = N->getOperand(Idx); 11343 if (V.isUndef()) 11344 continue; 11345 if (V.getOpcode() == ISD::BITCAST && 11346 V->getOperand(0).getValueType() == MVT::i32) 11347 // Fold obvious case. 11348 V = V.getOperand(0); 11349 else { 11350 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 11351 // Make the DAGCombiner fold the bitcasts. 11352 DCI.AddToWorklist(V.getNode()); 11353 } 11354 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 11355 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 11356 } 11357 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 11358 // Make the DAGCombiner fold the bitcasts. 11359 DCI.AddToWorklist(Vec.getNode()); 11360 return Vec; 11361 } 11362 11363 /// PerformInsertEltCombine - Target-specific dag combine xforms for 11364 /// ISD::INSERT_VECTOR_ELT. 11365 static SDValue PerformInsertEltCombine(SDNode *N, 11366 TargetLowering::DAGCombinerInfo &DCI) { 11367 // Bitcast an i64 load inserted into a vector to f64. 11368 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11369 EVT VT = N->getValueType(0); 11370 SDNode *Elt = N->getOperand(1).getNode(); 11371 if (VT.getVectorElementType() != MVT::i64 || 11372 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 11373 return SDValue(); 11374 11375 SelectionDAG &DAG = DCI.DAG; 11376 SDLoc dl(N); 11377 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11378 VT.getVectorNumElements()); 11379 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 11380 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 11381 // Make the DAGCombiner fold the bitcasts. 11382 DCI.AddToWorklist(Vec.getNode()); 11383 DCI.AddToWorklist(V.getNode()); 11384 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 11385 Vec, V, N->getOperand(2)); 11386 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 11387 } 11388 11389 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 11390 /// ISD::VECTOR_SHUFFLE. 11391 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 11392 // The LLVM shufflevector instruction does not require the shuffle mask 11393 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 11394 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 11395 // operands do not match the mask length, they are extended by concatenating 11396 // them with undef vectors. That is probably the right thing for other 11397 // targets, but for NEON it is better to concatenate two double-register 11398 // size vector operands into a single quad-register size vector. Do that 11399 // transformation here: 11400 // shuffle(concat(v1, undef), concat(v2, undef)) -> 11401 // shuffle(concat(v1, v2), undef) 11402 SDValue Op0 = N->getOperand(0); 11403 SDValue Op1 = N->getOperand(1); 11404 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 11405 Op1.getOpcode() != ISD::CONCAT_VECTORS || 11406 Op0.getNumOperands() != 2 || 11407 Op1.getNumOperands() != 2) 11408 return SDValue(); 11409 SDValue Concat0Op1 = Op0.getOperand(1); 11410 SDValue Concat1Op1 = Op1.getOperand(1); 11411 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 11412 return SDValue(); 11413 // Skip the transformation if any of the types are illegal. 11414 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11415 EVT VT = N->getValueType(0); 11416 if (!TLI.isTypeLegal(VT) || 11417 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 11418 !TLI.isTypeLegal(Concat1Op1.getValueType())) 11419 return SDValue(); 11420 11421 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11422 Op0.getOperand(0), Op1.getOperand(0)); 11423 // Translate the shuffle mask. 11424 SmallVector<int, 16> NewMask; 11425 unsigned NumElts = VT.getVectorNumElements(); 11426 unsigned HalfElts = NumElts/2; 11427 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11428 for (unsigned n = 0; n < NumElts; ++n) { 11429 int MaskElt = SVN->getMaskElt(n); 11430 int NewElt = -1; 11431 if (MaskElt < (int)HalfElts) 11432 NewElt = MaskElt; 11433 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 11434 NewElt = HalfElts + MaskElt - NumElts; 11435 NewMask.push_back(NewElt); 11436 } 11437 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 11438 DAG.getUNDEF(VT), NewMask); 11439 } 11440 11441 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 11442 /// NEON load/store intrinsics, and generic vector load/stores, to merge 11443 /// base address updates. 11444 /// For generic load/stores, the memory type is assumed to be a vector. 11445 /// The caller is assumed to have checked legality. 11446 static SDValue CombineBaseUpdate(SDNode *N, 11447 TargetLowering::DAGCombinerInfo &DCI) { 11448 SelectionDAG &DAG = DCI.DAG; 11449 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 11450 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 11451 const bool isStore = N->getOpcode() == ISD::STORE; 11452 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 11453 SDValue Addr = N->getOperand(AddrOpIdx); 11454 MemSDNode *MemN = cast<MemSDNode>(N); 11455 SDLoc dl(N); 11456 11457 // Search for a use of the address operand that is an increment. 11458 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11459 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11460 SDNode *User = *UI; 11461 if (User->getOpcode() != ISD::ADD || 11462 UI.getUse().getResNo() != Addr.getResNo()) 11463 continue; 11464 11465 // Check that the add is independent of the load/store. Otherwise, folding 11466 // it would create a cycle. 11467 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 11468 continue; 11469 11470 // Find the new opcode for the updating load/store. 11471 bool isLoadOp = true; 11472 bool isLaneOp = false; 11473 unsigned NewOpc = 0; 11474 unsigned NumVecs = 0; 11475 if (isIntrinsic) { 11476 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11477 switch (IntNo) { 11478 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11479 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 11480 NumVecs = 1; break; 11481 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 11482 NumVecs = 2; break; 11483 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 11484 NumVecs = 3; break; 11485 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 11486 NumVecs = 4; break; 11487 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 11488 NumVecs = 2; isLaneOp = true; break; 11489 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 11490 NumVecs = 3; isLaneOp = true; break; 11491 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 11492 NumVecs = 4; isLaneOp = true; break; 11493 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 11494 NumVecs = 1; isLoadOp = false; break; 11495 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 11496 NumVecs = 2; isLoadOp = false; break; 11497 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 11498 NumVecs = 3; isLoadOp = false; break; 11499 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 11500 NumVecs = 4; isLoadOp = false; break; 11501 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 11502 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 11503 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 11504 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 11505 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 11506 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 11507 } 11508 } else { 11509 isLaneOp = true; 11510 switch (N->getOpcode()) { 11511 default: llvm_unreachable("unexpected opcode for Neon base update"); 11512 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 11513 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 11514 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 11515 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 11516 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 11517 NumVecs = 1; isLaneOp = false; break; 11518 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 11519 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 11520 } 11521 } 11522 11523 // Find the size of memory referenced by the load/store. 11524 EVT VecTy; 11525 if (isLoadOp) { 11526 VecTy = N->getValueType(0); 11527 } else if (isIntrinsic) { 11528 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 11529 } else { 11530 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 11531 VecTy = N->getOperand(1).getValueType(); 11532 } 11533 11534 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11535 if (isLaneOp) 11536 NumBytes /= VecTy.getVectorNumElements(); 11537 11538 // If the increment is a constant, it must match the memory ref size. 11539 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11540 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 11541 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 11542 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 11543 // separate instructions that make it harder to use a non-constant update. 11544 continue; 11545 } 11546 11547 // OK, we found an ADD we can fold into the base update. 11548 // Now, create a _UPD node, taking care of not breaking alignment. 11549 11550 EVT AlignedVecTy = VecTy; 11551 unsigned Alignment = MemN->getAlignment(); 11552 11553 // If this is a less-than-standard-aligned load/store, change the type to 11554 // match the standard alignment. 11555 // The alignment is overlooked when selecting _UPD variants; and it's 11556 // easier to introduce bitcasts here than fix that. 11557 // There are 3 ways to get to this base-update combine: 11558 // - intrinsics: they are assumed to be properly aligned (to the standard 11559 // alignment of the memory type), so we don't need to do anything. 11560 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 11561 // intrinsics, so, likewise, there's nothing to do. 11562 // - generic load/store instructions: the alignment is specified as an 11563 // explicit operand, rather than implicitly as the standard alignment 11564 // of the memory type (like the intrisics). We need to change the 11565 // memory type to match the explicit alignment. That way, we don't 11566 // generate non-standard-aligned ARMISD::VLDx nodes. 11567 if (isa<LSBaseSDNode>(N)) { 11568 if (Alignment == 0) 11569 Alignment = 1; 11570 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 11571 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 11572 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 11573 assert(!isLaneOp && "Unexpected generic load/store lane."); 11574 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 11575 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 11576 } 11577 // Don't set an explicit alignment on regular load/stores that we want 11578 // to transform to VLD/VST 1_UPD nodes. 11579 // This matches the behavior of regular load/stores, which only get an 11580 // explicit alignment if the MMO alignment is larger than the standard 11581 // alignment of the memory type. 11582 // Intrinsics, however, always get an explicit alignment, set to the 11583 // alignment of the MMO. 11584 Alignment = 1; 11585 } 11586 11587 // Create the new updating load/store node. 11588 // First, create an SDVTList for the new updating node's results. 11589 EVT Tys[6]; 11590 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 11591 unsigned n; 11592 for (n = 0; n < NumResultVecs; ++n) 11593 Tys[n] = AlignedVecTy; 11594 Tys[n++] = MVT::i32; 11595 Tys[n] = MVT::Other; 11596 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 11597 11598 // Then, gather the new node's operands. 11599 SmallVector<SDValue, 8> Ops; 11600 Ops.push_back(N->getOperand(0)); // incoming chain 11601 Ops.push_back(N->getOperand(AddrOpIdx)); 11602 Ops.push_back(Inc); 11603 11604 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 11605 // Try to match the intrinsic's signature 11606 Ops.push_back(StN->getValue()); 11607 } else { 11608 // Loads (and of course intrinsics) match the intrinsics' signature, 11609 // so just add all but the alignment operand. 11610 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 11611 Ops.push_back(N->getOperand(i)); 11612 } 11613 11614 // For all node types, the alignment operand is always the last one. 11615 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 11616 11617 // If this is a non-standard-aligned STORE, the penultimate operand is the 11618 // stored value. Bitcast it to the aligned type. 11619 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 11620 SDValue &StVal = Ops[Ops.size()-2]; 11621 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 11622 } 11623 11624 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 11625 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 11626 MemN->getMemOperand()); 11627 11628 // Update the uses. 11629 SmallVector<SDValue, 5> NewResults; 11630 for (unsigned i = 0; i < NumResultVecs; ++i) 11631 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11632 11633 // If this is an non-standard-aligned LOAD, the first result is the loaded 11634 // value. Bitcast it to the expected result type. 11635 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 11636 SDValue &LdVal = NewResults[0]; 11637 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 11638 } 11639 11640 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 11641 DCI.CombineTo(N, NewResults); 11642 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11643 11644 break; 11645 } 11646 return SDValue(); 11647 } 11648 11649 static SDValue PerformVLDCombine(SDNode *N, 11650 TargetLowering::DAGCombinerInfo &DCI) { 11651 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11652 return SDValue(); 11653 11654 return CombineBaseUpdate(N, DCI); 11655 } 11656 11657 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 11658 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 11659 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11660 /// return true. 11661 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11662 SelectionDAG &DAG = DCI.DAG; 11663 EVT VT = N->getValueType(0); 11664 // vldN-dup instructions only support 64-bit vectors for N > 1. 11665 if (!VT.is64BitVector()) 11666 return false; 11667 11668 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11669 SDNode *VLD = N->getOperand(0).getNode(); 11670 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11671 return false; 11672 unsigned NumVecs = 0; 11673 unsigned NewOpc = 0; 11674 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11675 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11676 NumVecs = 2; 11677 NewOpc = ARMISD::VLD2DUP; 11678 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11679 NumVecs = 3; 11680 NewOpc = ARMISD::VLD3DUP; 11681 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11682 NumVecs = 4; 11683 NewOpc = ARMISD::VLD4DUP; 11684 } else { 11685 return false; 11686 } 11687 11688 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11689 // numbers match the load. 11690 unsigned VLDLaneNo = 11691 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11692 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11693 UI != UE; ++UI) { 11694 // Ignore uses of the chain result. 11695 if (UI.getUse().getResNo() == NumVecs) 11696 continue; 11697 SDNode *User = *UI; 11698 if (User->getOpcode() != ARMISD::VDUPLANE || 11699 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11700 return false; 11701 } 11702 11703 // Create the vldN-dup node. 11704 EVT Tys[5]; 11705 unsigned n; 11706 for (n = 0; n < NumVecs; ++n) 11707 Tys[n] = VT; 11708 Tys[n] = MVT::Other; 11709 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11710 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11711 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11712 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11713 Ops, VLDMemInt->getMemoryVT(), 11714 VLDMemInt->getMemOperand()); 11715 11716 // Update the uses. 11717 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11718 UI != UE; ++UI) { 11719 unsigned ResNo = UI.getUse().getResNo(); 11720 // Ignore uses of the chain result. 11721 if (ResNo == NumVecs) 11722 continue; 11723 SDNode *User = *UI; 11724 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11725 } 11726 11727 // Now the vldN-lane intrinsic is dead except for its chain result. 11728 // Update uses of the chain. 11729 std::vector<SDValue> VLDDupResults; 11730 for (unsigned n = 0; n < NumVecs; ++n) 11731 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11732 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11733 DCI.CombineTo(VLD, VLDDupResults); 11734 11735 return true; 11736 } 11737 11738 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11739 /// ARMISD::VDUPLANE. 11740 static SDValue PerformVDUPLANECombine(SDNode *N, 11741 TargetLowering::DAGCombinerInfo &DCI) { 11742 SDValue Op = N->getOperand(0); 11743 11744 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11745 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11746 if (CombineVLDDUP(N, DCI)) 11747 return SDValue(N, 0); 11748 11749 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11750 // redundant. Ignore bit_converts for now; element sizes are checked below. 11751 while (Op.getOpcode() == ISD::BITCAST) 11752 Op = Op.getOperand(0); 11753 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11754 return SDValue(); 11755 11756 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11757 unsigned EltSize = Op.getScalarValueSizeInBits(); 11758 // The canonical VMOV for a zero vector uses a 32-bit element size. 11759 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11760 unsigned EltBits; 11761 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11762 EltSize = 8; 11763 EVT VT = N->getValueType(0); 11764 if (EltSize > VT.getScalarSizeInBits()) 11765 return SDValue(); 11766 11767 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11768 } 11769 11770 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11771 static SDValue PerformVDUPCombine(SDNode *N, 11772 TargetLowering::DAGCombinerInfo &DCI) { 11773 SelectionDAG &DAG = DCI.DAG; 11774 SDValue Op = N->getOperand(0); 11775 11776 // Match VDUP(LOAD) -> VLD1DUP. 11777 // We match this pattern here rather than waiting for isel because the 11778 // transform is only legal for unindexed loads. 11779 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11780 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11781 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11782 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11783 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11784 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11785 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11786 Ops, LD->getMemoryVT(), 11787 LD->getMemOperand()); 11788 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11789 return VLDDup; 11790 } 11791 11792 return SDValue(); 11793 } 11794 11795 static SDValue PerformLOADCombine(SDNode *N, 11796 TargetLowering::DAGCombinerInfo &DCI) { 11797 EVT VT = N->getValueType(0); 11798 11799 // If this is a legal vector load, try to combine it into a VLD1_UPD. 11800 if (ISD::isNormalLoad(N) && VT.isVector() && 11801 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11802 return CombineBaseUpdate(N, DCI); 11803 11804 return SDValue(); 11805 } 11806 11807 /// PerformSTORECombine - Target-specific dag combine xforms for 11808 /// ISD::STORE. 11809 static SDValue PerformSTORECombine(SDNode *N, 11810 TargetLowering::DAGCombinerInfo &DCI) { 11811 StoreSDNode *St = cast<StoreSDNode>(N); 11812 if (St->isVolatile()) 11813 return SDValue(); 11814 11815 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 11816 // pack all of the elements in one place. Next, store to memory in fewer 11817 // chunks. 11818 SDValue StVal = St->getValue(); 11819 EVT VT = StVal.getValueType(); 11820 if (St->isTruncatingStore() && VT.isVector()) { 11821 SelectionDAG &DAG = DCI.DAG; 11822 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11823 EVT StVT = St->getMemoryVT(); 11824 unsigned NumElems = VT.getVectorNumElements(); 11825 assert(StVT != VT && "Cannot truncate to the same type"); 11826 unsigned FromEltSz = VT.getScalarSizeInBits(); 11827 unsigned ToEltSz = StVT.getScalarSizeInBits(); 11828 11829 // From, To sizes and ElemCount must be pow of two 11830 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 11831 11832 // We are going to use the original vector elt for storing. 11833 // Accumulated smaller vector elements must be a multiple of the store size. 11834 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 11835 11836 unsigned SizeRatio = FromEltSz / ToEltSz; 11837 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 11838 11839 // Create a type on which we perform the shuffle. 11840 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 11841 NumElems*SizeRatio); 11842 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 11843 11844 SDLoc DL(St); 11845 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 11846 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 11847 for (unsigned i = 0; i < NumElems; ++i) 11848 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 11849 ? (i + 1) * SizeRatio - 1 11850 : i * SizeRatio; 11851 11852 // Can't shuffle using an illegal type. 11853 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 11854 11855 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 11856 DAG.getUNDEF(WideVec.getValueType()), 11857 ShuffleVec); 11858 // At this point all of the data is stored at the bottom of the 11859 // register. We now need to save it to mem. 11860 11861 // Find the largest store unit 11862 MVT StoreType = MVT::i8; 11863 for (MVT Tp : MVT::integer_valuetypes()) { 11864 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 11865 StoreType = Tp; 11866 } 11867 // Didn't find a legal store type. 11868 if (!TLI.isTypeLegal(StoreType)) 11869 return SDValue(); 11870 11871 // Bitcast the original vector into a vector of store-size units 11872 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 11873 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 11874 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 11875 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 11876 SmallVector<SDValue, 8> Chains; 11877 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 11878 TLI.getPointerTy(DAG.getDataLayout())); 11879 SDValue BasePtr = St->getBasePtr(); 11880 11881 // Perform one or more big stores into memory. 11882 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 11883 for (unsigned I = 0; I < E; I++) { 11884 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 11885 StoreType, ShuffWide, 11886 DAG.getIntPtrConstant(I, DL)); 11887 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 11888 St->getPointerInfo(), St->getAlignment(), 11889 St->getMemOperand()->getFlags()); 11890 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 11891 Increment); 11892 Chains.push_back(Ch); 11893 } 11894 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11895 } 11896 11897 if (!ISD::isNormalStore(St)) 11898 return SDValue(); 11899 11900 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 11901 // ARM stores of arguments in the same cache line. 11902 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 11903 StVal.getNode()->hasOneUse()) { 11904 SelectionDAG &DAG = DCI.DAG; 11905 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 11906 SDLoc DL(St); 11907 SDValue BasePtr = St->getBasePtr(); 11908 SDValue NewST1 = DAG.getStore( 11909 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 11910 BasePtr, St->getPointerInfo(), St->getAlignment(), 11911 St->getMemOperand()->getFlags()); 11912 11913 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11914 DAG.getConstant(4, DL, MVT::i32)); 11915 return DAG.getStore(NewST1.getValue(0), DL, 11916 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 11917 OffsetPtr, St->getPointerInfo(), 11918 std::min(4U, St->getAlignment() / 2), 11919 St->getMemOperand()->getFlags()); 11920 } 11921 11922 if (StVal.getValueType() == MVT::i64 && 11923 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11924 11925 // Bitcast an i64 store extracted from a vector to f64. 11926 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11927 SelectionDAG &DAG = DCI.DAG; 11928 SDLoc dl(StVal); 11929 SDValue IntVec = StVal.getOperand(0); 11930 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11931 IntVec.getValueType().getVectorNumElements()); 11932 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 11933 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 11934 Vec, StVal.getOperand(1)); 11935 dl = SDLoc(N); 11936 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 11937 // Make the DAGCombiner fold the bitcasts. 11938 DCI.AddToWorklist(Vec.getNode()); 11939 DCI.AddToWorklist(ExtElt.getNode()); 11940 DCI.AddToWorklist(V.getNode()); 11941 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 11942 St->getPointerInfo(), St->getAlignment(), 11943 St->getMemOperand()->getFlags(), St->getAAInfo()); 11944 } 11945 11946 // If this is a legal vector store, try to combine it into a VST1_UPD. 11947 if (ISD::isNormalStore(N) && VT.isVector() && 11948 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11949 return CombineBaseUpdate(N, DCI); 11950 11951 return SDValue(); 11952 } 11953 11954 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11955 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11956 /// when the VMUL has a constant operand that is a power of 2. 11957 /// 11958 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11959 /// vmul.f32 d16, d17, d16 11960 /// vcvt.s32.f32 d16, d16 11961 /// becomes: 11962 /// vcvt.s32.f32 d16, d16, #3 11963 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11964 const ARMSubtarget *Subtarget) { 11965 if (!Subtarget->hasNEON()) 11966 return SDValue(); 11967 11968 SDValue Op = N->getOperand(0); 11969 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 11970 Op.getOpcode() != ISD::FMUL) 11971 return SDValue(); 11972 11973 SDValue ConstVec = Op->getOperand(1); 11974 if (!isa<BuildVectorSDNode>(ConstVec)) 11975 return SDValue(); 11976 11977 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 11978 uint32_t FloatBits = FloatTy.getSizeInBits(); 11979 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 11980 uint32_t IntBits = IntTy.getSizeInBits(); 11981 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11982 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11983 // These instructions only exist converting from f32 to i32. We can handle 11984 // smaller integers by generating an extra truncate, but larger ones would 11985 // be lossy. We also can't handle more then 4 lanes, since these intructions 11986 // only support v2i32/v4i32 types. 11987 return SDValue(); 11988 } 11989 11990 BitVector UndefElements; 11991 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11992 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11993 if (C == -1 || C == 0 || C > 32) 11994 return SDValue(); 11995 11996 SDLoc dl(N); 11997 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 11998 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 11999 Intrinsic::arm_neon_vcvtfp2fxu; 12000 SDValue FixConv = DAG.getNode( 12001 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12002 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 12003 DAG.getConstant(C, dl, MVT::i32)); 12004 12005 if (IntBits < FloatBits) 12006 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 12007 12008 return FixConv; 12009 } 12010 12011 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 12012 /// can replace combinations of VCVT (integer to floating-point) and VDIV 12013 /// when the VDIV has a constant operand that is a power of 2. 12014 /// 12015 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 12016 /// vcvt.f32.s32 d16, d16 12017 /// vdiv.f32 d16, d17, d16 12018 /// becomes: 12019 /// vcvt.f32.s32 d16, d16, #3 12020 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 12021 const ARMSubtarget *Subtarget) { 12022 if (!Subtarget->hasNEON()) 12023 return SDValue(); 12024 12025 SDValue Op = N->getOperand(0); 12026 unsigned OpOpcode = Op.getNode()->getOpcode(); 12027 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 12028 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 12029 return SDValue(); 12030 12031 SDValue ConstVec = N->getOperand(1); 12032 if (!isa<BuildVectorSDNode>(ConstVec)) 12033 return SDValue(); 12034 12035 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 12036 uint32_t FloatBits = FloatTy.getSizeInBits(); 12037 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 12038 uint32_t IntBits = IntTy.getSizeInBits(); 12039 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 12040 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 12041 // These instructions only exist converting from i32 to f32. We can handle 12042 // smaller integers by generating an extra extend, but larger ones would 12043 // be lossy. We also can't handle more then 4 lanes, since these intructions 12044 // only support v2i32/v4i32 types. 12045 return SDValue(); 12046 } 12047 12048 BitVector UndefElements; 12049 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12050 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12051 if (C == -1 || C == 0 || C > 32) 12052 return SDValue(); 12053 12054 SDLoc dl(N); 12055 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 12056 SDValue ConvInput = Op.getOperand(0); 12057 if (IntBits < FloatBits) 12058 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 12059 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12060 ConvInput); 12061 12062 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 12063 Intrinsic::arm_neon_vcvtfxu2fp; 12064 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 12065 Op.getValueType(), 12066 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 12067 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 12068 } 12069 12070 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 12071 /// operand of a vector shift operation, where all the elements of the 12072 /// build_vector must have the same constant integer value. 12073 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 12074 // Ignore bit_converts. 12075 while (Op.getOpcode() == ISD::BITCAST) 12076 Op = Op.getOperand(0); 12077 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 12078 APInt SplatBits, SplatUndef; 12079 unsigned SplatBitSize; 12080 bool HasAnyUndefs; 12081 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 12082 HasAnyUndefs, ElementBits) || 12083 SplatBitSize > ElementBits) 12084 return false; 12085 Cnt = SplatBits.getSExtValue(); 12086 return true; 12087 } 12088 12089 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 12090 /// operand of a vector shift left operation. That value must be in the range: 12091 /// 0 <= Value < ElementBits for a left shift; or 12092 /// 0 <= Value <= ElementBits for a long left shift. 12093 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, 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 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 12099 } 12100 12101 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 12102 /// operand of a vector shift right operation. For a shift opcode, the value 12103 /// is positive, but for an intrinsic the value count must be negative. The 12104 /// absolute value must be in the range: 12105 /// 1 <= |Value| <= ElementBits for a right shift; or 12106 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 12107 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 12108 int64_t &Cnt) { 12109 assert(VT.isVector() && "vector shift count is not a vector type"); 12110 int64_t ElementBits = VT.getScalarSizeInBits(); 12111 if (! getVShiftImm(Op, ElementBits, Cnt)) 12112 return false; 12113 if (!isIntrinsic) 12114 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 12115 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 12116 Cnt = -Cnt; 12117 return true; 12118 } 12119 return false; 12120 } 12121 12122 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 12123 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 12124 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12125 switch (IntNo) { 12126 default: 12127 // Don't do anything for most intrinsics. 12128 break; 12129 12130 // Vector shifts: check for immediate versions and lower them. 12131 // Note: This is done during DAG combining instead of DAG legalizing because 12132 // the build_vectors for 64-bit vector element shift counts are generally 12133 // not legal, and it is hard to see their values after they get legalized to 12134 // loads from a constant pool. 12135 case Intrinsic::arm_neon_vshifts: 12136 case Intrinsic::arm_neon_vshiftu: 12137 case Intrinsic::arm_neon_vrshifts: 12138 case Intrinsic::arm_neon_vrshiftu: 12139 case Intrinsic::arm_neon_vrshiftn: 12140 case Intrinsic::arm_neon_vqshifts: 12141 case Intrinsic::arm_neon_vqshiftu: 12142 case Intrinsic::arm_neon_vqshiftsu: 12143 case Intrinsic::arm_neon_vqshiftns: 12144 case Intrinsic::arm_neon_vqshiftnu: 12145 case Intrinsic::arm_neon_vqshiftnsu: 12146 case Intrinsic::arm_neon_vqrshiftns: 12147 case Intrinsic::arm_neon_vqrshiftnu: 12148 case Intrinsic::arm_neon_vqrshiftnsu: { 12149 EVT VT = N->getOperand(1).getValueType(); 12150 int64_t Cnt; 12151 unsigned VShiftOpc = 0; 12152 12153 switch (IntNo) { 12154 case Intrinsic::arm_neon_vshifts: 12155 case Intrinsic::arm_neon_vshiftu: 12156 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 12157 VShiftOpc = ARMISD::VSHL; 12158 break; 12159 } 12160 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 12161 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 12162 ARMISD::VSHRs : ARMISD::VSHRu); 12163 break; 12164 } 12165 return SDValue(); 12166 12167 case Intrinsic::arm_neon_vrshifts: 12168 case Intrinsic::arm_neon_vrshiftu: 12169 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 12170 break; 12171 return SDValue(); 12172 12173 case Intrinsic::arm_neon_vqshifts: 12174 case Intrinsic::arm_neon_vqshiftu: 12175 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12176 break; 12177 return SDValue(); 12178 12179 case Intrinsic::arm_neon_vqshiftsu: 12180 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12181 break; 12182 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 12183 12184 case Intrinsic::arm_neon_vrshiftn: 12185 case Intrinsic::arm_neon_vqshiftns: 12186 case Intrinsic::arm_neon_vqshiftnu: 12187 case Intrinsic::arm_neon_vqshiftnsu: 12188 case Intrinsic::arm_neon_vqrshiftns: 12189 case Intrinsic::arm_neon_vqrshiftnu: 12190 case Intrinsic::arm_neon_vqrshiftnsu: 12191 // Narrowing shifts require an immediate right shift. 12192 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 12193 break; 12194 llvm_unreachable("invalid shift count for narrowing vector shift " 12195 "intrinsic"); 12196 12197 default: 12198 llvm_unreachable("unhandled vector shift"); 12199 } 12200 12201 switch (IntNo) { 12202 case Intrinsic::arm_neon_vshifts: 12203 case Intrinsic::arm_neon_vshiftu: 12204 // Opcode already set above. 12205 break; 12206 case Intrinsic::arm_neon_vrshifts: 12207 VShiftOpc = ARMISD::VRSHRs; break; 12208 case Intrinsic::arm_neon_vrshiftu: 12209 VShiftOpc = ARMISD::VRSHRu; break; 12210 case Intrinsic::arm_neon_vrshiftn: 12211 VShiftOpc = ARMISD::VRSHRN; break; 12212 case Intrinsic::arm_neon_vqshifts: 12213 VShiftOpc = ARMISD::VQSHLs; break; 12214 case Intrinsic::arm_neon_vqshiftu: 12215 VShiftOpc = ARMISD::VQSHLu; break; 12216 case Intrinsic::arm_neon_vqshiftsu: 12217 VShiftOpc = ARMISD::VQSHLsu; break; 12218 case Intrinsic::arm_neon_vqshiftns: 12219 VShiftOpc = ARMISD::VQSHRNs; break; 12220 case Intrinsic::arm_neon_vqshiftnu: 12221 VShiftOpc = ARMISD::VQSHRNu; break; 12222 case Intrinsic::arm_neon_vqshiftnsu: 12223 VShiftOpc = ARMISD::VQSHRNsu; break; 12224 case Intrinsic::arm_neon_vqrshiftns: 12225 VShiftOpc = ARMISD::VQRSHRNs; break; 12226 case Intrinsic::arm_neon_vqrshiftnu: 12227 VShiftOpc = ARMISD::VQRSHRNu; break; 12228 case Intrinsic::arm_neon_vqrshiftnsu: 12229 VShiftOpc = ARMISD::VQRSHRNsu; break; 12230 } 12231 12232 SDLoc dl(N); 12233 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12234 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 12235 } 12236 12237 case Intrinsic::arm_neon_vshiftins: { 12238 EVT VT = N->getOperand(1).getValueType(); 12239 int64_t Cnt; 12240 unsigned VShiftOpc = 0; 12241 12242 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 12243 VShiftOpc = ARMISD::VSLI; 12244 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 12245 VShiftOpc = ARMISD::VSRI; 12246 else { 12247 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 12248 } 12249 12250 SDLoc dl(N); 12251 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12252 N->getOperand(1), N->getOperand(2), 12253 DAG.getConstant(Cnt, dl, MVT::i32)); 12254 } 12255 12256 case Intrinsic::arm_neon_vqrshifts: 12257 case Intrinsic::arm_neon_vqrshiftu: 12258 // No immediate versions of these to check for. 12259 break; 12260 } 12261 12262 return SDValue(); 12263 } 12264 12265 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 12266 /// lowers them. As with the vector shift intrinsics, this is done during DAG 12267 /// combining instead of DAG legalizing because the build_vectors for 64-bit 12268 /// vector element shift counts are generally not legal, and it is hard to see 12269 /// their values after they get legalized to loads from a constant pool. 12270 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 12271 const ARMSubtarget *ST) { 12272 EVT VT = N->getValueType(0); 12273 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 12274 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 12275 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 12276 SDValue N1 = N->getOperand(1); 12277 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12278 SDValue N0 = N->getOperand(0); 12279 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 12280 DAG.MaskedValueIsZero(N0.getOperand(0), 12281 APInt::getHighBitsSet(32, 16))) 12282 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 12283 } 12284 } 12285 12286 // Nothing to be done for scalar shifts. 12287 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12288 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 12289 return SDValue(); 12290 12291 assert(ST->hasNEON() && "unexpected vector shift"); 12292 int64_t Cnt; 12293 12294 switch (N->getOpcode()) { 12295 default: llvm_unreachable("unexpected shift opcode"); 12296 12297 case ISD::SHL: 12298 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 12299 SDLoc dl(N); 12300 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 12301 DAG.getConstant(Cnt, dl, MVT::i32)); 12302 } 12303 break; 12304 12305 case ISD::SRA: 12306 case ISD::SRL: 12307 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 12308 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 12309 ARMISD::VSHRs : ARMISD::VSHRu); 12310 SDLoc dl(N); 12311 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 12312 DAG.getConstant(Cnt, dl, MVT::i32)); 12313 } 12314 } 12315 return SDValue(); 12316 } 12317 12318 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 12319 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 12320 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 12321 const ARMSubtarget *ST) { 12322 SDValue N0 = N->getOperand(0); 12323 12324 // Check for sign- and zero-extensions of vector extract operations of 8- 12325 // and 16-bit vector elements. NEON supports these directly. They are 12326 // handled during DAG combining because type legalization will promote them 12327 // to 32-bit types and it is messy to recognize the operations after that. 12328 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12329 SDValue Vec = N0.getOperand(0); 12330 SDValue Lane = N0.getOperand(1); 12331 EVT VT = N->getValueType(0); 12332 EVT EltVT = N0.getValueType(); 12333 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12334 12335 if (VT == MVT::i32 && 12336 (EltVT == MVT::i8 || EltVT == MVT::i16) && 12337 TLI.isTypeLegal(Vec.getValueType()) && 12338 isa<ConstantSDNode>(Lane)) { 12339 12340 unsigned Opc = 0; 12341 switch (N->getOpcode()) { 12342 default: llvm_unreachable("unexpected opcode"); 12343 case ISD::SIGN_EXTEND: 12344 Opc = ARMISD::VGETLANEs; 12345 break; 12346 case ISD::ZERO_EXTEND: 12347 case ISD::ANY_EXTEND: 12348 Opc = ARMISD::VGETLANEu; 12349 break; 12350 } 12351 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 12352 } 12353 } 12354 12355 return SDValue(); 12356 } 12357 12358 static const APInt *isPowerOf2Constant(SDValue V) { 12359 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 12360 if (!C) 12361 return nullptr; 12362 const APInt *CV = &C->getAPIntValue(); 12363 return CV->isPowerOf2() ? CV : nullptr; 12364 } 12365 12366 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 12367 // If we have a CMOV, OR and AND combination such as: 12368 // if (x & CN) 12369 // y |= CM; 12370 // 12371 // And: 12372 // * CN is a single bit; 12373 // * All bits covered by CM are known zero in y 12374 // 12375 // Then we can convert this into a sequence of BFI instructions. This will 12376 // always be a win if CM is a single bit, will always be no worse than the 12377 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 12378 // three bits (due to the extra IT instruction). 12379 12380 SDValue Op0 = CMOV->getOperand(0); 12381 SDValue Op1 = CMOV->getOperand(1); 12382 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 12383 auto CC = CCNode->getAPIntValue().getLimitedValue(); 12384 SDValue CmpZ = CMOV->getOperand(4); 12385 12386 // The compare must be against zero. 12387 if (!isNullConstant(CmpZ->getOperand(1))) 12388 return SDValue(); 12389 12390 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 12391 SDValue And = CmpZ->getOperand(0); 12392 if (And->getOpcode() != ISD::AND) 12393 return SDValue(); 12394 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 12395 if (!AndC) 12396 return SDValue(); 12397 SDValue X = And->getOperand(0); 12398 12399 if (CC == ARMCC::EQ) { 12400 // We're performing an "equal to zero" compare. Swap the operands so we 12401 // canonicalize on a "not equal to zero" compare. 12402 std::swap(Op0, Op1); 12403 } else { 12404 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 12405 } 12406 12407 if (Op1->getOpcode() != ISD::OR) 12408 return SDValue(); 12409 12410 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 12411 if (!OrC) 12412 return SDValue(); 12413 SDValue Y = Op1->getOperand(0); 12414 12415 if (Op0 != Y) 12416 return SDValue(); 12417 12418 // Now, is it profitable to continue? 12419 APInt OrCI = OrC->getAPIntValue(); 12420 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 12421 if (OrCI.countPopulation() > Heuristic) 12422 return SDValue(); 12423 12424 // Lastly, can we determine that the bits defined by OrCI 12425 // are zero in Y? 12426 KnownBits Known; 12427 DAG.computeKnownBits(Y, Known); 12428 if ((OrCI & Known.Zero) != OrCI) 12429 return SDValue(); 12430 12431 // OK, we can do the combine. 12432 SDValue V = Y; 12433 SDLoc dl(X); 12434 EVT VT = X.getValueType(); 12435 unsigned BitInX = AndC->logBase2(); 12436 12437 if (BitInX != 0) { 12438 // We must shift X first. 12439 X = DAG.getNode(ISD::SRL, dl, VT, X, 12440 DAG.getConstant(BitInX, dl, VT)); 12441 } 12442 12443 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 12444 BitInY < NumActiveBits; ++BitInY) { 12445 if (OrCI[BitInY] == 0) 12446 continue; 12447 APInt Mask(VT.getSizeInBits(), 0); 12448 Mask.setBit(BitInY); 12449 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 12450 // Confusingly, the operand is an *inverted* mask. 12451 DAG.getConstant(~Mask, dl, VT)); 12452 } 12453 12454 return V; 12455 } 12456 12457 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 12458 SDValue 12459 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 12460 SDValue Cmp = N->getOperand(4); 12461 if (Cmp.getOpcode() != ARMISD::CMPZ) 12462 // Only looking at NE cases. 12463 return SDValue(); 12464 12465 EVT VT = N->getValueType(0); 12466 SDLoc dl(N); 12467 SDValue LHS = Cmp.getOperand(0); 12468 SDValue RHS = Cmp.getOperand(1); 12469 SDValue Chain = N->getOperand(0); 12470 SDValue BB = N->getOperand(1); 12471 SDValue ARMcc = N->getOperand(2); 12472 ARMCC::CondCodes CC = 12473 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12474 12475 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 12476 // -> (brcond Chain BB CC CPSR Cmp) 12477 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 12478 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 12479 LHS->getOperand(0)->hasOneUse()) { 12480 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 12481 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 12482 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12483 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12484 if ((LHS00C && LHS00C->getZExtValue() == 0) && 12485 (LHS01C && LHS01C->getZExtValue() == 1) && 12486 (LHS1C && LHS1C->getZExtValue() == 1) && 12487 (RHSC && RHSC->getZExtValue() == 0)) { 12488 return DAG.getNode( 12489 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 12490 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 12491 } 12492 } 12493 12494 return SDValue(); 12495 } 12496 12497 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 12498 SDValue 12499 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 12500 SDValue Cmp = N->getOperand(4); 12501 if (Cmp.getOpcode() != ARMISD::CMPZ) 12502 // Only looking at EQ and NE cases. 12503 return SDValue(); 12504 12505 EVT VT = N->getValueType(0); 12506 SDLoc dl(N); 12507 SDValue LHS = Cmp.getOperand(0); 12508 SDValue RHS = Cmp.getOperand(1); 12509 SDValue FalseVal = N->getOperand(0); 12510 SDValue TrueVal = N->getOperand(1); 12511 SDValue ARMcc = N->getOperand(2); 12512 ARMCC::CondCodes CC = 12513 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12514 12515 // BFI is only available on V6T2+. 12516 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 12517 SDValue R = PerformCMOVToBFICombine(N, DAG); 12518 if (R) 12519 return R; 12520 } 12521 12522 // Simplify 12523 // mov r1, r0 12524 // cmp r1, x 12525 // mov r0, y 12526 // moveq r0, x 12527 // to 12528 // cmp r0, x 12529 // movne r0, y 12530 // 12531 // mov r1, r0 12532 // cmp r1, x 12533 // mov r0, x 12534 // movne r0, y 12535 // to 12536 // cmp r0, x 12537 // movne r0, y 12538 /// FIXME: Turn this into a target neutral optimization? 12539 SDValue Res; 12540 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 12541 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 12542 N->getOperand(3), Cmp); 12543 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 12544 SDValue ARMcc; 12545 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 12546 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 12547 N->getOperand(3), NewCmp); 12548 } 12549 12550 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 12551 // -> (cmov F T CC CPSR Cmp) 12552 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 12553 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 12554 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12555 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12556 if ((LHS0C && LHS0C->getZExtValue() == 0) && 12557 (LHS1C && LHS1C->getZExtValue() == 1) && 12558 (RHSC && RHSC->getZExtValue() == 0)) { 12559 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 12560 LHS->getOperand(2), LHS->getOperand(3), 12561 LHS->getOperand(4)); 12562 } 12563 } 12564 12565 if (!VT.isInteger()) 12566 return SDValue(); 12567 12568 // Materialize a boolean comparison for integers so we can avoid branching. 12569 if (isNullConstant(FalseVal)) { 12570 if (CC == ARMCC::EQ && isOneConstant(TrueVal)) { 12571 if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) { 12572 // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it 12573 // right 5 bits will make that 32 be 1, otherwise it will be 0. 12574 // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5 12575 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12576 Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub), 12577 DAG.getConstant(5, dl, MVT::i32)); 12578 } else { 12579 // CMOV 0, 1, ==, (CMPZ x, y) -> 12580 // (ADDCARRY (SUB x, y), t:0, t:1) 12581 // where t = (SUBCARRY 0, (SUB x, y), 0) 12582 // 12583 // The SUBCARRY computes 0 - (x - y) and this will give a borrow when 12584 // x != y. In other words, a carry C == 1 when x == y, C == 0 12585 // otherwise. 12586 // The final ADDCARRY computes 12587 // x - y + (0 - (x - y)) + C == C 12588 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12589 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12590 SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub); 12591 // ISD::SUBCARRY returns a borrow but we want the carry here 12592 // actually. 12593 SDValue Carry = 12594 DAG.getNode(ISD::SUB, dl, MVT::i32, 12595 DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1)); 12596 Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry); 12597 } 12598 } else if (CC == ARMCC::NE && LHS != RHS && 12599 (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) { 12600 // This seems pointless but will allow us to combine it further below. 12601 // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUB x, y), z, !=, (CMPZ x, y) 12602 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12603 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc, 12604 N->getOperand(3), Cmp); 12605 } 12606 } else if (isNullConstant(TrueVal)) { 12607 if (CC == ARMCC::EQ && LHS != RHS && 12608 (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) { 12609 // This seems pointless but will allow us to combine it further below 12610 // Note that we change == for != as this is the dual for the case above. 12611 // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUB x, y), z, !=, (CMPZ x, y) 12612 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS); 12613 Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal, 12614 DAG.getConstant(ARMCC::NE, dl, MVT::i32), 12615 N->getOperand(3), Cmp); 12616 } 12617 } 12618 12619 // On Thumb1, the DAG above may be further combined if z is a power of 2 12620 // (z == 2 ^ K). 12621 // CMOV (SUB x, y), z, !=, (CMPZ x, y) -> 12622 // merge t3, t4 12623 // where t1 = (SUBCARRY (SUB x, y), z, 0) 12624 // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1) 12625 // t3 = if K != 0 then (SHL t2:0, K) else t2:0 12626 // t4 = (SUB 1, t2:1) [ we want a carry, not a borrow ] 12627 const APInt *TrueConst; 12628 if (Subtarget->isThumb1Only() && CC == ARMCC::NE && 12629 (FalseVal.getOpcode() == ISD::SUB) && (FalseVal.getOperand(0) == LHS) && 12630 (FalseVal.getOperand(1) == RHS) && 12631 (TrueConst = isPowerOf2Constant(TrueVal))) { 12632 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12633 unsigned ShiftAmount = TrueConst->logBase2(); 12634 if (ShiftAmount) 12635 TrueVal = DAG.getConstant(1, dl, VT); 12636 SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal); 12637 Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1)); 12638 // Make it a carry, not a borrow. 12639 SDValue Carry = DAG.getNode( 12640 ISD::SUB, dl, VT, DAG.getConstant(1, dl, MVT::i32), Res.getValue(1)); 12641 Res = DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Res, Carry); 12642 12643 if (ShiftAmount) 12644 Res = DAG.getNode(ISD::SHL, dl, VT, Res, 12645 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 12646 } 12647 12648 if (Res.getNode()) { 12649 KnownBits Known; 12650 DAG.computeKnownBits(SDValue(N,0), Known); 12651 // Capture demanded bits information that would be otherwise lost. 12652 if (Known.Zero == 0xfffffffe) 12653 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12654 DAG.getValueType(MVT::i1)); 12655 else if (Known.Zero == 0xffffff00) 12656 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12657 DAG.getValueType(MVT::i8)); 12658 else if (Known.Zero == 0xffff0000) 12659 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12660 DAG.getValueType(MVT::i16)); 12661 } 12662 12663 return Res; 12664 } 12665 12666 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 12667 DAGCombinerInfo &DCI) const { 12668 switch (N->getOpcode()) { 12669 default: break; 12670 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 12671 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 12672 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 12673 case ISD::SUB: return PerformSUBCombine(N, DCI); 12674 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 12675 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 12676 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 12677 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 12678 case ARMISD::ADDC: 12679 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 12680 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 12681 case ARMISD::BFI: return PerformBFICombine(N, DCI); 12682 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 12683 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 12684 case ISD::STORE: return PerformSTORECombine(N, DCI); 12685 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 12686 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 12687 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 12688 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 12689 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 12690 case ISD::FP_TO_SINT: 12691 case ISD::FP_TO_UINT: 12692 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 12693 case ISD::FDIV: 12694 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 12695 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 12696 case ISD::SHL: 12697 case ISD::SRA: 12698 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 12699 case ISD::SIGN_EXTEND: 12700 case ISD::ZERO_EXTEND: 12701 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 12702 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 12703 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 12704 case ISD::LOAD: return PerformLOADCombine(N, DCI); 12705 case ARMISD::VLD1DUP: 12706 case ARMISD::VLD2DUP: 12707 case ARMISD::VLD3DUP: 12708 case ARMISD::VLD4DUP: 12709 return PerformVLDCombine(N, DCI); 12710 case ARMISD::BUILD_VECTOR: 12711 return PerformARMBUILD_VECTORCombine(N, DCI); 12712 case ARMISD::SMULWB: { 12713 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12714 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12715 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12716 return SDValue(); 12717 break; 12718 } 12719 case ARMISD::SMULWT: { 12720 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12721 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12722 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12723 return SDValue(); 12724 break; 12725 } 12726 case ARMISD::SMLALBB: { 12727 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12728 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12729 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12730 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12731 return SDValue(); 12732 break; 12733 } 12734 case ARMISD::SMLALBT: { 12735 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 12736 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12737 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 12738 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12739 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 12740 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12741 return SDValue(); 12742 break; 12743 } 12744 case ARMISD::SMLALTB: { 12745 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12746 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12747 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12748 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12749 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12750 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12751 return SDValue(); 12752 break; 12753 } 12754 case ARMISD::SMLALTT: { 12755 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12756 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12757 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12758 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12759 return SDValue(); 12760 break; 12761 } 12762 case ISD::INTRINSIC_VOID: 12763 case ISD::INTRINSIC_W_CHAIN: 12764 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12765 case Intrinsic::arm_neon_vld1: 12766 case Intrinsic::arm_neon_vld1x2: 12767 case Intrinsic::arm_neon_vld1x3: 12768 case Intrinsic::arm_neon_vld1x4: 12769 case Intrinsic::arm_neon_vld2: 12770 case Intrinsic::arm_neon_vld3: 12771 case Intrinsic::arm_neon_vld4: 12772 case Intrinsic::arm_neon_vld2lane: 12773 case Intrinsic::arm_neon_vld3lane: 12774 case Intrinsic::arm_neon_vld4lane: 12775 case Intrinsic::arm_neon_vld2dup: 12776 case Intrinsic::arm_neon_vld3dup: 12777 case Intrinsic::arm_neon_vld4dup: 12778 case Intrinsic::arm_neon_vst1: 12779 case Intrinsic::arm_neon_vst1x2: 12780 case Intrinsic::arm_neon_vst1x3: 12781 case Intrinsic::arm_neon_vst1x4: 12782 case Intrinsic::arm_neon_vst2: 12783 case Intrinsic::arm_neon_vst3: 12784 case Intrinsic::arm_neon_vst4: 12785 case Intrinsic::arm_neon_vst2lane: 12786 case Intrinsic::arm_neon_vst3lane: 12787 case Intrinsic::arm_neon_vst4lane: 12788 return PerformVLDCombine(N, DCI); 12789 default: break; 12790 } 12791 break; 12792 } 12793 return SDValue(); 12794 } 12795 12796 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 12797 EVT VT) const { 12798 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 12799 } 12800 12801 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12802 unsigned, 12803 unsigned, 12804 bool *Fast) const { 12805 // Depends what it gets converted into if the type is weird. 12806 if (!VT.isSimple()) 12807 return false; 12808 12809 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 12810 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 12811 12812 switch (VT.getSimpleVT().SimpleTy) { 12813 default: 12814 return false; 12815 case MVT::i8: 12816 case MVT::i16: 12817 case MVT::i32: { 12818 // Unaligned access can use (for example) LRDB, LRDH, LDR 12819 if (AllowsUnaligned) { 12820 if (Fast) 12821 *Fast = Subtarget->hasV7Ops(); 12822 return true; 12823 } 12824 return false; 12825 } 12826 case MVT::f64: 12827 case MVT::v2f64: { 12828 // For any little-endian targets with neon, we can support unaligned ld/st 12829 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 12830 // A big-endian target may also explicitly support unaligned accesses 12831 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 12832 if (Fast) 12833 *Fast = true; 12834 return true; 12835 } 12836 return false; 12837 } 12838 } 12839 } 12840 12841 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 12842 unsigned AlignCheck) { 12843 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 12844 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 12845 } 12846 12847 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 12848 unsigned DstAlign, unsigned SrcAlign, 12849 bool IsMemset, bool ZeroMemset, 12850 bool MemcpyStrSrc, 12851 MachineFunction &MF) const { 12852 const Function &F = MF.getFunction(); 12853 12854 // See if we can use NEON instructions for this... 12855 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 12856 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 12857 bool Fast; 12858 if (Size >= 16 && 12859 (memOpAlign(SrcAlign, DstAlign, 16) || 12860 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 12861 return MVT::v2f64; 12862 } else if (Size >= 8 && 12863 (memOpAlign(SrcAlign, DstAlign, 8) || 12864 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 12865 Fast))) { 12866 return MVT::f64; 12867 } 12868 } 12869 12870 // Let the target-independent logic figure it out. 12871 return MVT::Other; 12872 } 12873 12874 // 64-bit integers are split into their high and low parts and held in two 12875 // different registers, so the trunc is free since the low register can just 12876 // be used. 12877 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 12878 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 12879 return false; 12880 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 12881 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 12882 return (SrcBits == 64 && DestBits == 32); 12883 } 12884 12885 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 12886 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 12887 !DstVT.isInteger()) 12888 return false; 12889 unsigned SrcBits = SrcVT.getSizeInBits(); 12890 unsigned DestBits = DstVT.getSizeInBits(); 12891 return (SrcBits == 64 && DestBits == 32); 12892 } 12893 12894 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12895 if (Val.getOpcode() != ISD::LOAD) 12896 return false; 12897 12898 EVT VT1 = Val.getValueType(); 12899 if (!VT1.isSimple() || !VT1.isInteger() || 12900 !VT2.isSimple() || !VT2.isInteger()) 12901 return false; 12902 12903 switch (VT1.getSimpleVT().SimpleTy) { 12904 default: break; 12905 case MVT::i1: 12906 case MVT::i8: 12907 case MVT::i16: 12908 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 12909 return true; 12910 } 12911 12912 return false; 12913 } 12914 12915 bool ARMTargetLowering::isFNegFree(EVT VT) const { 12916 if (!VT.isSimple()) 12917 return false; 12918 12919 // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that 12920 // negate values directly (fneg is free). So, we don't want to let the DAG 12921 // combiner rewrite fneg into xors and some other instructions. For f16 and 12922 // FullFP16 argument passing, some bitcast nodes may be introduced, 12923 // triggering this DAG combine rewrite, so we are avoiding that with this. 12924 switch (VT.getSimpleVT().SimpleTy) { 12925 default: break; 12926 case MVT::f16: 12927 return Subtarget->hasFullFP16(); 12928 } 12929 12930 return false; 12931 } 12932 12933 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 12934 EVT VT = ExtVal.getValueType(); 12935 12936 if (!isTypeLegal(VT)) 12937 return false; 12938 12939 // Don't create a loadext if we can fold the extension into a wide/long 12940 // instruction. 12941 // If there's more than one user instruction, the loadext is desirable no 12942 // matter what. There can be two uses by the same instruction. 12943 if (ExtVal->use_empty() || 12944 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 12945 return true; 12946 12947 SDNode *U = *ExtVal->use_begin(); 12948 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 12949 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 12950 return false; 12951 12952 return true; 12953 } 12954 12955 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 12956 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12957 return false; 12958 12959 if (!isTypeLegal(EVT::getEVT(Ty1))) 12960 return false; 12961 12962 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 12963 12964 // Assuming the caller doesn't have a zeroext or signext return parameter, 12965 // truncation all the way down to i1 is valid. 12966 return true; 12967 } 12968 12969 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 12970 const AddrMode &AM, Type *Ty, 12971 unsigned AS) const { 12972 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 12973 if (Subtarget->hasFPAO()) 12974 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 12975 return 0; 12976 } 12977 return -1; 12978 } 12979 12980 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 12981 if (V < 0) 12982 return false; 12983 12984 unsigned Scale = 1; 12985 switch (VT.getSimpleVT().SimpleTy) { 12986 default: return false; 12987 case MVT::i1: 12988 case MVT::i8: 12989 // Scale == 1; 12990 break; 12991 case MVT::i16: 12992 // Scale == 2; 12993 Scale = 2; 12994 break; 12995 case MVT::i32: 12996 // Scale == 4; 12997 Scale = 4; 12998 break; 12999 } 13000 13001 if ((V & (Scale - 1)) != 0) 13002 return false; 13003 V /= Scale; 13004 return V == (V & ((1LL << 5) - 1)); 13005 } 13006 13007 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 13008 const ARMSubtarget *Subtarget) { 13009 bool isNeg = false; 13010 if (V < 0) { 13011 isNeg = true; 13012 V = - V; 13013 } 13014 13015 switch (VT.getSimpleVT().SimpleTy) { 13016 default: return false; 13017 case MVT::i1: 13018 case MVT::i8: 13019 case MVT::i16: 13020 case MVT::i32: 13021 // + imm12 or - imm8 13022 if (isNeg) 13023 return V == (V & ((1LL << 8) - 1)); 13024 return V == (V & ((1LL << 12) - 1)); 13025 case MVT::f32: 13026 case MVT::f64: 13027 // Same as ARM mode. FIXME: NEON? 13028 if (!Subtarget->hasVFP2()) 13029 return false; 13030 if ((V & 3) != 0) 13031 return false; 13032 V >>= 2; 13033 return V == (V & ((1LL << 8) - 1)); 13034 } 13035 } 13036 13037 /// isLegalAddressImmediate - Return true if the integer value can be used 13038 /// as the offset of the target addressing mode for load / store of the 13039 /// given type. 13040 static bool isLegalAddressImmediate(int64_t V, EVT VT, 13041 const ARMSubtarget *Subtarget) { 13042 if (V == 0) 13043 return true; 13044 13045 if (!VT.isSimple()) 13046 return false; 13047 13048 if (Subtarget->isThumb1Only()) 13049 return isLegalT1AddressImmediate(V, VT); 13050 else if (Subtarget->isThumb2()) 13051 return isLegalT2AddressImmediate(V, VT, Subtarget); 13052 13053 // ARM mode. 13054 if (V < 0) 13055 V = - V; 13056 switch (VT.getSimpleVT().SimpleTy) { 13057 default: return false; 13058 case MVT::i1: 13059 case MVT::i8: 13060 case MVT::i32: 13061 // +- imm12 13062 return V == (V & ((1LL << 12) - 1)); 13063 case MVT::i16: 13064 // +- imm8 13065 return V == (V & ((1LL << 8) - 1)); 13066 case MVT::f32: 13067 case MVT::f64: 13068 if (!Subtarget->hasVFP2()) // FIXME: NEON? 13069 return false; 13070 if ((V & 3) != 0) 13071 return false; 13072 V >>= 2; 13073 return V == (V & ((1LL << 8) - 1)); 13074 } 13075 } 13076 13077 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 13078 EVT VT) const { 13079 int Scale = AM.Scale; 13080 if (Scale < 0) 13081 return false; 13082 13083 switch (VT.getSimpleVT().SimpleTy) { 13084 default: return false; 13085 case MVT::i1: 13086 case MVT::i8: 13087 case MVT::i16: 13088 case MVT::i32: 13089 if (Scale == 1) 13090 return true; 13091 // r + r << imm 13092 Scale = Scale & ~1; 13093 return Scale == 2 || Scale == 4 || Scale == 8; 13094 case MVT::i64: 13095 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 13096 // version in Thumb mode. 13097 // r + r 13098 if (Scale == 1) 13099 return true; 13100 // r * 2 (this can be lowered to r + r). 13101 if (!AM.HasBaseReg && Scale == 2) 13102 return true; 13103 return false; 13104 case MVT::isVoid: 13105 // Note, we allow "void" uses (basically, uses that aren't loads or 13106 // stores), because arm allows folding a scale into many arithmetic 13107 // operations. This should be made more precise and revisited later. 13108 13109 // Allow r << imm, but the imm has to be a multiple of two. 13110 if (Scale & 1) return false; 13111 return isPowerOf2_32(Scale); 13112 } 13113 } 13114 13115 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 13116 EVT VT) const { 13117 const int Scale = AM.Scale; 13118 13119 // Negative scales are not supported in Thumb1. 13120 if (Scale < 0) 13121 return false; 13122 13123 // Thumb1 addressing modes do not support register scaling excepting the 13124 // following cases: 13125 // 1. Scale == 1 means no scaling. 13126 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 13127 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 13128 } 13129 13130 /// isLegalAddressingMode - Return true if the addressing mode represented 13131 /// by AM is legal for this target, for a load/store of the specified type. 13132 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13133 const AddrMode &AM, Type *Ty, 13134 unsigned AS, Instruction *I) const { 13135 EVT VT = getValueType(DL, Ty, true); 13136 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 13137 return false; 13138 13139 // Can never fold addr of global into load/store. 13140 if (AM.BaseGV) 13141 return false; 13142 13143 switch (AM.Scale) { 13144 case 0: // no scale reg, must be "r+i" or "r", or "i". 13145 break; 13146 default: 13147 // ARM doesn't support any R+R*scale+imm addr modes. 13148 if (AM.BaseOffs) 13149 return false; 13150 13151 if (!VT.isSimple()) 13152 return false; 13153 13154 if (Subtarget->isThumb1Only()) 13155 return isLegalT1ScaledAddressingMode(AM, VT); 13156 13157 if (Subtarget->isThumb2()) 13158 return isLegalT2ScaledAddressingMode(AM, VT); 13159 13160 int Scale = AM.Scale; 13161 switch (VT.getSimpleVT().SimpleTy) { 13162 default: return false; 13163 case MVT::i1: 13164 case MVT::i8: 13165 case MVT::i32: 13166 if (Scale < 0) Scale = -Scale; 13167 if (Scale == 1) 13168 return true; 13169 // r + r << imm 13170 return isPowerOf2_32(Scale & ~1); 13171 case MVT::i16: 13172 case MVT::i64: 13173 // r +/- r 13174 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 13175 return true; 13176 // r * 2 (this can be lowered to r + r). 13177 if (!AM.HasBaseReg && Scale == 2) 13178 return true; 13179 return false; 13180 13181 case MVT::isVoid: 13182 // Note, we allow "void" uses (basically, uses that aren't loads or 13183 // stores), because arm allows folding a scale into many arithmetic 13184 // operations. This should be made more precise and revisited later. 13185 13186 // Allow r << imm, but the imm has to be a multiple of two. 13187 if (Scale & 1) return false; 13188 return isPowerOf2_32(Scale); 13189 } 13190 } 13191 return true; 13192 } 13193 13194 /// isLegalICmpImmediate - Return true if the specified immediate is legal 13195 /// icmp immediate, that is the target has icmp instructions which can compare 13196 /// a register against the immediate without having to materialize the 13197 /// immediate into a register. 13198 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13199 // Thumb2 and ARM modes can use cmn for negative immediates. 13200 if (!Subtarget->isThumb()) 13201 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 13202 if (Subtarget->isThumb2()) 13203 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 13204 // Thumb1 doesn't have cmn, and only 8-bit immediates. 13205 return Imm >= 0 && Imm <= 255; 13206 } 13207 13208 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 13209 /// *or sub* immediate, that is the target has add or sub instructions which can 13210 /// add a register with the immediate without having to materialize the 13211 /// immediate into a register. 13212 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13213 // Same encoding for add/sub, just flip the sign. 13214 int64_t AbsImm = std::abs(Imm); 13215 if (!Subtarget->isThumb()) 13216 return ARM_AM::getSOImmVal(AbsImm) != -1; 13217 if (Subtarget->isThumb2()) 13218 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 13219 // Thumb1 only has 8-bit unsigned immediate. 13220 return AbsImm >= 0 && AbsImm <= 255; 13221 } 13222 13223 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 13224 bool isSEXTLoad, SDValue &Base, 13225 SDValue &Offset, bool &isInc, 13226 SelectionDAG &DAG) { 13227 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13228 return false; 13229 13230 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 13231 // AddressingMode 3 13232 Base = Ptr->getOperand(0); 13233 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13234 int RHSC = (int)RHS->getZExtValue(); 13235 if (RHSC < 0 && RHSC > -256) { 13236 assert(Ptr->getOpcode() == ISD::ADD); 13237 isInc = false; 13238 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13239 return true; 13240 } 13241 } 13242 isInc = (Ptr->getOpcode() == ISD::ADD); 13243 Offset = Ptr->getOperand(1); 13244 return true; 13245 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 13246 // AddressingMode 2 13247 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13248 int RHSC = (int)RHS->getZExtValue(); 13249 if (RHSC < 0 && RHSC > -0x1000) { 13250 assert(Ptr->getOpcode() == ISD::ADD); 13251 isInc = false; 13252 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13253 Base = Ptr->getOperand(0); 13254 return true; 13255 } 13256 } 13257 13258 if (Ptr->getOpcode() == ISD::ADD) { 13259 isInc = true; 13260 ARM_AM::ShiftOpc ShOpcVal= 13261 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 13262 if (ShOpcVal != ARM_AM::no_shift) { 13263 Base = Ptr->getOperand(1); 13264 Offset = Ptr->getOperand(0); 13265 } else { 13266 Base = Ptr->getOperand(0); 13267 Offset = Ptr->getOperand(1); 13268 } 13269 return true; 13270 } 13271 13272 isInc = (Ptr->getOpcode() == ISD::ADD); 13273 Base = Ptr->getOperand(0); 13274 Offset = Ptr->getOperand(1); 13275 return true; 13276 } 13277 13278 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 13279 return false; 13280 } 13281 13282 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 13283 bool isSEXTLoad, SDValue &Base, 13284 SDValue &Offset, bool &isInc, 13285 SelectionDAG &DAG) { 13286 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13287 return false; 13288 13289 Base = Ptr->getOperand(0); 13290 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13291 int RHSC = (int)RHS->getZExtValue(); 13292 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 13293 assert(Ptr->getOpcode() == ISD::ADD); 13294 isInc = false; 13295 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13296 return true; 13297 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 13298 isInc = Ptr->getOpcode() == ISD::ADD; 13299 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13300 return true; 13301 } 13302 } 13303 13304 return false; 13305 } 13306 13307 /// getPreIndexedAddressParts - returns true by value, base pointer and 13308 /// offset pointer and addressing mode by reference if the node's address 13309 /// can be legally represented as pre-indexed load / store address. 13310 bool 13311 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 13312 SDValue &Offset, 13313 ISD::MemIndexedMode &AM, 13314 SelectionDAG &DAG) const { 13315 if (Subtarget->isThumb1Only()) 13316 return false; 13317 13318 EVT VT; 13319 SDValue Ptr; 13320 bool isSEXTLoad = false; 13321 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13322 Ptr = LD->getBasePtr(); 13323 VT = LD->getMemoryVT(); 13324 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13325 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13326 Ptr = ST->getBasePtr(); 13327 VT = ST->getMemoryVT(); 13328 } else 13329 return false; 13330 13331 bool isInc; 13332 bool isLegal = false; 13333 if (Subtarget->isThumb2()) 13334 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13335 Offset, isInc, DAG); 13336 else 13337 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13338 Offset, isInc, DAG); 13339 if (!isLegal) 13340 return false; 13341 13342 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 13343 return true; 13344 } 13345 13346 /// getPostIndexedAddressParts - returns true by value, base pointer and 13347 /// offset pointer and addressing mode by reference if this node can be 13348 /// combined with a load / store to form a post-indexed load / store. 13349 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 13350 SDValue &Base, 13351 SDValue &Offset, 13352 ISD::MemIndexedMode &AM, 13353 SelectionDAG &DAG) const { 13354 EVT VT; 13355 SDValue Ptr; 13356 bool isSEXTLoad = false, isNonExt; 13357 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13358 VT = LD->getMemoryVT(); 13359 Ptr = LD->getBasePtr(); 13360 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13361 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 13362 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13363 VT = ST->getMemoryVT(); 13364 Ptr = ST->getBasePtr(); 13365 isNonExt = !ST->isTruncatingStore(); 13366 } else 13367 return false; 13368 13369 if (Subtarget->isThumb1Only()) { 13370 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 13371 // must be non-extending/truncating, i32, with an offset of 4. 13372 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 13373 if (Op->getOpcode() != ISD::ADD || !isNonExt) 13374 return false; 13375 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 13376 if (!RHS || RHS->getZExtValue() != 4) 13377 return false; 13378 13379 Offset = Op->getOperand(1); 13380 Base = Op->getOperand(0); 13381 AM = ISD::POST_INC; 13382 return true; 13383 } 13384 13385 bool isInc; 13386 bool isLegal = false; 13387 if (Subtarget->isThumb2()) 13388 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13389 isInc, DAG); 13390 else 13391 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13392 isInc, DAG); 13393 if (!isLegal) 13394 return false; 13395 13396 if (Ptr != Base) { 13397 // Swap base ptr and offset to catch more post-index load / store when 13398 // it's legal. In Thumb2 mode, offset must be an immediate. 13399 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 13400 !Subtarget->isThumb2()) 13401 std::swap(Base, Offset); 13402 13403 // Post-indexed load / store update the base pointer. 13404 if (Ptr != Base) 13405 return false; 13406 } 13407 13408 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 13409 return true; 13410 } 13411 13412 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13413 KnownBits &Known, 13414 const APInt &DemandedElts, 13415 const SelectionDAG &DAG, 13416 unsigned Depth) const { 13417 unsigned BitWidth = Known.getBitWidth(); 13418 Known.resetAll(); 13419 switch (Op.getOpcode()) { 13420 default: break; 13421 case ARMISD::ADDC: 13422 case ARMISD::ADDE: 13423 case ARMISD::SUBC: 13424 case ARMISD::SUBE: 13425 // Special cases when we convert a carry to a boolean. 13426 if (Op.getResNo() == 0) { 13427 SDValue LHS = Op.getOperand(0); 13428 SDValue RHS = Op.getOperand(1); 13429 // (ADDE 0, 0, C) will give us a single bit. 13430 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 13431 isNullConstant(RHS)) { 13432 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 13433 return; 13434 } 13435 } 13436 break; 13437 case ARMISD::CMOV: { 13438 // Bits are known zero/one if known on the LHS and RHS. 13439 DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1); 13440 if (Known.isUnknown()) 13441 return; 13442 13443 KnownBits KnownRHS; 13444 DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1); 13445 Known.Zero &= KnownRHS.Zero; 13446 Known.One &= KnownRHS.One; 13447 return; 13448 } 13449 case ISD::INTRINSIC_W_CHAIN: { 13450 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 13451 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 13452 switch (IntID) { 13453 default: return; 13454 case Intrinsic::arm_ldaex: 13455 case Intrinsic::arm_ldrex: { 13456 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 13457 unsigned MemBits = VT.getScalarSizeInBits(); 13458 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 13459 return; 13460 } 13461 } 13462 } 13463 case ARMISD::BFI: { 13464 // Conservatively, we can recurse down the first operand 13465 // and just mask out all affected bits. 13466 DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1); 13467 13468 // The operand to BFI is already a mask suitable for removing the bits it 13469 // sets. 13470 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 13471 const APInt &Mask = CI->getAPIntValue(); 13472 Known.Zero &= Mask; 13473 Known.One &= Mask; 13474 return; 13475 } 13476 } 13477 } 13478 13479 //===----------------------------------------------------------------------===// 13480 // ARM Inline Assembly Support 13481 //===----------------------------------------------------------------------===// 13482 13483 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 13484 // Looking for "rev" which is V6+. 13485 if (!Subtarget->hasV6Ops()) 13486 return false; 13487 13488 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 13489 std::string AsmStr = IA->getAsmString(); 13490 SmallVector<StringRef, 4> AsmPieces; 13491 SplitString(AsmStr, AsmPieces, ";\n"); 13492 13493 switch (AsmPieces.size()) { 13494 default: return false; 13495 case 1: 13496 AsmStr = AsmPieces[0]; 13497 AsmPieces.clear(); 13498 SplitString(AsmStr, AsmPieces, " \t,"); 13499 13500 // rev $0, $1 13501 if (AsmPieces.size() == 3 && 13502 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 13503 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 13504 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 13505 if (Ty && Ty->getBitWidth() == 32) 13506 return IntrinsicLowering::LowerToByteSwap(CI); 13507 } 13508 break; 13509 } 13510 13511 return false; 13512 } 13513 13514 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 13515 // At this point, we have to lower this constraint to something else, so we 13516 // lower it to an "r" or "w". However, by doing this we will force the result 13517 // to be in register, while the X constraint is much more permissive. 13518 // 13519 // Although we are correct (we are free to emit anything, without 13520 // constraints), we might break use cases that would expect us to be more 13521 // efficient and emit something else. 13522 if (!Subtarget->hasVFP2()) 13523 return "r"; 13524 if (ConstraintVT.isFloatingPoint()) 13525 return "w"; 13526 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 13527 (ConstraintVT.getSizeInBits() == 64 || 13528 ConstraintVT.getSizeInBits() == 128)) 13529 return "w"; 13530 13531 return "r"; 13532 } 13533 13534 /// getConstraintType - Given a constraint letter, return the type of 13535 /// constraint it is for this target. 13536 ARMTargetLowering::ConstraintType 13537 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 13538 if (Constraint.size() == 1) { 13539 switch (Constraint[0]) { 13540 default: break; 13541 case 'l': return C_RegisterClass; 13542 case 'w': return C_RegisterClass; 13543 case 'h': return C_RegisterClass; 13544 case 'x': return C_RegisterClass; 13545 case 't': return C_RegisterClass; 13546 case 'j': return C_Other; // Constant for movw. 13547 // An address with a single base register. Due to the way we 13548 // currently handle addresses it is the same as an 'r' memory constraint. 13549 case 'Q': return C_Memory; 13550 } 13551 } else if (Constraint.size() == 2) { 13552 switch (Constraint[0]) { 13553 default: break; 13554 // All 'U+' constraints are addresses. 13555 case 'U': return C_Memory; 13556 } 13557 } 13558 return TargetLowering::getConstraintType(Constraint); 13559 } 13560 13561 /// Examine constraint type and operand type and determine a weight value. 13562 /// This object must already have been set up with the operand type 13563 /// and the current alternative constraint selected. 13564 TargetLowering::ConstraintWeight 13565 ARMTargetLowering::getSingleConstraintMatchWeight( 13566 AsmOperandInfo &info, const char *constraint) const { 13567 ConstraintWeight weight = CW_Invalid; 13568 Value *CallOperandVal = info.CallOperandVal; 13569 // If we don't have a value, we can't do a match, 13570 // but allow it at the lowest weight. 13571 if (!CallOperandVal) 13572 return CW_Default; 13573 Type *type = CallOperandVal->getType(); 13574 // Look at the constraint type. 13575 switch (*constraint) { 13576 default: 13577 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13578 break; 13579 case 'l': 13580 if (type->isIntegerTy()) { 13581 if (Subtarget->isThumb()) 13582 weight = CW_SpecificReg; 13583 else 13584 weight = CW_Register; 13585 } 13586 break; 13587 case 'w': 13588 if (type->isFloatingPointTy()) 13589 weight = CW_Register; 13590 break; 13591 } 13592 return weight; 13593 } 13594 13595 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 13596 13597 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 13598 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 13599 if (Constraint.size() == 1) { 13600 // GCC ARM Constraint Letters 13601 switch (Constraint[0]) { 13602 case 'l': // Low regs or general regs. 13603 if (Subtarget->isThumb()) 13604 return RCPair(0U, &ARM::tGPRRegClass); 13605 return RCPair(0U, &ARM::GPRRegClass); 13606 case 'h': // High regs or no regs. 13607 if (Subtarget->isThumb()) 13608 return RCPair(0U, &ARM::hGPRRegClass); 13609 break; 13610 case 'r': 13611 if (Subtarget->isThumb1Only()) 13612 return RCPair(0U, &ARM::tGPRRegClass); 13613 return RCPair(0U, &ARM::GPRRegClass); 13614 case 'w': 13615 if (VT == MVT::Other) 13616 break; 13617 if (VT == MVT::f32) 13618 return RCPair(0U, &ARM::SPRRegClass); 13619 if (VT.getSizeInBits() == 64) 13620 return RCPair(0U, &ARM::DPRRegClass); 13621 if (VT.getSizeInBits() == 128) 13622 return RCPair(0U, &ARM::QPRRegClass); 13623 break; 13624 case 'x': 13625 if (VT == MVT::Other) 13626 break; 13627 if (VT == MVT::f32) 13628 return RCPair(0U, &ARM::SPR_8RegClass); 13629 if (VT.getSizeInBits() == 64) 13630 return RCPair(0U, &ARM::DPR_8RegClass); 13631 if (VT.getSizeInBits() == 128) 13632 return RCPair(0U, &ARM::QPR_8RegClass); 13633 break; 13634 case 't': 13635 if (VT == MVT::Other) 13636 break; 13637 if (VT == MVT::f32 || VT == MVT::i32) 13638 return RCPair(0U, &ARM::SPRRegClass); 13639 if (VT.getSizeInBits() == 64) 13640 return RCPair(0U, &ARM::DPR_VFP2RegClass); 13641 if (VT.getSizeInBits() == 128) 13642 return RCPair(0U, &ARM::QPR_VFP2RegClass); 13643 break; 13644 } 13645 } 13646 if (StringRef("{cc}").equals_lower(Constraint)) 13647 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 13648 13649 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13650 } 13651 13652 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13653 /// vector. If it is invalid, don't add anything to Ops. 13654 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13655 std::string &Constraint, 13656 std::vector<SDValue>&Ops, 13657 SelectionDAG &DAG) const { 13658 SDValue Result; 13659 13660 // Currently only support length 1 constraints. 13661 if (Constraint.length() != 1) return; 13662 13663 char ConstraintLetter = Constraint[0]; 13664 switch (ConstraintLetter) { 13665 default: break; 13666 case 'j': 13667 case 'I': case 'J': case 'K': case 'L': 13668 case 'M': case 'N': case 'O': 13669 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 13670 if (!C) 13671 return; 13672 13673 int64_t CVal64 = C->getSExtValue(); 13674 int CVal = (int) CVal64; 13675 // None of these constraints allow values larger than 32 bits. Check 13676 // that the value fits in an int. 13677 if (CVal != CVal64) 13678 return; 13679 13680 switch (ConstraintLetter) { 13681 case 'j': 13682 // Constant suitable for movw, must be between 0 and 13683 // 65535. 13684 if (Subtarget->hasV6T2Ops()) 13685 if (CVal >= 0 && CVal <= 65535) 13686 break; 13687 return; 13688 case 'I': 13689 if (Subtarget->isThumb1Only()) { 13690 // This must be a constant between 0 and 255, for ADD 13691 // immediates. 13692 if (CVal >= 0 && CVal <= 255) 13693 break; 13694 } else if (Subtarget->isThumb2()) { 13695 // A constant that can be used as an immediate value in a 13696 // data-processing instruction. 13697 if (ARM_AM::getT2SOImmVal(CVal) != -1) 13698 break; 13699 } else { 13700 // A constant that can be used as an immediate value in a 13701 // data-processing instruction. 13702 if (ARM_AM::getSOImmVal(CVal) != -1) 13703 break; 13704 } 13705 return; 13706 13707 case 'J': 13708 if (Subtarget->isThumb1Only()) { 13709 // This must be a constant between -255 and -1, for negated ADD 13710 // immediates. This can be used in GCC with an "n" modifier that 13711 // prints the negated value, for use with SUB instructions. It is 13712 // not useful otherwise but is implemented for compatibility. 13713 if (CVal >= -255 && CVal <= -1) 13714 break; 13715 } else { 13716 // This must be a constant between -4095 and 4095. It is not clear 13717 // what this constraint is intended for. Implemented for 13718 // compatibility with GCC. 13719 if (CVal >= -4095 && CVal <= 4095) 13720 break; 13721 } 13722 return; 13723 13724 case 'K': 13725 if (Subtarget->isThumb1Only()) { 13726 // A 32-bit value where only one byte has a nonzero value. Exclude 13727 // zero to match GCC. This constraint is used by GCC internally for 13728 // constants that can be loaded with a move/shift combination. 13729 // It is not useful otherwise but is implemented for compatibility. 13730 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 13731 break; 13732 } else if (Subtarget->isThumb2()) { 13733 // A constant whose bitwise inverse can be used as an immediate 13734 // value in a data-processing instruction. This can be used in GCC 13735 // with a "B" modifier that prints the inverted value, for use with 13736 // BIC and MVN instructions. It is not useful otherwise but is 13737 // implemented for compatibility. 13738 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 13739 break; 13740 } else { 13741 // A constant whose bitwise inverse can be used as an immediate 13742 // value in a data-processing instruction. This can be used in GCC 13743 // with a "B" modifier that prints the inverted value, for use with 13744 // BIC and MVN instructions. It is not useful otherwise but is 13745 // implemented for compatibility. 13746 if (ARM_AM::getSOImmVal(~CVal) != -1) 13747 break; 13748 } 13749 return; 13750 13751 case 'L': 13752 if (Subtarget->isThumb1Only()) { 13753 // This must be a constant between -7 and 7, 13754 // for 3-operand ADD/SUB immediate instructions. 13755 if (CVal >= -7 && CVal < 7) 13756 break; 13757 } else if (Subtarget->isThumb2()) { 13758 // A constant whose negation can be used as an immediate value in a 13759 // data-processing instruction. This can be used in GCC with an "n" 13760 // modifier that prints the negated value, for use with SUB 13761 // instructions. It is not useful otherwise but is implemented for 13762 // compatibility. 13763 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 13764 break; 13765 } else { 13766 // A constant whose negation can be used as an immediate value in a 13767 // data-processing instruction. This can be used in GCC with an "n" 13768 // modifier that prints the negated value, for use with SUB 13769 // instructions. It is not useful otherwise but is implemented for 13770 // compatibility. 13771 if (ARM_AM::getSOImmVal(-CVal) != -1) 13772 break; 13773 } 13774 return; 13775 13776 case 'M': 13777 if (Subtarget->isThumb1Only()) { 13778 // This must be a multiple of 4 between 0 and 1020, for 13779 // ADD sp + immediate. 13780 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 13781 break; 13782 } else { 13783 // A power of two or a constant between 0 and 32. This is used in 13784 // GCC for the shift amount on shifted register operands, but it is 13785 // useful in general for any shift amounts. 13786 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 13787 break; 13788 } 13789 return; 13790 13791 case 'N': 13792 if (Subtarget->isThumb()) { // FIXME thumb2 13793 // This must be a constant between 0 and 31, for shift amounts. 13794 if (CVal >= 0 && CVal <= 31) 13795 break; 13796 } 13797 return; 13798 13799 case 'O': 13800 if (Subtarget->isThumb()) { // FIXME thumb2 13801 // This must be a multiple of 4 between -508 and 508, for 13802 // ADD/SUB sp = sp + immediate. 13803 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 13804 break; 13805 } 13806 return; 13807 } 13808 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 13809 break; 13810 } 13811 13812 if (Result.getNode()) { 13813 Ops.push_back(Result); 13814 return; 13815 } 13816 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13817 } 13818 13819 static RTLIB::Libcall getDivRemLibcall( 13820 const SDNode *N, MVT::SimpleValueType SVT) { 13821 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13822 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13823 "Unhandled Opcode in getDivRemLibcall"); 13824 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13825 N->getOpcode() == ISD::SREM; 13826 RTLIB::Libcall LC; 13827 switch (SVT) { 13828 default: llvm_unreachable("Unexpected request for libcall!"); 13829 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 13830 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 13831 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 13832 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 13833 } 13834 return LC; 13835 } 13836 13837 static TargetLowering::ArgListTy getDivRemArgList( 13838 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 13839 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13840 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13841 "Unhandled Opcode in getDivRemArgList"); 13842 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13843 N->getOpcode() == ISD::SREM; 13844 TargetLowering::ArgListTy Args; 13845 TargetLowering::ArgListEntry Entry; 13846 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13847 EVT ArgVT = N->getOperand(i).getValueType(); 13848 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 13849 Entry.Node = N->getOperand(i); 13850 Entry.Ty = ArgTy; 13851 Entry.IsSExt = isSigned; 13852 Entry.IsZExt = !isSigned; 13853 Args.push_back(Entry); 13854 } 13855 if (Subtarget->isTargetWindows() && Args.size() >= 2) 13856 std::swap(Args[0], Args[1]); 13857 return Args; 13858 } 13859 13860 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 13861 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 13862 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 13863 Subtarget->isTargetWindows()) && 13864 "Register-based DivRem lowering only"); 13865 unsigned Opcode = Op->getOpcode(); 13866 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 13867 "Invalid opcode for Div/Rem lowering"); 13868 bool isSigned = (Opcode == ISD::SDIVREM); 13869 EVT VT = Op->getValueType(0); 13870 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 13871 SDLoc dl(Op); 13872 13873 // If the target has hardware divide, use divide + multiply + subtract: 13874 // div = a / b 13875 // rem = a - b * div 13876 // return {div, rem} 13877 // This should be lowered into UDIV/SDIV + MLS later on. 13878 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 13879 : Subtarget->hasDivideInARMMode(); 13880 if (hasDivide && Op->getValueType(0).isSimple() && 13881 Op->getSimpleValueType(0) == MVT::i32) { 13882 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 13883 const SDValue Dividend = Op->getOperand(0); 13884 const SDValue Divisor = Op->getOperand(1); 13885 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 13886 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 13887 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 13888 13889 SDValue Values[2] = {Div, Rem}; 13890 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 13891 } 13892 13893 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 13894 VT.getSimpleVT().SimpleTy); 13895 SDValue InChain = DAG.getEntryNode(); 13896 13897 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 13898 DAG.getContext(), 13899 Subtarget); 13900 13901 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13902 getPointerTy(DAG.getDataLayout())); 13903 13904 Type *RetTy = StructType::get(Ty, Ty); 13905 13906 if (Subtarget->isTargetWindows()) 13907 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 13908 13909 TargetLowering::CallLoweringInfo CLI(DAG); 13910 CLI.setDebugLoc(dl).setChain(InChain) 13911 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 13912 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 13913 13914 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 13915 return CallInfo.first; 13916 } 13917 13918 // Lowers REM using divmod helpers 13919 // see RTABI section 4.2/4.3 13920 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 13921 // Build return types (div and rem) 13922 std::vector<Type*> RetTyParams; 13923 Type *RetTyElement; 13924 13925 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 13926 default: llvm_unreachable("Unexpected request for libcall!"); 13927 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 13928 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 13929 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 13930 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 13931 } 13932 13933 RetTyParams.push_back(RetTyElement); 13934 RetTyParams.push_back(RetTyElement); 13935 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 13936 Type *RetTy = StructType::get(*DAG.getContext(), ret); 13937 13938 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 13939 SimpleTy); 13940 SDValue InChain = DAG.getEntryNode(); 13941 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 13942 Subtarget); 13943 bool isSigned = N->getOpcode() == ISD::SREM; 13944 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13945 getPointerTy(DAG.getDataLayout())); 13946 13947 if (Subtarget->isTargetWindows()) 13948 InChain = WinDBZCheckDenominator(DAG, N, InChain); 13949 13950 // Lower call 13951 CallLoweringInfo CLI(DAG); 13952 CLI.setChain(InChain) 13953 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 13954 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 13955 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 13956 13957 // Return second (rem) result operand (first contains div) 13958 SDNode *ResNode = CallResult.first.getNode(); 13959 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 13960 return ResNode->getOperand(1); 13961 } 13962 13963 SDValue 13964 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 13965 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 13966 SDLoc DL(Op); 13967 13968 // Get the inputs. 13969 SDValue Chain = Op.getOperand(0); 13970 SDValue Size = Op.getOperand(1); 13971 13972 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 13973 "no-stack-arg-probe")) { 13974 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 13975 SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 13976 Chain = SP.getValue(1); 13977 SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size); 13978 if (Align) 13979 SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0), 13980 DAG.getConstant(-(uint64_t)Align, DL, MVT::i32)); 13981 Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP); 13982 SDValue Ops[2] = { SP, Chain }; 13983 return DAG.getMergeValues(Ops, DL); 13984 } 13985 13986 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 13987 DAG.getConstant(2, DL, MVT::i32)); 13988 13989 SDValue Flag; 13990 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 13991 Flag = Chain.getValue(1); 13992 13993 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 13994 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 13995 13996 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 13997 Chain = NewSP.getValue(1); 13998 13999 SDValue Ops[2] = { NewSP, Chain }; 14000 return DAG.getMergeValues(Ops, DL); 14001 } 14002 14003 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 14004 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 14005 "Unexpected type for custom-lowering FP_EXTEND"); 14006 14007 RTLIB::Libcall LC; 14008 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 14009 14010 SDValue SrcVal = Op.getOperand(0); 14011 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 14012 SDLoc(Op)).first; 14013 } 14014 14015 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 14016 assert(Op.getOperand(0).getValueType() == MVT::f64 && 14017 Subtarget->isFPOnlySP() && 14018 "Unexpected type for custom-lowering FP_ROUND"); 14019 14020 RTLIB::Libcall LC; 14021 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 14022 14023 SDValue SrcVal = Op.getOperand(0); 14024 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 14025 SDLoc(Op)).first; 14026 } 14027 14028 bool 14029 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14030 // The ARM target isn't yet aware of offsets. 14031 return false; 14032 } 14033 14034 bool ARM::isBitFieldInvertedMask(unsigned v) { 14035 if (v == 0xffffffff) 14036 return false; 14037 14038 // there can be 1's on either or both "outsides", all the "inside" 14039 // bits must be 0's 14040 return isShiftedMask_32(~v); 14041 } 14042 14043 /// isFPImmLegal - Returns true if the target can instruction select the 14044 /// specified FP immediate natively. If false, the legalizer will 14045 /// materialize the FP immediate as a load from a constant pool. 14046 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 14047 if (!Subtarget->hasVFP3()) 14048 return false; 14049 if (VT == MVT::f16 && Subtarget->hasFullFP16()) 14050 return ARM_AM::getFP16Imm(Imm) != -1; 14051 if (VT == MVT::f32) 14052 return ARM_AM::getFP32Imm(Imm) != -1; 14053 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 14054 return ARM_AM::getFP64Imm(Imm) != -1; 14055 return false; 14056 } 14057 14058 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 14059 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 14060 /// specified in the intrinsic calls. 14061 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14062 const CallInst &I, 14063 MachineFunction &MF, 14064 unsigned Intrinsic) const { 14065 switch (Intrinsic) { 14066 case Intrinsic::arm_neon_vld1: 14067 case Intrinsic::arm_neon_vld2: 14068 case Intrinsic::arm_neon_vld3: 14069 case Intrinsic::arm_neon_vld4: 14070 case Intrinsic::arm_neon_vld2lane: 14071 case Intrinsic::arm_neon_vld3lane: 14072 case Intrinsic::arm_neon_vld4lane: 14073 case Intrinsic::arm_neon_vld2dup: 14074 case Intrinsic::arm_neon_vld3dup: 14075 case Intrinsic::arm_neon_vld4dup: { 14076 Info.opc = ISD::INTRINSIC_W_CHAIN; 14077 // Conservatively set memVT to the entire set of vectors loaded. 14078 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14079 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14080 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14081 Info.ptrVal = I.getArgOperand(0); 14082 Info.offset = 0; 14083 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14084 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14085 // volatile loads with NEON intrinsics not supported 14086 Info.flags = MachineMemOperand::MOLoad; 14087 return true; 14088 } 14089 case Intrinsic::arm_neon_vld1x2: 14090 case Intrinsic::arm_neon_vld1x3: 14091 case Intrinsic::arm_neon_vld1x4: { 14092 Info.opc = ISD::INTRINSIC_W_CHAIN; 14093 // Conservatively set memVT to the entire set of vectors loaded. 14094 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14095 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 14096 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14097 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 14098 Info.offset = 0; 14099 Info.align = 0; 14100 // volatile loads with NEON intrinsics not supported 14101 Info.flags = MachineMemOperand::MOLoad; 14102 return true; 14103 } 14104 case Intrinsic::arm_neon_vst1: 14105 case Intrinsic::arm_neon_vst2: 14106 case Intrinsic::arm_neon_vst3: 14107 case Intrinsic::arm_neon_vst4: 14108 case Intrinsic::arm_neon_vst2lane: 14109 case Intrinsic::arm_neon_vst3lane: 14110 case Intrinsic::arm_neon_vst4lane: { 14111 Info.opc = ISD::INTRINSIC_VOID; 14112 // Conservatively set memVT to the entire set of vectors stored. 14113 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14114 unsigned NumElts = 0; 14115 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14116 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14117 if (!ArgTy->isVectorTy()) 14118 break; 14119 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14120 } 14121 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14122 Info.ptrVal = I.getArgOperand(0); 14123 Info.offset = 0; 14124 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 14125 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 14126 // volatile stores with NEON intrinsics not supported 14127 Info.flags = MachineMemOperand::MOStore; 14128 return true; 14129 } 14130 case Intrinsic::arm_neon_vst1x2: 14131 case Intrinsic::arm_neon_vst1x3: 14132 case Intrinsic::arm_neon_vst1x4: { 14133 Info.opc = ISD::INTRINSIC_VOID; 14134 // Conservatively set memVT to the entire set of vectors stored. 14135 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14136 unsigned NumElts = 0; 14137 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 14138 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 14139 if (!ArgTy->isVectorTy()) 14140 break; 14141 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 14142 } 14143 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 14144 Info.ptrVal = I.getArgOperand(0); 14145 Info.offset = 0; 14146 Info.align = 0; 14147 // volatile stores with NEON intrinsics not supported 14148 Info.flags = MachineMemOperand::MOStore; 14149 return true; 14150 } 14151 case Intrinsic::arm_ldaex: 14152 case Intrinsic::arm_ldrex: { 14153 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14154 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 14155 Info.opc = ISD::INTRINSIC_W_CHAIN; 14156 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14157 Info.ptrVal = I.getArgOperand(0); 14158 Info.offset = 0; 14159 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14160 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14161 return true; 14162 } 14163 case Intrinsic::arm_stlex: 14164 case Intrinsic::arm_strex: { 14165 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 14166 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 14167 Info.opc = ISD::INTRINSIC_W_CHAIN; 14168 Info.memVT = MVT::getVT(PtrTy->getElementType()); 14169 Info.ptrVal = I.getArgOperand(1); 14170 Info.offset = 0; 14171 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 14172 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14173 return true; 14174 } 14175 case Intrinsic::arm_stlexd: 14176 case Intrinsic::arm_strexd: 14177 Info.opc = ISD::INTRINSIC_W_CHAIN; 14178 Info.memVT = MVT::i64; 14179 Info.ptrVal = I.getArgOperand(2); 14180 Info.offset = 0; 14181 Info.align = 8; 14182 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 14183 return true; 14184 14185 case Intrinsic::arm_ldaexd: 14186 case Intrinsic::arm_ldrexd: 14187 Info.opc = ISD::INTRINSIC_W_CHAIN; 14188 Info.memVT = MVT::i64; 14189 Info.ptrVal = I.getArgOperand(0); 14190 Info.offset = 0; 14191 Info.align = 8; 14192 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 14193 return true; 14194 14195 default: 14196 break; 14197 } 14198 14199 return false; 14200 } 14201 14202 /// Returns true if it is beneficial to convert a load of a constant 14203 /// to just the constant itself. 14204 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14205 Type *Ty) const { 14206 assert(Ty->isIntegerTy()); 14207 14208 unsigned Bits = Ty->getPrimitiveSizeInBits(); 14209 if (Bits == 0 || Bits > 32) 14210 return false; 14211 return true; 14212 } 14213 14214 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 14215 unsigned Index) const { 14216 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 14217 return false; 14218 14219 return (Index == 0 || Index == ResVT.getVectorNumElements()); 14220 } 14221 14222 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 14223 ARM_MB::MemBOpt Domain) const { 14224 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14225 14226 // First, if the target has no DMB, see what fallback we can use. 14227 if (!Subtarget->hasDataBarrier()) { 14228 // Some ARMv6 cpus can support data barriers with an mcr instruction. 14229 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 14230 // here. 14231 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 14232 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 14233 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 14234 Builder.getInt32(0), Builder.getInt32(7), 14235 Builder.getInt32(10), Builder.getInt32(5)}; 14236 return Builder.CreateCall(MCR, args); 14237 } else { 14238 // Instead of using barriers, atomic accesses on these subtargets use 14239 // libcalls. 14240 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 14241 } 14242 } else { 14243 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 14244 // Only a full system barrier exists in the M-class architectures. 14245 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 14246 Constant *CDomain = Builder.getInt32(Domain); 14247 return Builder.CreateCall(DMB, CDomain); 14248 } 14249 } 14250 14251 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 14252 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 14253 Instruction *Inst, 14254 AtomicOrdering Ord) const { 14255 switch (Ord) { 14256 case AtomicOrdering::NotAtomic: 14257 case AtomicOrdering::Unordered: 14258 llvm_unreachable("Invalid fence: unordered/non-atomic"); 14259 case AtomicOrdering::Monotonic: 14260 case AtomicOrdering::Acquire: 14261 return nullptr; // Nothing to do 14262 case AtomicOrdering::SequentiallyConsistent: 14263 if (!Inst->hasAtomicStore()) 14264 return nullptr; // Nothing to do 14265 LLVM_FALLTHROUGH; 14266 case AtomicOrdering::Release: 14267 case AtomicOrdering::AcquireRelease: 14268 if (Subtarget->preferISHSTBarriers()) 14269 return makeDMB(Builder, ARM_MB::ISHST); 14270 // FIXME: add a comment with a link to documentation justifying this. 14271 else 14272 return makeDMB(Builder, ARM_MB::ISH); 14273 } 14274 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 14275 } 14276 14277 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 14278 Instruction *Inst, 14279 AtomicOrdering Ord) const { 14280 switch (Ord) { 14281 case AtomicOrdering::NotAtomic: 14282 case AtomicOrdering::Unordered: 14283 llvm_unreachable("Invalid fence: unordered/not-atomic"); 14284 case AtomicOrdering::Monotonic: 14285 case AtomicOrdering::Release: 14286 return nullptr; // Nothing to do 14287 case AtomicOrdering::Acquire: 14288 case AtomicOrdering::AcquireRelease: 14289 case AtomicOrdering::SequentiallyConsistent: 14290 return makeDMB(Builder, ARM_MB::ISH); 14291 } 14292 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 14293 } 14294 14295 // Loads and stores less than 64-bits are already atomic; ones above that 14296 // are doomed anyway, so defer to the default libcall and blame the OS when 14297 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14298 // anything for those. 14299 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 14300 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 14301 return (Size == 64) && !Subtarget->isMClass(); 14302 } 14303 14304 // Loads and stores less than 64-bits are already atomic; ones above that 14305 // are doomed anyway, so defer to the default libcall and blame the OS when 14306 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14307 // anything for those. 14308 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 14309 // guarantee, see DDI0406C ARM architecture reference manual, 14310 // sections A8.8.72-74 LDRD) 14311 TargetLowering::AtomicExpansionKind 14312 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 14313 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 14314 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 14315 : AtomicExpansionKind::None; 14316 } 14317 14318 // For the real atomic operations, we have ldrex/strex up to 32 bits, 14319 // and up to 64 bits on the non-M profiles 14320 TargetLowering::AtomicExpansionKind 14321 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 14322 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 14323 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14324 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 14325 ? AtomicExpansionKind::LLSC 14326 : AtomicExpansionKind::None; 14327 } 14328 14329 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 14330 AtomicCmpXchgInst *AI) const { 14331 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 14332 // implement cmpxchg without spilling. If the address being exchanged is also 14333 // on the stack and close enough to the spill slot, this can lead to a 14334 // situation where the monitor always gets cleared and the atomic operation 14335 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 14336 bool hasAtomicCmpXchg = 14337 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14338 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 14339 } 14340 14341 bool ARMTargetLowering::shouldInsertFencesForAtomic( 14342 const Instruction *I) const { 14343 return InsertFencesForAtomic; 14344 } 14345 14346 // This has so far only been implemented for MachO. 14347 bool ARMTargetLowering::useLoadStackGuardNode() const { 14348 return Subtarget->isTargetMachO(); 14349 } 14350 14351 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 14352 unsigned &Cost) const { 14353 // If we do not have NEON, vector types are not natively supported. 14354 if (!Subtarget->hasNEON()) 14355 return false; 14356 14357 // Floating point values and vector values map to the same register file. 14358 // Therefore, although we could do a store extract of a vector type, this is 14359 // better to leave at float as we have more freedom in the addressing mode for 14360 // those. 14361 if (VectorTy->isFPOrFPVectorTy()) 14362 return false; 14363 14364 // If the index is unknown at compile time, this is very expensive to lower 14365 // and it is not possible to combine the store with the extract. 14366 if (!isa<ConstantInt>(Idx)) 14367 return false; 14368 14369 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 14370 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 14371 // We can do a store + vector extract on any vector that fits perfectly in a D 14372 // or Q register. 14373 if (BitWidth == 64 || BitWidth == 128) { 14374 Cost = 0; 14375 return true; 14376 } 14377 return false; 14378 } 14379 14380 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 14381 return Subtarget->hasV6T2Ops(); 14382 } 14383 14384 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 14385 return Subtarget->hasV6T2Ops(); 14386 } 14387 14388 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 14389 AtomicOrdering Ord) const { 14390 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14391 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 14392 bool IsAcquire = isAcquireOrStronger(Ord); 14393 14394 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 14395 // intrinsic must return {i32, i32} and we have to recombine them into a 14396 // single i64 here. 14397 if (ValTy->getPrimitiveSizeInBits() == 64) { 14398 Intrinsic::ID Int = 14399 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 14400 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 14401 14402 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14403 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 14404 14405 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 14406 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 14407 if (!Subtarget->isLittle()) 14408 std::swap (Lo, Hi); 14409 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 14410 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 14411 return Builder.CreateOr( 14412 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 14413 } 14414 14415 Type *Tys[] = { Addr->getType() }; 14416 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 14417 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 14418 14419 return Builder.CreateTruncOrBitCast( 14420 Builder.CreateCall(Ldrex, Addr), 14421 cast<PointerType>(Addr->getType())->getElementType()); 14422 } 14423 14424 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 14425 IRBuilder<> &Builder) const { 14426 if (!Subtarget->hasV7Ops()) 14427 return; 14428 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14429 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 14430 } 14431 14432 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 14433 Value *Addr, 14434 AtomicOrdering Ord) const { 14435 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14436 bool IsRelease = isReleaseOrStronger(Ord); 14437 14438 // Since the intrinsics must have legal type, the i64 intrinsics take two 14439 // parameters: "i32, i32". We must marshal Val into the appropriate form 14440 // before the call. 14441 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 14442 Intrinsic::ID Int = 14443 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 14444 Function *Strex = Intrinsic::getDeclaration(M, Int); 14445 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 14446 14447 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 14448 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 14449 if (!Subtarget->isLittle()) 14450 std::swap(Lo, Hi); 14451 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14452 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 14453 } 14454 14455 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 14456 Type *Tys[] = { Addr->getType() }; 14457 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 14458 14459 return Builder.CreateCall( 14460 Strex, {Builder.CreateZExtOrBitCast( 14461 Val, Strex->getFunctionType()->getParamType(0)), 14462 Addr}); 14463 } 14464 14465 /// A helper function for determining the number of interleaved accesses we 14466 /// will generate when lowering accesses of the given type. 14467 unsigned 14468 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 14469 const DataLayout &DL) const { 14470 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 14471 } 14472 14473 bool ARMTargetLowering::isLegalInterleavedAccessType( 14474 VectorType *VecTy, const DataLayout &DL) const { 14475 14476 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 14477 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 14478 14479 // Ensure the vector doesn't have f16 elements. Even though we could do an 14480 // i16 vldN, we can't hold the f16 vectors and will end up converting via 14481 // f32. 14482 if (VecTy->getElementType()->isHalfTy()) 14483 return false; 14484 14485 // Ensure the number of vector elements is greater than 1. 14486 if (VecTy->getNumElements() < 2) 14487 return false; 14488 14489 // Ensure the element type is legal. 14490 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 14491 return false; 14492 14493 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 14494 // 128 will be split into multiple interleaved accesses. 14495 return VecSize == 64 || VecSize % 128 == 0; 14496 } 14497 14498 /// Lower an interleaved load into a vldN intrinsic. 14499 /// 14500 /// E.g. Lower an interleaved load (Factor = 2): 14501 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 14502 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 14503 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 14504 /// 14505 /// Into: 14506 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 14507 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 14508 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 14509 bool ARMTargetLowering::lowerInterleavedLoad( 14510 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 14511 ArrayRef<unsigned> Indices, unsigned Factor) const { 14512 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14513 "Invalid interleave factor"); 14514 assert(!Shuffles.empty() && "Empty shufflevector input"); 14515 assert(Shuffles.size() == Indices.size() && 14516 "Unmatched number of shufflevectors and indices"); 14517 14518 VectorType *VecTy = Shuffles[0]->getType(); 14519 Type *EltTy = VecTy->getVectorElementType(); 14520 14521 const DataLayout &DL = LI->getModule()->getDataLayout(); 14522 14523 // Skip if we do not have NEON and skip illegal vector types. We can 14524 // "legalize" wide vector types into multiple interleaved accesses as long as 14525 // the vector types are divisible by 128. 14526 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 14527 return false; 14528 14529 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 14530 14531 // A pointer vector can not be the return type of the ldN intrinsics. Need to 14532 // load integer vectors first and then convert to pointer vectors. 14533 if (EltTy->isPointerTy()) 14534 VecTy = 14535 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 14536 14537 IRBuilder<> Builder(LI); 14538 14539 // The base address of the load. 14540 Value *BaseAddr = LI->getPointerOperand(); 14541 14542 if (NumLoads > 1) { 14543 // If we're going to generate more than one load, reset the sub-vector type 14544 // to something legal. 14545 VecTy = VectorType::get(VecTy->getVectorElementType(), 14546 VecTy->getVectorNumElements() / NumLoads); 14547 14548 // We will compute the pointer operand of each load from the original base 14549 // address using GEPs. Cast the base address to a pointer to the scalar 14550 // element type. 14551 BaseAddr = Builder.CreateBitCast( 14552 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 14553 LI->getPointerAddressSpace())); 14554 } 14555 14556 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 14557 14558 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 14559 Type *Tys[] = {VecTy, Int8Ptr}; 14560 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 14561 Intrinsic::arm_neon_vld3, 14562 Intrinsic::arm_neon_vld4}; 14563 Function *VldnFunc = 14564 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 14565 14566 // Holds sub-vectors extracted from the load intrinsic return values. The 14567 // sub-vectors are associated with the shufflevector instructions they will 14568 // replace. 14569 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 14570 14571 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 14572 // If we're generating more than one load, compute the base address of 14573 // subsequent loads as an offset from the previous. 14574 if (LoadCount > 0) 14575 BaseAddr = Builder.CreateConstGEP1_32( 14576 BaseAddr, VecTy->getVectorNumElements() * Factor); 14577 14578 SmallVector<Value *, 2> Ops; 14579 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14580 Ops.push_back(Builder.getInt32(LI->getAlignment())); 14581 14582 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 14583 14584 // Replace uses of each shufflevector with the corresponding vector loaded 14585 // by ldN. 14586 for (unsigned i = 0; i < Shuffles.size(); i++) { 14587 ShuffleVectorInst *SV = Shuffles[i]; 14588 unsigned Index = Indices[i]; 14589 14590 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 14591 14592 // Convert the integer vector to pointer vector if the element is pointer. 14593 if (EltTy->isPointerTy()) 14594 SubVec = Builder.CreateIntToPtr( 14595 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 14596 VecTy->getVectorNumElements())); 14597 14598 SubVecs[SV].push_back(SubVec); 14599 } 14600 } 14601 14602 // Replace uses of the shufflevector instructions with the sub-vectors 14603 // returned by the load intrinsic. If a shufflevector instruction is 14604 // associated with more than one sub-vector, those sub-vectors will be 14605 // concatenated into a single wide vector. 14606 for (ShuffleVectorInst *SVI : Shuffles) { 14607 auto &SubVec = SubVecs[SVI]; 14608 auto *WideVec = 14609 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 14610 SVI->replaceAllUsesWith(WideVec); 14611 } 14612 14613 return true; 14614 } 14615 14616 /// Lower an interleaved store into a vstN intrinsic. 14617 /// 14618 /// E.g. Lower an interleaved store (Factor = 3): 14619 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 14620 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 14621 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 14622 /// 14623 /// Into: 14624 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 14625 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 14626 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 14627 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14628 /// 14629 /// Note that the new shufflevectors will be removed and we'll only generate one 14630 /// vst3 instruction in CodeGen. 14631 /// 14632 /// Example for a more general valid mask (Factor 3). Lower: 14633 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 14634 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 14635 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 14636 /// 14637 /// Into: 14638 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 14639 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 14640 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 14641 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14642 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 14643 ShuffleVectorInst *SVI, 14644 unsigned Factor) const { 14645 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14646 "Invalid interleave factor"); 14647 14648 VectorType *VecTy = SVI->getType(); 14649 assert(VecTy->getVectorNumElements() % Factor == 0 && 14650 "Invalid interleaved store"); 14651 14652 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 14653 Type *EltTy = VecTy->getVectorElementType(); 14654 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 14655 14656 const DataLayout &DL = SI->getModule()->getDataLayout(); 14657 14658 // Skip if we do not have NEON and skip illegal vector types. We can 14659 // "legalize" wide vector types into multiple interleaved accesses as long as 14660 // the vector types are divisible by 128. 14661 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 14662 return false; 14663 14664 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 14665 14666 Value *Op0 = SVI->getOperand(0); 14667 Value *Op1 = SVI->getOperand(1); 14668 IRBuilder<> Builder(SI); 14669 14670 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 14671 // vectors to integer vectors. 14672 if (EltTy->isPointerTy()) { 14673 Type *IntTy = DL.getIntPtrType(EltTy); 14674 14675 // Convert to the corresponding integer vector. 14676 Type *IntVecTy = 14677 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 14678 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 14679 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 14680 14681 SubVecTy = VectorType::get(IntTy, LaneLen); 14682 } 14683 14684 // The base address of the store. 14685 Value *BaseAddr = SI->getPointerOperand(); 14686 14687 if (NumStores > 1) { 14688 // If we're going to generate more than one store, reset the lane length 14689 // and sub-vector type to something legal. 14690 LaneLen /= NumStores; 14691 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 14692 14693 // We will compute the pointer operand of each store from the original base 14694 // address using GEPs. Cast the base address to a pointer to the scalar 14695 // element type. 14696 BaseAddr = Builder.CreateBitCast( 14697 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 14698 SI->getPointerAddressSpace())); 14699 } 14700 14701 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 14702 14703 auto Mask = SVI->getShuffleMask(); 14704 14705 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 14706 Type *Tys[] = {Int8Ptr, SubVecTy}; 14707 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 14708 Intrinsic::arm_neon_vst3, 14709 Intrinsic::arm_neon_vst4}; 14710 14711 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 14712 // If we generating more than one store, we compute the base address of 14713 // subsequent stores as an offset from the previous. 14714 if (StoreCount > 0) 14715 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 14716 14717 SmallVector<Value *, 6> Ops; 14718 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14719 14720 Function *VstNFunc = 14721 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 14722 14723 // Split the shufflevector operands into sub vectors for the new vstN call. 14724 for (unsigned i = 0; i < Factor; i++) { 14725 unsigned IdxI = StoreCount * LaneLen * Factor + i; 14726 if (Mask[IdxI] >= 0) { 14727 Ops.push_back(Builder.CreateShuffleVector( 14728 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 14729 } else { 14730 unsigned StartMask = 0; 14731 for (unsigned j = 1; j < LaneLen; j++) { 14732 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 14733 if (Mask[IdxJ * Factor + IdxI] >= 0) { 14734 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 14735 break; 14736 } 14737 } 14738 // Note: If all elements in a chunk are undefs, StartMask=0! 14739 // Note: Filling undef gaps with random elements is ok, since 14740 // those elements were being written anyway (with undefs). 14741 // In the case of all undefs we're defaulting to using elems from 0 14742 // Note: StartMask cannot be negative, it's checked in 14743 // isReInterleaveMask 14744 Ops.push_back(Builder.CreateShuffleVector( 14745 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 14746 } 14747 } 14748 14749 Ops.push_back(Builder.getInt32(SI->getAlignment())); 14750 Builder.CreateCall(VstNFunc, Ops); 14751 } 14752 return true; 14753 } 14754 14755 enum HABaseType { 14756 HA_UNKNOWN = 0, 14757 HA_FLOAT, 14758 HA_DOUBLE, 14759 HA_VECT64, 14760 HA_VECT128 14761 }; 14762 14763 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 14764 uint64_t &Members) { 14765 if (auto *ST = dyn_cast<StructType>(Ty)) { 14766 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 14767 uint64_t SubMembers = 0; 14768 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 14769 return false; 14770 Members += SubMembers; 14771 } 14772 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 14773 uint64_t SubMembers = 0; 14774 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 14775 return false; 14776 Members += SubMembers * AT->getNumElements(); 14777 } else if (Ty->isFloatTy()) { 14778 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 14779 return false; 14780 Members = 1; 14781 Base = HA_FLOAT; 14782 } else if (Ty->isDoubleTy()) { 14783 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 14784 return false; 14785 Members = 1; 14786 Base = HA_DOUBLE; 14787 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 14788 Members = 1; 14789 switch (Base) { 14790 case HA_FLOAT: 14791 case HA_DOUBLE: 14792 return false; 14793 case HA_VECT64: 14794 return VT->getBitWidth() == 64; 14795 case HA_VECT128: 14796 return VT->getBitWidth() == 128; 14797 case HA_UNKNOWN: 14798 switch (VT->getBitWidth()) { 14799 case 64: 14800 Base = HA_VECT64; 14801 return true; 14802 case 128: 14803 Base = HA_VECT128; 14804 return true; 14805 default: 14806 return false; 14807 } 14808 } 14809 } 14810 14811 return (Members > 0 && Members <= 4); 14812 } 14813 14814 /// Return the correct alignment for the current calling convention. 14815 unsigned 14816 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy, 14817 DataLayout DL) const { 14818 if (!ArgTy->isVectorTy()) 14819 return DL.getABITypeAlignment(ArgTy); 14820 14821 // Avoid over-aligning vector parameters. It would require realigning the 14822 // stack and waste space for no real benefit. 14823 return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment()); 14824 } 14825 14826 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 14827 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 14828 /// passing according to AAPCS rules. 14829 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 14830 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 14831 if (getEffectiveCallingConv(CallConv, isVarArg) != 14832 CallingConv::ARM_AAPCS_VFP) 14833 return false; 14834 14835 HABaseType Base = HA_UNKNOWN; 14836 uint64_t Members = 0; 14837 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 14838 LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 14839 14840 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 14841 return IsHA || IsIntArray; 14842 } 14843 14844 unsigned ARMTargetLowering::getExceptionPointerRegister( 14845 const Constant *PersonalityFn) const { 14846 // Platforms which do not use SjLj EH may return values in these registers 14847 // via the personality function. 14848 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 14849 } 14850 14851 unsigned ARMTargetLowering::getExceptionSelectorRegister( 14852 const Constant *PersonalityFn) const { 14853 // Platforms which do not use SjLj EH may return values in these registers 14854 // via the personality function. 14855 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 14856 } 14857 14858 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14859 // Update IsSplitCSR in ARMFunctionInfo. 14860 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 14861 AFI->setIsSplitCSR(true); 14862 } 14863 14864 void ARMTargetLowering::insertCopiesSplitCSR( 14865 MachineBasicBlock *Entry, 14866 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14867 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 14868 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14869 if (!IStart) 14870 return; 14871 14872 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 14873 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14874 MachineBasicBlock::iterator MBBI = Entry->begin(); 14875 for (const MCPhysReg *I = IStart; *I; ++I) { 14876 const TargetRegisterClass *RC = nullptr; 14877 if (ARM::GPRRegClass.contains(*I)) 14878 RC = &ARM::GPRRegClass; 14879 else if (ARM::DPRRegClass.contains(*I)) 14880 RC = &ARM::DPRRegClass; 14881 else 14882 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14883 14884 unsigned NewVR = MRI->createVirtualRegister(RC); 14885 // Create copy from CSR to a virtual register. 14886 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14887 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14888 // nounwind. If we want to generalize this later, we may need to emit 14889 // CFI pseudo-instructions. 14890 assert(Entry->getParent()->getFunction().hasFnAttribute( 14891 Attribute::NoUnwind) && 14892 "Function should be nounwind in insertCopiesSplitCSR!"); 14893 Entry->addLiveIn(*I); 14894 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14895 .addReg(*I); 14896 14897 // Insert the copy-back instructions right before the terminator. 14898 for (auto *Exit : Exits) 14899 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14900 TII->get(TargetOpcode::COPY), *I) 14901 .addReg(NewVR); 14902 } 14903 } 14904 14905 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 14906 MF.getFrameInfo().computeMaxCallFrameSize(MF); 14907 TargetLoweringBase::finalizeLowering(MF); 14908 } 14909