1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that ARM uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "ARMISelLowering.h" 16 #include "ARMBaseInstrInfo.h" 17 #include "ARMBaseRegisterInfo.h" 18 #include "ARMCallingConv.h" 19 #include "ARMConstantPoolValue.h" 20 #include "ARMMachineFunctionInfo.h" 21 #include "ARMPerfectShuffle.h" 22 #include "ARMRegisterInfo.h" 23 #include "ARMSelectionDAGInfo.h" 24 #include "ARMSubtarget.h" 25 #include "MCTargetDesc/ARMAddressingModes.h" 26 #include "MCTargetDesc/ARMBaseInfo.h" 27 #include "Utils/ARMBaseInfo.h" 28 #include "llvm/ADT/APFloat.h" 29 #include "llvm/ADT/APInt.h" 30 #include "llvm/ADT/ArrayRef.h" 31 #include "llvm/ADT/BitVector.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/STLExtras.h" 34 #include "llvm/ADT/SmallPtrSet.h" 35 #include "llvm/ADT/SmallVector.h" 36 #include "llvm/ADT/Statistic.h" 37 #include "llvm/ADT/StringExtras.h" 38 #include "llvm/ADT/StringRef.h" 39 #include "llvm/ADT/StringSwitch.h" 40 #include "llvm/ADT/Triple.h" 41 #include "llvm/ADT/Twine.h" 42 #include "llvm/Analysis/VectorUtils.h" 43 #include "llvm/CodeGen/CallingConvLower.h" 44 #include "llvm/CodeGen/ISDOpcodes.h" 45 #include "llvm/CodeGen/IntrinsicLowering.h" 46 #include "llvm/CodeGen/MachineBasicBlock.h" 47 #include "llvm/CodeGen/MachineConstantPool.h" 48 #include "llvm/CodeGen/MachineFrameInfo.h" 49 #include "llvm/CodeGen/MachineFunction.h" 50 #include "llvm/CodeGen/MachineInstr.h" 51 #include "llvm/CodeGen/MachineInstrBuilder.h" 52 #include "llvm/CodeGen/MachineJumpTableInfo.h" 53 #include "llvm/CodeGen/MachineMemOperand.h" 54 #include "llvm/CodeGen/MachineOperand.h" 55 #include "llvm/CodeGen/MachineRegisterInfo.h" 56 #include "llvm/CodeGen/MachineValueType.h" 57 #include "llvm/CodeGen/RuntimeLibcalls.h" 58 #include "llvm/CodeGen/SelectionDAG.h" 59 #include "llvm/CodeGen/SelectionDAGNodes.h" 60 #include "llvm/CodeGen/TargetInstrInfo.h" 61 #include "llvm/CodeGen/TargetLowering.h" 62 #include "llvm/CodeGen/TargetOpcodes.h" 63 #include "llvm/CodeGen/TargetRegisterInfo.h" 64 #include "llvm/CodeGen/TargetSubtargetInfo.h" 65 #include "llvm/CodeGen/ValueTypes.h" 66 #include "llvm/IR/Attributes.h" 67 #include "llvm/IR/CallingConv.h" 68 #include "llvm/IR/Constant.h" 69 #include "llvm/IR/Constants.h" 70 #include "llvm/IR/DataLayout.h" 71 #include "llvm/IR/DebugLoc.h" 72 #include "llvm/IR/DerivedTypes.h" 73 #include "llvm/IR/Function.h" 74 #include "llvm/IR/GlobalAlias.h" 75 #include "llvm/IR/GlobalValue.h" 76 #include "llvm/IR/GlobalVariable.h" 77 #include "llvm/IR/IRBuilder.h" 78 #include "llvm/IR/InlineAsm.h" 79 #include "llvm/IR/Instruction.h" 80 #include "llvm/IR/Instructions.h" 81 #include "llvm/IR/IntrinsicInst.h" 82 #include "llvm/IR/Intrinsics.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Type.h" 85 #include "llvm/IR/User.h" 86 #include "llvm/IR/Value.h" 87 #include "llvm/MC/MCInstrDesc.h" 88 #include "llvm/MC/MCInstrItineraries.h" 89 #include "llvm/MC/MCRegisterInfo.h" 90 #include "llvm/MC/MCSchedule.h" 91 #include "llvm/Support/AtomicOrdering.h" 92 #include "llvm/Support/BranchProbability.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CodeGen.h" 95 #include "llvm/Support/CommandLine.h" 96 #include "llvm/Support/Compiler.h" 97 #include "llvm/Support/Debug.h" 98 #include "llvm/Support/ErrorHandling.h" 99 #include "llvm/Support/KnownBits.h" 100 #include "llvm/Support/MathExtras.h" 101 #include "llvm/Support/raw_ostream.h" 102 #include "llvm/Target/TargetMachine.h" 103 #include "llvm/Target/TargetOptions.h" 104 #include <algorithm> 105 #include <cassert> 106 #include <cstdint> 107 #include <cstdlib> 108 #include <iterator> 109 #include <limits> 110 #include <string> 111 #include <tuple> 112 #include <utility> 113 #include <vector> 114 115 using namespace llvm; 116 117 #define DEBUG_TYPE "arm-isel" 118 119 STATISTIC(NumTailCalls, "Number of tail calls"); 120 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 121 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 122 STATISTIC(NumConstpoolPromoted, 123 "Number of constants with their storage promoted into constant pools"); 124 125 static cl::opt<bool> 126 ARMInterworking("arm-interworking", cl::Hidden, 127 cl::desc("Enable / disable ARM interworking (for debugging only)"), 128 cl::init(true)); 129 130 static cl::opt<bool> EnableConstpoolPromotion( 131 "arm-promote-constant", cl::Hidden, 132 cl::desc("Enable / disable promotion of unnamed_addr constants into " 133 "constant pools"), 134 cl::init(false)); // FIXME: set to true by default once PR32780 is fixed 135 static cl::opt<unsigned> ConstpoolPromotionMaxSize( 136 "arm-promote-constant-max-size", cl::Hidden, 137 cl::desc("Maximum size of constant to promote into a constant pool"), 138 cl::init(64)); 139 static cl::opt<unsigned> ConstpoolPromotionMaxTotal( 140 "arm-promote-constant-max-total", cl::Hidden, 141 cl::desc("Maximum size of ALL constants to promote into a constant pool"), 142 cl::init(128)); 143 144 // The APCS parameter registers. 145 static const MCPhysReg GPRArgRegs[] = { 146 ARM::R0, ARM::R1, ARM::R2, ARM::R3 147 }; 148 149 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 150 MVT PromotedBitwiseVT) { 151 if (VT != PromotedLdStVT) { 152 setOperationAction(ISD::LOAD, VT, Promote); 153 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 154 155 setOperationAction(ISD::STORE, VT, Promote); 156 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 157 } 158 159 MVT ElemTy = VT.getVectorElementType(); 160 if (ElemTy != MVT::f64) 161 setOperationAction(ISD::SETCC, VT, Custom); 162 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 163 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 164 if (ElemTy == MVT::i32) { 165 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 166 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 167 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 168 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 169 } else { 170 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 171 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 172 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 173 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 174 } 175 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 176 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 177 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 178 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 179 setOperationAction(ISD::SELECT, VT, Expand); 180 setOperationAction(ISD::SELECT_CC, VT, Expand); 181 setOperationAction(ISD::VSELECT, VT, Expand); 182 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 183 if (VT.isInteger()) { 184 setOperationAction(ISD::SHL, VT, Custom); 185 setOperationAction(ISD::SRA, VT, Custom); 186 setOperationAction(ISD::SRL, VT, Custom); 187 } 188 189 // Promote all bit-wise operations. 190 if (VT.isInteger() && VT != PromotedBitwiseVT) { 191 setOperationAction(ISD::AND, VT, Promote); 192 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 193 setOperationAction(ISD::OR, VT, Promote); 194 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 195 setOperationAction(ISD::XOR, VT, Promote); 196 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 197 } 198 199 // Neon does not support vector divide/remainder operations. 200 setOperationAction(ISD::SDIV, VT, Expand); 201 setOperationAction(ISD::UDIV, VT, Expand); 202 setOperationAction(ISD::FDIV, VT, Expand); 203 setOperationAction(ISD::SREM, VT, Expand); 204 setOperationAction(ISD::UREM, VT, Expand); 205 setOperationAction(ISD::FREM, VT, Expand); 206 207 if (!VT.isFloatingPoint() && 208 VT != MVT::v2i64 && VT != MVT::v1i64) 209 for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 210 setOperationAction(Opcode, VT, Legal); 211 } 212 213 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 214 addRegisterClass(VT, &ARM::DPRRegClass); 215 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 216 } 217 218 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 219 addRegisterClass(VT, &ARM::DPairRegClass); 220 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 221 } 222 223 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM, 224 const ARMSubtarget &STI) 225 : TargetLowering(TM), Subtarget(&STI) { 226 RegInfo = Subtarget->getRegisterInfo(); 227 Itins = Subtarget->getInstrItineraryData(); 228 229 setBooleanContents(ZeroOrOneBooleanContent); 230 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 231 232 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() && 233 !Subtarget->isTargetWatchOS()) { 234 bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard; 235 for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID) 236 setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID), 237 IsHFTarget ? CallingConv::ARM_AAPCS_VFP 238 : CallingConv::ARM_AAPCS); 239 } 240 241 if (Subtarget->isTargetMachO()) { 242 // Uses VFP for Thumb libfuncs if available. 243 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 244 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) { 245 static const struct { 246 const RTLIB::Libcall Op; 247 const char * const Name; 248 const ISD::CondCode Cond; 249 } LibraryCalls[] = { 250 // Single-precision floating-point arithmetic. 251 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID }, 252 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID }, 253 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID }, 254 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID }, 255 256 // Double-precision floating-point arithmetic. 257 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID }, 258 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID }, 259 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID }, 260 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID }, 261 262 // Single-precision comparisons. 263 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE }, 264 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE }, 265 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE }, 266 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE }, 267 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE }, 268 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE }, 269 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE }, 270 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ }, 271 272 // Double-precision comparisons. 273 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE }, 274 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE }, 275 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE }, 276 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE }, 277 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE }, 278 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE }, 279 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE }, 280 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ }, 281 282 // Floating-point to integer conversions. 283 // i64 conversions are done via library routines even when generating VFP 284 // instructions, so use the same ones. 285 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID }, 286 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID }, 287 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID }, 288 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID }, 289 290 // Conversions between floating types. 291 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID }, 292 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID }, 293 294 // Integer to floating-point conversions. 295 // i64 conversions are done via library routines even when generating VFP 296 // instructions, so use the same ones. 297 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 298 // e.g., __floatunsidf vs. __floatunssidfvfp. 299 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID }, 300 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID }, 301 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID }, 302 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID }, 303 }; 304 305 for (const auto &LC : LibraryCalls) { 306 setLibcallName(LC.Op, LC.Name); 307 if (LC.Cond != ISD::SETCC_INVALID) 308 setCmpLibcallCC(LC.Op, LC.Cond); 309 } 310 } 311 312 // Set the correct calling convention for ARMv7k WatchOS. It's just 313 // AAPCS_VFP for functions as simple as libcalls. 314 if (Subtarget->isTargetWatchABI()) { 315 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) 316 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP); 317 } 318 } 319 320 // These libcalls are not available in 32-bit. 321 setLibcallName(RTLIB::SHL_I128, nullptr); 322 setLibcallName(RTLIB::SRL_I128, nullptr); 323 setLibcallName(RTLIB::SRA_I128, nullptr); 324 325 // RTLIB 326 if (Subtarget->isAAPCS_ABI() && 327 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() || 328 Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) { 329 static const struct { 330 const RTLIB::Libcall Op; 331 const char * const Name; 332 const CallingConv::ID CC; 333 const ISD::CondCode Cond; 334 } LibraryCalls[] = { 335 // Double-precision floating-point arithmetic helper functions 336 // RTABI chapter 4.1.2, Table 2 337 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 338 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 339 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 340 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 341 342 // Double-precision floating-point comparison helper functions 343 // RTABI chapter 4.1.2, Table 3 344 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 345 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 346 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 347 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 348 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 349 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 350 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 351 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 352 353 // Single-precision floating-point arithmetic helper functions 354 // RTABI chapter 4.1.2, Table 4 355 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 356 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 357 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 358 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 359 360 // Single-precision floating-point comparison helper functions 361 // RTABI chapter 4.1.2, Table 5 362 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE }, 363 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ }, 364 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE }, 365 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE }, 366 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE }, 367 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE }, 368 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE }, 369 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ }, 370 371 // Floating-point to integer conversions. 372 // RTABI chapter 4.1.2, Table 6 373 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 374 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 375 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 376 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 377 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 378 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 379 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 380 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 381 382 // Conversions between floating types. 383 // RTABI chapter 4.1.2, Table 7 384 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 385 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 386 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 387 388 // Integer to floating-point conversions. 389 // RTABI chapter 4.1.2, Table 8 390 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 391 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 392 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 393 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 394 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 395 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 396 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 397 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 398 399 // Long long helper functions 400 // RTABI chapter 4.2, Table 9 401 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 402 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 403 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 404 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 405 406 // Integer division functions 407 // RTABI chapter 4.3.1 408 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 409 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 410 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 411 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 412 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 413 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 414 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 415 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 416 }; 417 418 for (const auto &LC : LibraryCalls) { 419 setLibcallName(LC.Op, LC.Name); 420 setLibcallCallingConv(LC.Op, LC.CC); 421 if (LC.Cond != ISD::SETCC_INVALID) 422 setCmpLibcallCC(LC.Op, LC.Cond); 423 } 424 425 // EABI dependent RTLIB 426 if (TM.Options.EABIVersion == EABI::EABI4 || 427 TM.Options.EABIVersion == EABI::EABI5) { 428 static const struct { 429 const RTLIB::Libcall Op; 430 const char *const Name; 431 const CallingConv::ID CC; 432 const ISD::CondCode Cond; 433 } MemOpsLibraryCalls[] = { 434 // Memory operations 435 // RTABI chapter 4.3.4 436 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 437 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 438 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID }, 439 }; 440 441 for (const auto &LC : MemOpsLibraryCalls) { 442 setLibcallName(LC.Op, LC.Name); 443 setLibcallCallingConv(LC.Op, LC.CC); 444 if (LC.Cond != ISD::SETCC_INVALID) 445 setCmpLibcallCC(LC.Op, LC.Cond); 446 } 447 } 448 } 449 450 if (Subtarget->isTargetWindows()) { 451 static const struct { 452 const RTLIB::Libcall Op; 453 const char * const Name; 454 const CallingConv::ID CC; 455 } LibraryCalls[] = { 456 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP }, 457 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP }, 458 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP }, 459 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP }, 460 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP }, 461 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP }, 462 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP }, 463 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP }, 464 }; 465 466 for (const auto &LC : LibraryCalls) { 467 setLibcallName(LC.Op, LC.Name); 468 setLibcallCallingConv(LC.Op, LC.CC); 469 } 470 } 471 472 // Use divmod compiler-rt calls for iOS 5.0 and later. 473 if (Subtarget->isTargetMachO() && 474 !(Subtarget->isTargetIOS() && 475 Subtarget->getTargetTriple().isOSVersionLT(5, 0))) { 476 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 477 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 478 } 479 480 // The half <-> float conversion functions are always soft-float on 481 // non-watchos platforms, but are needed for some targets which use a 482 // hard-float calling convention by default. 483 if (!Subtarget->isTargetWatchABI()) { 484 if (Subtarget->isAAPCS_ABI()) { 485 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS); 486 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS); 487 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS); 488 } else { 489 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS); 490 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS); 491 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS); 492 } 493 } 494 495 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have 496 // a __gnu_ prefix (which is the default). 497 if (Subtarget->isTargetAEABI()) { 498 static const struct { 499 const RTLIB::Libcall Op; 500 const char * const Name; 501 const CallingConv::ID CC; 502 } LibraryCalls[] = { 503 { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS }, 504 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS }, 505 { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS }, 506 }; 507 508 for (const auto &LC : LibraryCalls) { 509 setLibcallName(LC.Op, LC.Name); 510 setLibcallCallingConv(LC.Op, LC.CC); 511 } 512 } 513 514 if (Subtarget->isThumb1Only()) 515 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 516 else 517 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 518 519 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 520 !Subtarget->isThumb1Only()) { 521 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 522 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 523 } 524 525 if (Subtarget->hasFullFP16()) { 526 addRegisterClass(MVT::f16, &ARM::HPRRegClass); 527 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 528 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 529 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 530 } 531 532 for (MVT VT : MVT::vector_valuetypes()) { 533 for (MVT InnerVT : MVT::vector_valuetypes()) { 534 setTruncStoreAction(VT, InnerVT, Expand); 535 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 536 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 537 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 538 } 539 540 setOperationAction(ISD::MULHS, VT, Expand); 541 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 542 setOperationAction(ISD::MULHU, VT, Expand); 543 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 544 545 setOperationAction(ISD::BSWAP, VT, Expand); 546 } 547 548 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 549 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 550 551 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom); 552 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom); 553 554 if (Subtarget->hasNEON()) { 555 addDRTypeForNEON(MVT::v2f32); 556 addDRTypeForNEON(MVT::v8i8); 557 addDRTypeForNEON(MVT::v4i16); 558 addDRTypeForNEON(MVT::v2i32); 559 addDRTypeForNEON(MVT::v1i64); 560 561 addQRTypeForNEON(MVT::v4f32); 562 addQRTypeForNEON(MVT::v2f64); 563 addQRTypeForNEON(MVT::v16i8); 564 addQRTypeForNEON(MVT::v8i16); 565 addQRTypeForNEON(MVT::v4i32); 566 addQRTypeForNEON(MVT::v2i64); 567 568 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 569 // neither Neon nor VFP support any arithmetic operations on it. 570 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 571 // supported for v4f32. 572 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 573 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 574 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 575 // FIXME: Code duplication: FDIV and FREM are expanded always, see 576 // ARMTargetLowering::addTypeForNEON method for details. 577 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 578 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 579 // FIXME: Create unittest. 580 // In another words, find a way when "copysign" appears in DAG with vector 581 // operands. 582 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 583 // FIXME: Code duplication: SETCC has custom operation action, see 584 // ARMTargetLowering::addTypeForNEON method for details. 585 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 586 // FIXME: Create unittest for FNEG and for FABS. 587 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 588 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 589 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 590 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 591 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 592 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 593 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 594 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 595 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 596 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 597 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 598 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 599 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 600 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 601 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 602 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 603 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 604 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 605 606 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 607 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 608 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 609 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 610 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 611 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 612 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 613 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 614 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 615 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 616 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 617 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 618 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 619 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 620 621 // Mark v2f32 intrinsics. 622 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 623 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 624 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 625 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 626 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 627 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 628 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 629 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 630 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 631 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 632 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 633 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 634 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 635 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 636 637 // Neon does not support some operations on v1i64 and v2i64 types. 638 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 639 // Custom handling for some quad-vector types to detect VMULL. 640 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 641 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 642 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 643 // Custom handling for some vector types to avoid expensive expansions 644 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 645 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 646 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 647 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 648 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 649 // a destination type that is wider than the source, and nor does 650 // it have a FP_TO_[SU]INT instruction with a narrower destination than 651 // source. 652 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 653 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 654 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 655 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 656 657 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 658 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 659 660 // NEON does not have single instruction CTPOP for vectors with element 661 // types wider than 8-bits. However, custom lowering can leverage the 662 // v8i8/v16i8 vcnt instruction. 663 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 664 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 665 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 666 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 667 setOperationAction(ISD::CTPOP, MVT::v1i64, Expand); 668 setOperationAction(ISD::CTPOP, MVT::v2i64, Expand); 669 670 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 671 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 672 673 // NEON does not have single instruction CTTZ for vectors. 674 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom); 675 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom); 676 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom); 677 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom); 678 679 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom); 680 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom); 681 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom); 682 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom); 683 684 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom); 685 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom); 686 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom); 687 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom); 688 689 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom); 690 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom); 691 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom); 692 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom); 693 694 // NEON only has FMA instructions as of VFP4. 695 if (!Subtarget->hasVFP4()) { 696 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 697 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 698 } 699 700 setTargetDAGCombine(ISD::INTRINSIC_VOID); 701 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 702 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 703 setTargetDAGCombine(ISD::SHL); 704 setTargetDAGCombine(ISD::SRL); 705 setTargetDAGCombine(ISD::SRA); 706 setTargetDAGCombine(ISD::SIGN_EXTEND); 707 setTargetDAGCombine(ISD::ZERO_EXTEND); 708 setTargetDAGCombine(ISD::ANY_EXTEND); 709 setTargetDAGCombine(ISD::BUILD_VECTOR); 710 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 711 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 712 setTargetDAGCombine(ISD::STORE); 713 setTargetDAGCombine(ISD::FP_TO_SINT); 714 setTargetDAGCombine(ISD::FP_TO_UINT); 715 setTargetDAGCombine(ISD::FDIV); 716 setTargetDAGCombine(ISD::LOAD); 717 718 // It is legal to extload from v4i8 to v4i16 or v4i32. 719 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16, 720 MVT::v2i32}) { 721 for (MVT VT : MVT::integer_vector_valuetypes()) { 722 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal); 723 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal); 724 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal); 725 } 726 } 727 } 728 729 if (Subtarget->isFPOnlySP()) { 730 // When targeting a floating-point unit with only single-precision 731 // operations, f64 is legal for the few double-precision instructions which 732 // are present However, no double-precision operations other than moves, 733 // loads and stores are provided by the hardware. 734 setOperationAction(ISD::FADD, MVT::f64, Expand); 735 setOperationAction(ISD::FSUB, MVT::f64, Expand); 736 setOperationAction(ISD::FMUL, MVT::f64, Expand); 737 setOperationAction(ISD::FMA, MVT::f64, Expand); 738 setOperationAction(ISD::FDIV, MVT::f64, Expand); 739 setOperationAction(ISD::FREM, MVT::f64, Expand); 740 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 741 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand); 742 setOperationAction(ISD::FNEG, MVT::f64, Expand); 743 setOperationAction(ISD::FABS, MVT::f64, Expand); 744 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 745 setOperationAction(ISD::FSIN, MVT::f64, Expand); 746 setOperationAction(ISD::FCOS, MVT::f64, Expand); 747 setOperationAction(ISD::FPOW, MVT::f64, Expand); 748 setOperationAction(ISD::FLOG, MVT::f64, Expand); 749 setOperationAction(ISD::FLOG2, MVT::f64, Expand); 750 setOperationAction(ISD::FLOG10, MVT::f64, Expand); 751 setOperationAction(ISD::FEXP, MVT::f64, Expand); 752 setOperationAction(ISD::FEXP2, MVT::f64, Expand); 753 setOperationAction(ISD::FCEIL, MVT::f64, Expand); 754 setOperationAction(ISD::FTRUNC, MVT::f64, Expand); 755 setOperationAction(ISD::FRINT, MVT::f64, Expand); 756 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand); 757 setOperationAction(ISD::FFLOOR, MVT::f64, Expand); 758 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 759 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 760 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 761 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 762 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom); 763 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom); 764 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 765 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom); 766 } 767 768 computeRegisterProperties(Subtarget->getRegisterInfo()); 769 770 // ARM does not have floating-point extending loads. 771 for (MVT VT : MVT::fp_valuetypes()) { 772 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 773 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 774 } 775 776 // ... or truncating stores 777 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 778 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 779 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 780 781 // ARM does not have i1 sign extending load. 782 for (MVT VT : MVT::integer_valuetypes()) 783 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 784 785 // ARM supports all 4 flavors of integer indexed load / store. 786 if (!Subtarget->isThumb1Only()) { 787 for (unsigned im = (unsigned)ISD::PRE_INC; 788 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 789 setIndexedLoadAction(im, MVT::i1, Legal); 790 setIndexedLoadAction(im, MVT::i8, Legal); 791 setIndexedLoadAction(im, MVT::i16, Legal); 792 setIndexedLoadAction(im, MVT::i32, Legal); 793 setIndexedStoreAction(im, MVT::i1, Legal); 794 setIndexedStoreAction(im, MVT::i8, Legal); 795 setIndexedStoreAction(im, MVT::i16, Legal); 796 setIndexedStoreAction(im, MVT::i32, Legal); 797 } 798 } else { 799 // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}. 800 setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal); 801 setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal); 802 } 803 804 setOperationAction(ISD::SADDO, MVT::i32, Custom); 805 setOperationAction(ISD::UADDO, MVT::i32, Custom); 806 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 807 setOperationAction(ISD::USUBO, MVT::i32, Custom); 808 809 setOperationAction(ISD::ADDCARRY, MVT::i32, Custom); 810 setOperationAction(ISD::SUBCARRY, MVT::i32, Custom); 811 812 // i64 operation support. 813 setOperationAction(ISD::MUL, MVT::i64, Expand); 814 setOperationAction(ISD::MULHU, MVT::i32, Expand); 815 if (Subtarget->isThumb1Only()) { 816 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 817 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 818 } 819 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 820 || (Subtarget->isThumb2() && !Subtarget->hasDSP())) 821 setOperationAction(ISD::MULHS, MVT::i32, Expand); 822 823 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 824 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 825 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 826 setOperationAction(ISD::SRL, MVT::i64, Custom); 827 setOperationAction(ISD::SRA, MVT::i64, Custom); 828 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom); 829 830 // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1. 831 if (Subtarget->isThumb1Only()) { 832 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 833 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 834 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 835 } 836 837 setOperationAction(ISD::ADDC, MVT::i32, Custom); 838 setOperationAction(ISD::ADDE, MVT::i32, Custom); 839 setOperationAction(ISD::SUBC, MVT::i32, Custom); 840 setOperationAction(ISD::SUBE, MVT::i32, Custom); 841 842 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) 843 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 844 845 // ARM does not have ROTL. 846 setOperationAction(ISD::ROTL, MVT::i32, Expand); 847 for (MVT VT : MVT::vector_valuetypes()) { 848 setOperationAction(ISD::ROTL, VT, Expand); 849 setOperationAction(ISD::ROTR, VT, Expand); 850 } 851 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 852 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 853 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 854 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 855 856 // @llvm.readcyclecounter requires the Performance Monitors extension. 857 // Default to the 0 expansion on unsupported platforms. 858 // FIXME: Technically there are older ARM CPUs that have 859 // implementation-specific ways of obtaining this information. 860 if (Subtarget->hasPerfMon()) 861 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 862 863 // Only ARMv6 has BSWAP. 864 if (!Subtarget->hasV6Ops()) 865 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 866 867 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 868 : Subtarget->hasDivideInARMMode(); 869 if (!hasDivide) { 870 // These are expanded into libcalls if the cpu doesn't have HW divider. 871 setOperationAction(ISD::SDIV, MVT::i32, LibCall); 872 setOperationAction(ISD::UDIV, MVT::i32, LibCall); 873 } 874 875 if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) { 876 setOperationAction(ISD::SDIV, MVT::i32, Custom); 877 setOperationAction(ISD::UDIV, MVT::i32, Custom); 878 879 setOperationAction(ISD::SDIV, MVT::i64, Custom); 880 setOperationAction(ISD::UDIV, MVT::i64, Custom); 881 } 882 883 setOperationAction(ISD::SREM, MVT::i32, Expand); 884 setOperationAction(ISD::UREM, MVT::i32, Expand); 885 886 // Register based DivRem for AEABI (RTABI 4.2) 887 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 888 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 889 Subtarget->isTargetWindows()) { 890 setOperationAction(ISD::SREM, MVT::i64, Custom); 891 setOperationAction(ISD::UREM, MVT::i64, Custom); 892 HasStandaloneRem = false; 893 894 if (Subtarget->isTargetWindows()) { 895 const struct { 896 const RTLIB::Libcall Op; 897 const char * const Name; 898 const CallingConv::ID CC; 899 } LibraryCalls[] = { 900 { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS }, 901 { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS }, 902 { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS }, 903 { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS }, 904 905 { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS }, 906 { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS }, 907 { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS }, 908 { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS }, 909 }; 910 911 for (const auto &LC : LibraryCalls) { 912 setLibcallName(LC.Op, LC.Name); 913 setLibcallCallingConv(LC.Op, LC.CC); 914 } 915 } else { 916 const struct { 917 const RTLIB::Libcall Op; 918 const char * const Name; 919 const CallingConv::ID CC; 920 } LibraryCalls[] = { 921 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 922 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 923 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS }, 924 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS }, 925 926 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 927 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 928 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS }, 929 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS }, 930 }; 931 932 for (const auto &LC : LibraryCalls) { 933 setLibcallName(LC.Op, LC.Name); 934 setLibcallCallingConv(LC.Op, LC.CC); 935 } 936 } 937 938 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 939 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 940 setOperationAction(ISD::SDIVREM, MVT::i64, Custom); 941 setOperationAction(ISD::UDIVREM, MVT::i64, Custom); 942 } else { 943 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 944 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 945 } 946 947 if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT()) 948 for (auto &VT : {MVT::f32, MVT::f64}) 949 setOperationAction(ISD::FPOWI, VT, Custom); 950 951 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 952 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 953 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 954 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 955 956 setOperationAction(ISD::TRAP, MVT::Other, Legal); 957 958 // Use the default implementation. 959 setOperationAction(ISD::VASTART, MVT::Other, Custom); 960 setOperationAction(ISD::VAARG, MVT::Other, Expand); 961 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 962 setOperationAction(ISD::VAEND, MVT::Other, Expand); 963 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 964 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 965 966 if (Subtarget->isTargetWindows()) 967 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 968 else 969 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 970 971 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 972 // the default expansion. 973 InsertFencesForAtomic = false; 974 if (Subtarget->hasAnyDataBarrier() && 975 (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) { 976 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 977 // to ldrex/strex loops already. 978 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 979 if (!Subtarget->isThumb() || !Subtarget->isMClass()) 980 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 981 982 // On v8, we have particularly efficient implementations of atomic fences 983 // if they can be combined with nearby atomic loads and stores. 984 if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) { 985 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc. 986 InsertFencesForAtomic = true; 987 } 988 } else { 989 // If there's anything we can use as a barrier, go through custom lowering 990 // for ATOMIC_FENCE. 991 // If target has DMB in thumb, Fences can be inserted. 992 if (Subtarget->hasDataBarrier()) 993 InsertFencesForAtomic = true; 994 995 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 996 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 997 998 // Set them all for expansion, which will force libcalls. 999 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 1000 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 1001 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 1002 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 1003 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 1004 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 1005 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 1006 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 1007 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 1008 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 1009 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 1010 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 1011 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 1012 // Unordered/Monotonic case. 1013 if (!InsertFencesForAtomic) { 1014 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 1015 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 1016 } 1017 } 1018 1019 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 1020 1021 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 1022 if (!Subtarget->hasV6Ops()) { 1023 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 1024 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 1025 } 1026 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 1027 1028 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1029 !Subtarget->isThumb1Only()) { 1030 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 1031 // iff target supports vfp2. 1032 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 1033 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 1034 } 1035 1036 // We want to custom lower some of our intrinsics. 1037 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1038 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 1039 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 1040 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 1041 if (Subtarget->useSjLjEH()) 1042 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 1043 1044 setOperationAction(ISD::SETCC, MVT::i32, Expand); 1045 setOperationAction(ISD::SETCC, MVT::f32, Expand); 1046 setOperationAction(ISD::SETCC, MVT::f64, Expand); 1047 setOperationAction(ISD::SELECT, MVT::i32, Custom); 1048 setOperationAction(ISD::SELECT, MVT::f32, Custom); 1049 setOperationAction(ISD::SELECT, MVT::f64, Custom); 1050 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1051 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 1052 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 1053 1054 // Thumb-1 cannot currently select ARMISD::SUBE. 1055 if (!Subtarget->isThumb1Only()) 1056 setOperationAction(ISD::SETCCE, MVT::i32, Custom); 1057 1058 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 1059 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 1060 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 1061 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 1062 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 1063 1064 // We don't support sin/cos/fmod/copysign/pow 1065 setOperationAction(ISD::FSIN, MVT::f64, Expand); 1066 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1067 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1068 setOperationAction(ISD::FCOS, MVT::f64, Expand); 1069 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 1070 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 1071 setOperationAction(ISD::FREM, MVT::f64, Expand); 1072 setOperationAction(ISD::FREM, MVT::f32, Expand); 1073 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() && 1074 !Subtarget->isThumb1Only()) { 1075 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 1076 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 1077 } 1078 setOperationAction(ISD::FPOW, MVT::f64, Expand); 1079 setOperationAction(ISD::FPOW, MVT::f32, Expand); 1080 1081 if (!Subtarget->hasVFP4()) { 1082 setOperationAction(ISD::FMA, MVT::f64, Expand); 1083 setOperationAction(ISD::FMA, MVT::f32, Expand); 1084 } 1085 1086 // Various VFP goodness 1087 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) { 1088 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded. 1089 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) { 1090 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 1091 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 1092 } 1093 1094 // fp16 is a special v7 extension that adds f16 <-> f32 conversions. 1095 if (!Subtarget->hasFP16()) { 1096 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 1097 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 1098 } 1099 } 1100 1101 // Use __sincos_stret if available. 1102 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 1103 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 1104 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1105 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1106 } 1107 1108 // FP-ARMv8 implements a lot of rounding-like FP operations. 1109 if (Subtarget->hasFPARMv8()) { 1110 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1111 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1112 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1113 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1114 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1115 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1116 setOperationAction(ISD::FMINNUM, MVT::f32, Legal); 1117 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal); 1118 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal); 1119 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal); 1120 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1121 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1122 1123 if (!Subtarget->isFPOnlySP()) { 1124 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1125 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1126 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1127 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1128 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1129 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1130 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 1131 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 1132 } 1133 } 1134 1135 if (Subtarget->hasNEON()) { 1136 // vmin and vmax aren't available in a scalar form, so we use 1137 // a NEON instruction with an undef lane instead. 1138 setOperationAction(ISD::FMINNAN, MVT::f32, Legal); 1139 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal); 1140 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal); 1141 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal); 1142 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal); 1143 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal); 1144 } 1145 1146 // We have target-specific dag combine patterns for the following nodes: 1147 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 1148 setTargetDAGCombine(ISD::ADD); 1149 setTargetDAGCombine(ISD::SUB); 1150 setTargetDAGCombine(ISD::MUL); 1151 setTargetDAGCombine(ISD::AND); 1152 setTargetDAGCombine(ISD::OR); 1153 setTargetDAGCombine(ISD::XOR); 1154 1155 if (Subtarget->hasV6Ops()) 1156 setTargetDAGCombine(ISD::SRL); 1157 1158 setStackPointerRegisterToSaveRestore(ARM::SP); 1159 1160 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() || 1161 !Subtarget->hasVFP2()) 1162 setSchedulingPreference(Sched::RegPressure); 1163 else 1164 setSchedulingPreference(Sched::Hybrid); 1165 1166 //// temporary - rewrite interface to use type 1167 MaxStoresPerMemset = 8; 1168 MaxStoresPerMemsetOptSize = 4; 1169 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 1170 MaxStoresPerMemcpyOptSize = 2; 1171 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 1172 MaxStoresPerMemmoveOptSize = 2; 1173 1174 // On ARM arguments smaller than 4 bytes are extended, so all arguments 1175 // are at least 4 bytes aligned. 1176 setMinStackArgumentAlignment(4); 1177 1178 // Prefer likely predicted branches to selects on out-of-order cores. 1179 PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder(); 1180 1181 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 1182 } 1183 1184 bool ARMTargetLowering::useSoftFloat() const { 1185 return Subtarget->useSoftFloat(); 1186 } 1187 1188 // FIXME: It might make sense to define the representative register class as the 1189 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 1190 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 1191 // SPR's representative would be DPR_VFP2. This should work well if register 1192 // pressure tracking were modified such that a register use would increment the 1193 // pressure of the register class's representative and all of it's super 1194 // classes' representatives transitively. We have not implemented this because 1195 // of the difficulty prior to coalescing of modeling operand register classes 1196 // due to the common occurrence of cross class copies and subregister insertions 1197 // and extractions. 1198 std::pair<const TargetRegisterClass *, uint8_t> 1199 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI, 1200 MVT VT) const { 1201 const TargetRegisterClass *RRC = nullptr; 1202 uint8_t Cost = 1; 1203 switch (VT.SimpleTy) { 1204 default: 1205 return TargetLowering::findRepresentativeClass(TRI, VT); 1206 // Use DPR as representative register class for all floating point 1207 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 1208 // the cost is 1 for both f32 and f64. 1209 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 1210 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 1211 RRC = &ARM::DPRRegClass; 1212 // When NEON is used for SP, only half of the register file is available 1213 // because operations that define both SP and DP results will be constrained 1214 // to the VFP2 class (D0-D15). We currently model this constraint prior to 1215 // coalescing by double-counting the SP regs. See the FIXME above. 1216 if (Subtarget->useNEONForSinglePrecisionFP()) 1217 Cost = 2; 1218 break; 1219 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1220 case MVT::v4f32: case MVT::v2f64: 1221 RRC = &ARM::DPRRegClass; 1222 Cost = 2; 1223 break; 1224 case MVT::v4i64: 1225 RRC = &ARM::DPRRegClass; 1226 Cost = 4; 1227 break; 1228 case MVT::v8i64: 1229 RRC = &ARM::DPRRegClass; 1230 Cost = 8; 1231 break; 1232 } 1233 return std::make_pair(RRC, Cost); 1234 } 1235 1236 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 1237 switch ((ARMISD::NodeType)Opcode) { 1238 case ARMISD::FIRST_NUMBER: break; 1239 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 1240 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 1241 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 1242 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL"; 1243 case ARMISD::CALL: return "ARMISD::CALL"; 1244 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 1245 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 1246 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 1247 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 1248 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 1249 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 1250 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 1251 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 1252 case ARMISD::CMP: return "ARMISD::CMP"; 1253 case ARMISD::CMN: return "ARMISD::CMN"; 1254 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 1255 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 1256 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 1257 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 1258 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 1259 1260 case ARMISD::CMOV: return "ARMISD::CMOV"; 1261 1262 case ARMISD::SSAT: return "ARMISD::SSAT"; 1263 case ARMISD::USAT: return "ARMISD::USAT"; 1264 1265 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 1266 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 1267 case ARMISD::RRX: return "ARMISD::RRX"; 1268 1269 case ARMISD::ADDC: return "ARMISD::ADDC"; 1270 case ARMISD::ADDE: return "ARMISD::ADDE"; 1271 case ARMISD::SUBC: return "ARMISD::SUBC"; 1272 case ARMISD::SUBE: return "ARMISD::SUBE"; 1273 1274 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 1275 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 1276 case ARMISD::VMOVhr: return "ARMISD::VMOVhr"; 1277 case ARMISD::VMOVrh: return "ARMISD::VMOVrh"; 1278 1279 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 1280 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP"; 1281 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH"; 1282 1283 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1284 1285 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1286 1287 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1288 1289 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1290 1291 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1292 1293 case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK"; 1294 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK"; 1295 1296 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1297 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1298 case ARMISD::VCGE: return "ARMISD::VCGE"; 1299 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1300 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1301 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1302 case ARMISD::VCGT: return "ARMISD::VCGT"; 1303 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1304 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1305 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1306 case ARMISD::VTST: return "ARMISD::VTST"; 1307 1308 case ARMISD::VSHL: return "ARMISD::VSHL"; 1309 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1310 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1311 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1312 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1313 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1314 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1315 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1316 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1317 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1318 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1319 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1320 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1321 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1322 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1323 case ARMISD::VSLI: return "ARMISD::VSLI"; 1324 case ARMISD::VSRI: return "ARMISD::VSRI"; 1325 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1326 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1327 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1328 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1329 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1330 case ARMISD::VDUP: return "ARMISD::VDUP"; 1331 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1332 case ARMISD::VEXT: return "ARMISD::VEXT"; 1333 case ARMISD::VREV64: return "ARMISD::VREV64"; 1334 case ARMISD::VREV32: return "ARMISD::VREV32"; 1335 case ARMISD::VREV16: return "ARMISD::VREV16"; 1336 case ARMISD::VZIP: return "ARMISD::VZIP"; 1337 case ARMISD::VUZP: return "ARMISD::VUZP"; 1338 case ARMISD::VTRN: return "ARMISD::VTRN"; 1339 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1340 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1341 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1342 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1343 case ARMISD::UMAAL: return "ARMISD::UMAAL"; 1344 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1345 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1346 case ARMISD::SMLALBB: return "ARMISD::SMLALBB"; 1347 case ARMISD::SMLALBT: return "ARMISD::SMLALBT"; 1348 case ARMISD::SMLALTB: return "ARMISD::SMLALTB"; 1349 case ARMISD::SMLALTT: return "ARMISD::SMLALTT"; 1350 case ARMISD::SMULWB: return "ARMISD::SMULWB"; 1351 case ARMISD::SMULWT: return "ARMISD::SMULWT"; 1352 case ARMISD::SMLALD: return "ARMISD::SMLALD"; 1353 case ARMISD::SMLALDX: return "ARMISD::SMLALDX"; 1354 case ARMISD::SMLSLD: return "ARMISD::SMLSLD"; 1355 case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX"; 1356 case ARMISD::SMMLAR: return "ARMISD::SMMLAR"; 1357 case ARMISD::SMMLSR: return "ARMISD::SMMLSR"; 1358 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1359 case ARMISD::BFI: return "ARMISD::BFI"; 1360 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1361 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1362 case ARMISD::VBSL: return "ARMISD::VBSL"; 1363 case ARMISD::MEMCPY: return "ARMISD::MEMCPY"; 1364 case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP"; 1365 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1366 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1367 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1368 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1369 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1370 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1371 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1372 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1373 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1374 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1375 case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD"; 1376 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1377 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1378 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1379 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1380 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1381 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1382 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1383 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1384 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1385 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1386 } 1387 return nullptr; 1388 } 1389 1390 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &, 1391 EVT VT) const { 1392 if (!VT.isVector()) 1393 return getPointerTy(DL); 1394 return VT.changeVectorElementTypeToInteger(); 1395 } 1396 1397 /// getRegClassFor - Return the register class that should be used for the 1398 /// specified value type. 1399 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1400 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1401 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1402 // load / store 4 to 8 consecutive D registers. 1403 if (Subtarget->hasNEON()) { 1404 if (VT == MVT::v4i64) 1405 return &ARM::QQPRRegClass; 1406 if (VT == MVT::v8i64) 1407 return &ARM::QQQQPRRegClass; 1408 } 1409 return TargetLowering::getRegClassFor(VT); 1410 } 1411 1412 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the 1413 // source/dest is aligned and the copy size is large enough. We therefore want 1414 // to align such objects passed to memory intrinsics. 1415 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize, 1416 unsigned &PrefAlign) const { 1417 if (!isa<MemIntrinsic>(CI)) 1418 return false; 1419 MinSize = 8; 1420 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1 1421 // cycle faster than 4-byte aligned LDM. 1422 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4); 1423 return true; 1424 } 1425 1426 // Create a fast isel object. 1427 FastISel * 1428 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1429 const TargetLibraryInfo *libInfo) const { 1430 return ARM::createFastISel(funcInfo, libInfo); 1431 } 1432 1433 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1434 unsigned NumVals = N->getNumValues(); 1435 if (!NumVals) 1436 return Sched::RegPressure; 1437 1438 for (unsigned i = 0; i != NumVals; ++i) { 1439 EVT VT = N->getValueType(i); 1440 if (VT == MVT::Glue || VT == MVT::Other) 1441 continue; 1442 if (VT.isFloatingPoint() || VT.isVector()) 1443 return Sched::ILP; 1444 } 1445 1446 if (!N->isMachineOpcode()) 1447 return Sched::RegPressure; 1448 1449 // Load are scheduled for latency even if there instruction itinerary 1450 // is not available. 1451 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1452 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1453 1454 if (MCID.getNumDefs() == 0) 1455 return Sched::RegPressure; 1456 if (!Itins->isEmpty() && 1457 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1458 return Sched::ILP; 1459 1460 return Sched::RegPressure; 1461 } 1462 1463 //===----------------------------------------------------------------------===// 1464 // Lowering Code 1465 //===----------------------------------------------------------------------===// 1466 1467 static bool isSRL16(const SDValue &Op) { 1468 if (Op.getOpcode() != ISD::SRL) 1469 return false; 1470 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1471 return Const->getZExtValue() == 16; 1472 return false; 1473 } 1474 1475 static bool isSRA16(const SDValue &Op) { 1476 if (Op.getOpcode() != ISD::SRA) 1477 return false; 1478 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1479 return Const->getZExtValue() == 16; 1480 return false; 1481 } 1482 1483 static bool isSHL16(const SDValue &Op) { 1484 if (Op.getOpcode() != ISD::SHL) 1485 return false; 1486 if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 1487 return Const->getZExtValue() == 16; 1488 return false; 1489 } 1490 1491 // Check for a signed 16-bit value. We special case SRA because it makes it 1492 // more simple when also looking for SRAs that aren't sign extending a 1493 // smaller value. Without the check, we'd need to take extra care with 1494 // checking order for some operations. 1495 static bool isS16(const SDValue &Op, SelectionDAG &DAG) { 1496 if (isSRA16(Op)) 1497 return isSHL16(Op.getOperand(0)); 1498 return DAG.ComputeNumSignBits(Op) == 17; 1499 } 1500 1501 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1502 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1503 switch (CC) { 1504 default: llvm_unreachable("Unknown condition code!"); 1505 case ISD::SETNE: return ARMCC::NE; 1506 case ISD::SETEQ: return ARMCC::EQ; 1507 case ISD::SETGT: return ARMCC::GT; 1508 case ISD::SETGE: return ARMCC::GE; 1509 case ISD::SETLT: return ARMCC::LT; 1510 case ISD::SETLE: return ARMCC::LE; 1511 case ISD::SETUGT: return ARMCC::HI; 1512 case ISD::SETUGE: return ARMCC::HS; 1513 case ISD::SETULT: return ARMCC::LO; 1514 case ISD::SETULE: return ARMCC::LS; 1515 } 1516 } 1517 1518 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1519 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1520 ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) { 1521 CondCode2 = ARMCC::AL; 1522 InvalidOnQNaN = true; 1523 switch (CC) { 1524 default: llvm_unreachable("Unknown FP condition!"); 1525 case ISD::SETEQ: 1526 case ISD::SETOEQ: 1527 CondCode = ARMCC::EQ; 1528 InvalidOnQNaN = false; 1529 break; 1530 case ISD::SETGT: 1531 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1532 case ISD::SETGE: 1533 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1534 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1535 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1536 case ISD::SETONE: 1537 CondCode = ARMCC::MI; 1538 CondCode2 = ARMCC::GT; 1539 InvalidOnQNaN = false; 1540 break; 1541 case ISD::SETO: CondCode = ARMCC::VC; break; 1542 case ISD::SETUO: CondCode = ARMCC::VS; break; 1543 case ISD::SETUEQ: 1544 CondCode = ARMCC::EQ; 1545 CondCode2 = ARMCC::VS; 1546 InvalidOnQNaN = false; 1547 break; 1548 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1549 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1550 case ISD::SETLT: 1551 case ISD::SETULT: CondCode = ARMCC::LT; break; 1552 case ISD::SETLE: 1553 case ISD::SETULE: CondCode = ARMCC::LE; break; 1554 case ISD::SETNE: 1555 case ISD::SETUNE: 1556 CondCode = ARMCC::NE; 1557 InvalidOnQNaN = false; 1558 break; 1559 } 1560 } 1561 1562 //===----------------------------------------------------------------------===// 1563 // Calling Convention Implementation 1564 //===----------------------------------------------------------------------===// 1565 1566 #include "ARMGenCallingConv.inc" 1567 1568 /// getEffectiveCallingConv - Get the effective calling convention, taking into 1569 /// account presence of floating point hardware and calling convention 1570 /// limitations, such as support for variadic functions. 1571 CallingConv::ID 1572 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC, 1573 bool isVarArg) const { 1574 switch (CC) { 1575 default: 1576 report_fatal_error("Unsupported calling convention"); 1577 case CallingConv::ARM_AAPCS: 1578 case CallingConv::ARM_APCS: 1579 case CallingConv::GHC: 1580 return CC; 1581 case CallingConv::PreserveMost: 1582 return CallingConv::PreserveMost; 1583 case CallingConv::ARM_AAPCS_VFP: 1584 case CallingConv::Swift: 1585 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP; 1586 case CallingConv::C: 1587 if (!Subtarget->isAAPCS_ABI()) 1588 return CallingConv::ARM_APCS; 1589 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && 1590 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1591 !isVarArg) 1592 return CallingConv::ARM_AAPCS_VFP; 1593 else 1594 return CallingConv::ARM_AAPCS; 1595 case CallingConv::Fast: 1596 case CallingConv::CXX_FAST_TLS: 1597 if (!Subtarget->isAAPCS_ABI()) { 1598 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1599 return CallingConv::Fast; 1600 return CallingConv::ARM_APCS; 1601 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg) 1602 return CallingConv::ARM_AAPCS_VFP; 1603 else 1604 return CallingConv::ARM_AAPCS; 1605 } 1606 } 1607 1608 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC, 1609 bool isVarArg) const { 1610 return CCAssignFnForNode(CC, false, isVarArg); 1611 } 1612 1613 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC, 1614 bool isVarArg) const { 1615 return CCAssignFnForNode(CC, true, isVarArg); 1616 } 1617 1618 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given 1619 /// CallingConvention. 1620 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1621 bool Return, 1622 bool isVarArg) const { 1623 switch (getEffectiveCallingConv(CC, isVarArg)) { 1624 default: 1625 report_fatal_error("Unsupported calling convention"); 1626 case CallingConv::ARM_APCS: 1627 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1628 case CallingConv::ARM_AAPCS: 1629 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1630 case CallingConv::ARM_AAPCS_VFP: 1631 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1632 case CallingConv::Fast: 1633 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1634 case CallingConv::GHC: 1635 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1636 case CallingConv::PreserveMost: 1637 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1638 } 1639 } 1640 1641 /// LowerCallResult - Lower the result values of a call into the 1642 /// appropriate copies out of appropriate physical registers. 1643 SDValue ARMTargetLowering::LowerCallResult( 1644 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 1645 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 1646 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 1647 SDValue ThisVal) const { 1648 // Assign locations to each value returned by this call. 1649 SmallVector<CCValAssign, 16> RVLocs; 1650 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1651 *DAG.getContext()); 1652 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg)); 1653 1654 // Copy all of the result registers out of their specified physreg. 1655 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1656 CCValAssign VA = RVLocs[i]; 1657 1658 // Pass 'this' value directly from the argument to return value, to avoid 1659 // reg unit interference 1660 if (i == 0 && isThisReturn) { 1661 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1662 "unexpected return calling convention register assignment"); 1663 InVals.push_back(ThisVal); 1664 continue; 1665 } 1666 1667 SDValue Val; 1668 if (VA.needsCustom()) { 1669 // Handle f64 or half of a v2f64. 1670 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1671 InFlag); 1672 Chain = Lo.getValue(1); 1673 InFlag = Lo.getValue(2); 1674 VA = RVLocs[++i]; // skip ahead to next loc 1675 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1676 InFlag); 1677 Chain = Hi.getValue(1); 1678 InFlag = Hi.getValue(2); 1679 if (!Subtarget->isLittle()) 1680 std::swap (Lo, Hi); 1681 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1682 1683 if (VA.getLocVT() == MVT::v2f64) { 1684 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1685 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1686 DAG.getConstant(0, dl, MVT::i32)); 1687 1688 VA = RVLocs[++i]; // skip ahead to next loc 1689 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1690 Chain = Lo.getValue(1); 1691 InFlag = Lo.getValue(2); 1692 VA = RVLocs[++i]; // skip ahead to next loc 1693 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1694 Chain = Hi.getValue(1); 1695 InFlag = Hi.getValue(2); 1696 if (!Subtarget->isLittle()) 1697 std::swap (Lo, Hi); 1698 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1699 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1700 DAG.getConstant(1, dl, MVT::i32)); 1701 } 1702 } else { 1703 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1704 InFlag); 1705 Chain = Val.getValue(1); 1706 InFlag = Val.getValue(2); 1707 } 1708 1709 switch (VA.getLocInfo()) { 1710 default: llvm_unreachable("Unknown loc info!"); 1711 case CCValAssign::Full: break; 1712 case CCValAssign::BCvt: 1713 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1714 break; 1715 } 1716 1717 InVals.push_back(Val); 1718 } 1719 1720 return Chain; 1721 } 1722 1723 /// LowerMemOpCallTo - Store the argument to the stack. 1724 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr, 1725 SDValue Arg, const SDLoc &dl, 1726 SelectionDAG &DAG, 1727 const CCValAssign &VA, 1728 ISD::ArgFlagsTy Flags) const { 1729 unsigned LocMemOffset = VA.getLocMemOffset(); 1730 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1731 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 1732 StackPtr, PtrOff); 1733 return DAG.getStore( 1734 Chain, dl, Arg, PtrOff, 1735 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset)); 1736 } 1737 1738 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, 1739 SDValue Chain, SDValue &Arg, 1740 RegsToPassVector &RegsToPass, 1741 CCValAssign &VA, CCValAssign &NextVA, 1742 SDValue &StackPtr, 1743 SmallVectorImpl<SDValue> &MemOpChains, 1744 ISD::ArgFlagsTy Flags) const { 1745 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1746 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1747 unsigned id = Subtarget->isLittle() ? 0 : 1; 1748 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id))); 1749 1750 if (NextVA.isRegLoc()) 1751 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id))); 1752 else { 1753 assert(NextVA.isMemLoc()); 1754 if (!StackPtr.getNode()) 1755 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, 1756 getPointerTy(DAG.getDataLayout())); 1757 1758 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id), 1759 dl, DAG, NextVA, 1760 Flags)); 1761 } 1762 } 1763 1764 /// LowerCall - Lowering a call into a callseq_start <- 1765 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1766 /// nodes. 1767 SDValue 1768 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1769 SmallVectorImpl<SDValue> &InVals) const { 1770 SelectionDAG &DAG = CLI.DAG; 1771 SDLoc &dl = CLI.DL; 1772 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1773 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1774 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1775 SDValue Chain = CLI.Chain; 1776 SDValue Callee = CLI.Callee; 1777 bool &isTailCall = CLI.IsTailCall; 1778 CallingConv::ID CallConv = CLI.CallConv; 1779 bool doesNotRet = CLI.DoesNotReturn; 1780 bool isVarArg = CLI.IsVarArg; 1781 1782 MachineFunction &MF = DAG.getMachineFunction(); 1783 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1784 bool isThisReturn = false; 1785 bool isSibCall = false; 1786 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls"); 1787 1788 // Disable tail calls if they're not supported. 1789 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true") 1790 isTailCall = false; 1791 1792 if (isTailCall) { 1793 // Check if it's really possible to do a tail call. 1794 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1795 isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(), 1796 Outs, OutVals, Ins, DAG); 1797 if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall()) 1798 report_fatal_error("failed to perform tail call elimination on a call " 1799 "site marked musttail"); 1800 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1801 // detected sibcalls. 1802 if (isTailCall) { 1803 ++NumTailCalls; 1804 isSibCall = true; 1805 } 1806 } 1807 1808 // Analyze operands of the call, assigning locations to each operand. 1809 SmallVector<CCValAssign, 16> ArgLocs; 1810 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1811 *DAG.getContext()); 1812 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg)); 1813 1814 // Get a count of how many bytes are to be pushed on the stack. 1815 unsigned NumBytes = CCInfo.getNextStackOffset(); 1816 1817 // For tail calls, memory operands are available in our caller's stack. 1818 if (isSibCall) 1819 NumBytes = 0; 1820 1821 // Adjust the stack pointer for the new arguments... 1822 // These operations are automatically eliminated by the prolog/epilog pass 1823 if (!isSibCall) 1824 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 1825 1826 SDValue StackPtr = 1827 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout())); 1828 1829 RegsToPassVector RegsToPass; 1830 SmallVector<SDValue, 8> MemOpChains; 1831 1832 // Walk the register/memloc assignments, inserting copies/loads. In the case 1833 // of tail call optimization, arguments are handled later. 1834 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1835 i != e; 1836 ++i, ++realArgIdx) { 1837 CCValAssign &VA = ArgLocs[i]; 1838 SDValue Arg = OutVals[realArgIdx]; 1839 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1840 bool isByVal = Flags.isByVal(); 1841 1842 // Promote the value if needed. 1843 switch (VA.getLocInfo()) { 1844 default: llvm_unreachable("Unknown loc info!"); 1845 case CCValAssign::Full: break; 1846 case CCValAssign::SExt: 1847 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1848 break; 1849 case CCValAssign::ZExt: 1850 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1851 break; 1852 case CCValAssign::AExt: 1853 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1854 break; 1855 case CCValAssign::BCvt: 1856 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1857 break; 1858 } 1859 1860 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1861 if (VA.needsCustom()) { 1862 if (VA.getLocVT() == MVT::v2f64) { 1863 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1864 DAG.getConstant(0, dl, MVT::i32)); 1865 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1866 DAG.getConstant(1, dl, MVT::i32)); 1867 1868 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1869 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1870 1871 VA = ArgLocs[++i]; // skip ahead to next loc 1872 if (VA.isRegLoc()) { 1873 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1874 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1875 } else { 1876 assert(VA.isMemLoc()); 1877 1878 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1879 dl, DAG, VA, Flags)); 1880 } 1881 } else { 1882 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1883 StackPtr, MemOpChains, Flags); 1884 } 1885 } else if (VA.isRegLoc()) { 1886 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 1887 Outs[0].VT == MVT::i32) { 1888 assert(VA.getLocVT() == MVT::i32 && 1889 "unexpected calling convention register assignment"); 1890 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1891 "unexpected use of 'returned'"); 1892 isThisReturn = true; 1893 } 1894 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1895 } else if (isByVal) { 1896 assert(VA.isMemLoc()); 1897 unsigned offset = 0; 1898 1899 // True if this byval aggregate will be split between registers 1900 // and memory. 1901 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1902 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed(); 1903 1904 if (CurByValIdx < ByValArgsCount) { 1905 1906 unsigned RegBegin, RegEnd; 1907 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1908 1909 EVT PtrVT = 1910 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1911 unsigned int i, j; 1912 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1913 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32); 1914 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1915 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1916 MachinePointerInfo(), 1917 DAG.InferPtrAlignment(AddArg)); 1918 MemOpChains.push_back(Load.getValue(1)); 1919 RegsToPass.push_back(std::make_pair(j, Load)); 1920 } 1921 1922 // If parameter size outsides register area, "offset" value 1923 // helps us to calculate stack slot for remained part properly. 1924 offset = RegEnd - RegBegin; 1925 1926 CCInfo.nextInRegsParam(); 1927 } 1928 1929 if (Flags.getByValSize() > 4*offset) { 1930 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1931 unsigned LocMemOffset = VA.getLocMemOffset(); 1932 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 1933 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff); 1934 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl); 1935 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset); 1936 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl, 1937 MVT::i32); 1938 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl, 1939 MVT::i32); 1940 1941 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1942 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1943 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1944 Ops)); 1945 } 1946 } else if (!isSibCall) { 1947 assert(VA.isMemLoc()); 1948 1949 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1950 dl, DAG, VA, Flags)); 1951 } 1952 } 1953 1954 if (!MemOpChains.empty()) 1955 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 1956 1957 // Build a sequence of copy-to-reg nodes chained together with token chain 1958 // and flag operands which copy the outgoing args into the appropriate regs. 1959 SDValue InFlag; 1960 // Tail call byval lowering might overwrite argument registers so in case of 1961 // tail call optimization the copies to registers are lowered later. 1962 if (!isTailCall) 1963 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1964 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1965 RegsToPass[i].second, InFlag); 1966 InFlag = Chain.getValue(1); 1967 } 1968 1969 // For tail calls lower the arguments to the 'real' stack slot. 1970 if (isTailCall) { 1971 // Force all the incoming stack arguments to be loaded from the stack 1972 // before any new outgoing arguments are stored to the stack, because the 1973 // outgoing stack slots may alias the incoming argument stack slots, and 1974 // the alias isn't otherwise explicit. This is slightly more conservative 1975 // than necessary, because it means that each store effectively depends 1976 // on every argument instead of just those arguments it would clobber. 1977 1978 // Do not flag preceding copytoreg stuff together with the following stuff. 1979 InFlag = SDValue(); 1980 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1981 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1982 RegsToPass[i].second, InFlag); 1983 InFlag = Chain.getValue(1); 1984 } 1985 InFlag = SDValue(); 1986 } 1987 1988 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1989 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1990 // node so that legalize doesn't hack it. 1991 bool isDirect = false; 1992 1993 const TargetMachine &TM = getTargetMachine(); 1994 const Module *Mod = MF.getFunction().getParent(); 1995 const GlobalValue *GV = nullptr; 1996 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 1997 GV = G->getGlobal(); 1998 bool isStub = 1999 !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO(); 2000 2001 bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass()); 2002 bool isLocalARMFunc = false; 2003 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2004 auto PtrVt = getPointerTy(DAG.getDataLayout()); 2005 2006 if (Subtarget->genLongCalls()) { 2007 assert((!isPositionIndependent() || Subtarget->isTargetWindows()) && 2008 "long-calls codegen is not position independent!"); 2009 // Handle a global address or an external symbol. If it's not one of 2010 // those, the target's already in a register, so we don't need to do 2011 // anything extra. 2012 if (isa<GlobalAddressSDNode>(Callee)) { 2013 // Create a constant pool entry for the callee address 2014 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2015 ARMConstantPoolValue *CPV = 2016 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 2017 2018 // Get the address of the callee into a register 2019 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2020 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2021 Callee = DAG.getLoad( 2022 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2023 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2024 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 2025 const char *Sym = S->getSymbol(); 2026 2027 // Create a constant pool entry for the callee address 2028 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2029 ARMConstantPoolValue *CPV = 2030 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2031 ARMPCLabelIndex, 0); 2032 // Get the address of the callee into a register 2033 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2034 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2035 Callee = DAG.getLoad( 2036 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2037 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2038 } 2039 } else if (isa<GlobalAddressSDNode>(Callee)) { 2040 // If we're optimizing for minimum size and the function is called three or 2041 // more times in this block, we can improve codesize by calling indirectly 2042 // as BLXr has a 16-bit encoding. 2043 auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 2044 auto *BB = CLI.CS.getParent(); 2045 bool PreferIndirect = 2046 Subtarget->isThumb() && MF.getFunction().optForMinSize() && 2047 count_if(GV->users(), [&BB](const User *U) { 2048 return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB; 2049 }) > 2; 2050 2051 if (!PreferIndirect) { 2052 isDirect = true; 2053 bool isDef = GV->isStrongDefinitionForLinker(); 2054 2055 // ARM call to a local ARM function is predicable. 2056 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking); 2057 // tBX takes a register source operand. 2058 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2059 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 2060 Callee = DAG.getNode( 2061 ARMISD::WrapperPIC, dl, PtrVt, 2062 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY)); 2063 Callee = DAG.getLoad( 2064 PtrVt, dl, DAG.getEntryNode(), Callee, 2065 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2066 /* Alignment = */ 0, MachineMemOperand::MODereferenceable | 2067 MachineMemOperand::MOInvariant); 2068 } else if (Subtarget->isTargetCOFF()) { 2069 assert(Subtarget->isTargetWindows() && 2070 "Windows is the only supported COFF target"); 2071 unsigned TargetFlags = GV->hasDLLImportStorageClass() 2072 ? ARMII::MO_DLLIMPORT 2073 : ARMII::MO_NO_FLAG; 2074 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, 2075 TargetFlags); 2076 if (GV->hasDLLImportStorageClass()) 2077 Callee = 2078 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), 2079 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee), 2080 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 2081 } else { 2082 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0); 2083 } 2084 } 2085 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2086 isDirect = true; 2087 // tBX takes a register source operand. 2088 const char *Sym = S->getSymbol(); 2089 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 2090 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2091 ARMConstantPoolValue *CPV = 2092 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 2093 ARMPCLabelIndex, 4); 2094 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4); 2095 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2096 Callee = DAG.getLoad( 2097 PtrVt, dl, DAG.getEntryNode(), CPAddr, 2098 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2099 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2100 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel); 2101 } else { 2102 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0); 2103 } 2104 } 2105 2106 // FIXME: handle tail calls differently. 2107 unsigned CallOpc; 2108 if (Subtarget->isThumb()) { 2109 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 2110 CallOpc = ARMISD::CALL_NOLINK; 2111 else 2112 CallOpc = ARMISD::CALL; 2113 } else { 2114 if (!isDirect && !Subtarget->hasV5TOps()) 2115 CallOpc = ARMISD::CALL_NOLINK; 2116 else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() && 2117 // Emit regular call when code size is the priority 2118 !MF.getFunction().optForMinSize()) 2119 // "mov lr, pc; b _foo" to avoid confusing the RSP 2120 CallOpc = ARMISD::CALL_NOLINK; 2121 else 2122 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 2123 } 2124 2125 std::vector<SDValue> Ops; 2126 Ops.push_back(Chain); 2127 Ops.push_back(Callee); 2128 2129 // Add argument registers to the end of the list so that they are known live 2130 // into the call. 2131 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2132 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2133 RegsToPass[i].second.getValueType())); 2134 2135 // Add a register mask operand representing the call-preserved registers. 2136 if (!isTailCall) { 2137 const uint32_t *Mask; 2138 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo(); 2139 if (isThisReturn) { 2140 // For 'this' returns, use the R0-preserving mask if applicable 2141 Mask = ARI->getThisReturnPreservedMask(MF, CallConv); 2142 if (!Mask) { 2143 // Set isThisReturn to false if the calling convention is not one that 2144 // allows 'returned' to be modeled in this way, so LowerCallResult does 2145 // not try to pass 'this' straight through 2146 isThisReturn = false; 2147 Mask = ARI->getCallPreservedMask(MF, CallConv); 2148 } 2149 } else 2150 Mask = ARI->getCallPreservedMask(MF, CallConv); 2151 2152 assert(Mask && "Missing call preserved mask for calling convention"); 2153 Ops.push_back(DAG.getRegisterMask(Mask)); 2154 } 2155 2156 if (InFlag.getNode()) 2157 Ops.push_back(InFlag); 2158 2159 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2160 if (isTailCall) { 2161 MF.getFrameInfo().setHasTailCall(); 2162 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops); 2163 } 2164 2165 // Returns a chain and a flag for retval copy to use. 2166 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 2167 InFlag = Chain.getValue(1); 2168 2169 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 2170 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 2171 if (!Ins.empty()) 2172 InFlag = Chain.getValue(1); 2173 2174 // Handle result values, copying them out of physregs into vregs that we 2175 // return. 2176 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 2177 InVals, isThisReturn, 2178 isThisReturn ? OutVals[0] : SDValue()); 2179 } 2180 2181 /// HandleByVal - Every parameter *after* a byval parameter is passed 2182 /// on the stack. Remember the next parameter register to allocate, 2183 /// and then confiscate the rest of the parameter registers to insure 2184 /// this. 2185 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size, 2186 unsigned Align) const { 2187 // Byval (as with any stack) slots are always at least 4 byte aligned. 2188 Align = std::max(Align, 4U); 2189 2190 unsigned Reg = State->AllocateReg(GPRArgRegs); 2191 if (!Reg) 2192 return; 2193 2194 unsigned AlignInRegs = Align / 4; 2195 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs; 2196 for (unsigned i = 0; i < Waste; ++i) 2197 Reg = State->AllocateReg(GPRArgRegs); 2198 2199 if (!Reg) 2200 return; 2201 2202 unsigned Excess = 4 * (ARM::R4 - Reg); 2203 2204 // Special case when NSAA != SP and parameter size greater than size of 2205 // all remained GPR regs. In that case we can't split parameter, we must 2206 // send it to stack. We also must set NCRN to R4, so waste all 2207 // remained registers. 2208 const unsigned NSAAOffset = State->getNextStackOffset(); 2209 if (NSAAOffset != 0 && Size > Excess) { 2210 while (State->AllocateReg(GPRArgRegs)) 2211 ; 2212 return; 2213 } 2214 2215 // First register for byval parameter is the first register that wasn't 2216 // allocated before this method call, so it would be "reg". 2217 // If parameter is small enough to be saved in range [reg, r4), then 2218 // the end (first after last) register would be reg + param-size-in-regs, 2219 // else parameter would be splitted between registers and stack, 2220 // end register would be r4 in this case. 2221 unsigned ByValRegBegin = Reg; 2222 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4); 2223 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 2224 // Note, first register is allocated in the beginning of function already, 2225 // allocate remained amount of registers we need. 2226 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i) 2227 State->AllocateReg(GPRArgRegs); 2228 // A byval parameter that is split between registers and memory needs its 2229 // size truncated here. 2230 // In the case where the entire structure fits in registers, we set the 2231 // size in memory to zero. 2232 Size = std::max<int>(Size - Excess, 0); 2233 } 2234 2235 /// MatchingStackOffset - Return true if the given stack call argument is 2236 /// already available in the same position (relatively) of the caller's 2237 /// incoming argument stack. 2238 static 2239 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2240 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, 2241 const TargetInstrInfo *TII) { 2242 unsigned Bytes = Arg.getValueSizeInBits() / 8; 2243 int FI = std::numeric_limits<int>::max(); 2244 if (Arg.getOpcode() == ISD::CopyFromReg) { 2245 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2246 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2247 return false; 2248 MachineInstr *Def = MRI->getVRegDef(VR); 2249 if (!Def) 2250 return false; 2251 if (!Flags.isByVal()) { 2252 if (!TII->isLoadFromStackSlot(*Def, FI)) 2253 return false; 2254 } else { 2255 return false; 2256 } 2257 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2258 if (Flags.isByVal()) 2259 // ByVal argument is passed in as a pointer but it's now being 2260 // dereferenced. e.g. 2261 // define @foo(%struct.X* %A) { 2262 // tail call @bar(%struct.X* byval %A) 2263 // } 2264 return false; 2265 SDValue Ptr = Ld->getBasePtr(); 2266 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2267 if (!FINode) 2268 return false; 2269 FI = FINode->getIndex(); 2270 } else 2271 return false; 2272 2273 assert(FI != std::numeric_limits<int>::max()); 2274 if (!MFI.isFixedObjectIndex(FI)) 2275 return false; 2276 return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI); 2277 } 2278 2279 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2280 /// for tail call optimization. Targets which want to do tail call 2281 /// optimization should implement this function. 2282 bool 2283 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2284 CallingConv::ID CalleeCC, 2285 bool isVarArg, 2286 bool isCalleeStructRet, 2287 bool isCallerStructRet, 2288 const SmallVectorImpl<ISD::OutputArg> &Outs, 2289 const SmallVectorImpl<SDValue> &OutVals, 2290 const SmallVectorImpl<ISD::InputArg> &Ins, 2291 SelectionDAG& DAG) const { 2292 MachineFunction &MF = DAG.getMachineFunction(); 2293 const Function &CallerF = MF.getFunction(); 2294 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2295 2296 assert(Subtarget->supportsTailCall()); 2297 2298 // Tail calls to function pointers cannot be optimized for Thumb1 if the args 2299 // to the call take up r0-r3. The reason is that there are no legal registers 2300 // left to hold the pointer to the function to be called. 2301 if (Subtarget->isThumb1Only() && Outs.size() >= 4 && 2302 !isa<GlobalAddressSDNode>(Callee.getNode())) 2303 return false; 2304 2305 // Look for obvious safe cases to perform tail call optimization that do not 2306 // require ABI changes. This is what gcc calls sibcall. 2307 2308 // Exception-handling functions need a special set of instructions to indicate 2309 // a return to the hardware. Tail-calling another function would probably 2310 // break this. 2311 if (CallerF.hasFnAttribute("interrupt")) 2312 return false; 2313 2314 // Also avoid sibcall optimization if either caller or callee uses struct 2315 // return semantics. 2316 if (isCalleeStructRet || isCallerStructRet) 2317 return false; 2318 2319 // Externally-defined functions with weak linkage should not be 2320 // tail-called on ARM when the OS does not support dynamic 2321 // pre-emption of symbols, as the AAELF spec requires normal calls 2322 // to undefined weak functions to be replaced with a NOP or jump to the 2323 // next instruction. The behaviour of branch instructions in this 2324 // situation (as used for tail calls) is implementation-defined, so we 2325 // cannot rely on the linker replacing the tail call with a return. 2326 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2327 const GlobalValue *GV = G->getGlobal(); 2328 const Triple &TT = getTargetMachine().getTargetTriple(); 2329 if (GV->hasExternalWeakLinkage() && 2330 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2331 return false; 2332 } 2333 2334 // Check that the call results are passed in the same way. 2335 LLVMContext &C = *DAG.getContext(); 2336 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2337 CCAssignFnForReturn(CalleeCC, isVarArg), 2338 CCAssignFnForReturn(CallerCC, isVarArg))) 2339 return false; 2340 // The callee has to preserve all registers the caller needs to preserve. 2341 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2342 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2343 if (CalleeCC != CallerCC) { 2344 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2345 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2346 return false; 2347 } 2348 2349 // If Caller's vararg or byval argument has been split between registers and 2350 // stack, do not perform tail call, since part of the argument is in caller's 2351 // local frame. 2352 const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>(); 2353 if (AFI_Caller->getArgRegsSaveSize()) 2354 return false; 2355 2356 // If the callee takes no arguments then go on to check the results of the 2357 // call. 2358 if (!Outs.empty()) { 2359 // Check if stack adjustment is needed. For now, do not do this if any 2360 // argument is passed on the stack. 2361 SmallVector<CCValAssign, 16> ArgLocs; 2362 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2363 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2364 if (CCInfo.getNextStackOffset()) { 2365 // Check if the arguments are already laid out in the right way as 2366 // the caller's fixed stack objects. 2367 MachineFrameInfo &MFI = MF.getFrameInfo(); 2368 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2369 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2370 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 2371 i != e; 2372 ++i, ++realArgIdx) { 2373 CCValAssign &VA = ArgLocs[i]; 2374 EVT RegVT = VA.getLocVT(); 2375 SDValue Arg = OutVals[realArgIdx]; 2376 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2377 if (VA.getLocInfo() == CCValAssign::Indirect) 2378 return false; 2379 if (VA.needsCustom()) { 2380 // f64 and vector types are split into multiple registers or 2381 // register/stack-slot combinations. The types will not match 2382 // the registers; give up on memory f64 refs until we figure 2383 // out what to do about this. 2384 if (!VA.isRegLoc()) 2385 return false; 2386 if (!ArgLocs[++i].isRegLoc()) 2387 return false; 2388 if (RegVT == MVT::v2f64) { 2389 if (!ArgLocs[++i].isRegLoc()) 2390 return false; 2391 if (!ArgLocs[++i].isRegLoc()) 2392 return false; 2393 } 2394 } else if (!VA.isRegLoc()) { 2395 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2396 MFI, MRI, TII)) 2397 return false; 2398 } 2399 } 2400 } 2401 2402 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2403 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2404 return false; 2405 } 2406 2407 return true; 2408 } 2409 2410 bool 2411 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2412 MachineFunction &MF, bool isVarArg, 2413 const SmallVectorImpl<ISD::OutputArg> &Outs, 2414 LLVMContext &Context) const { 2415 SmallVector<CCValAssign, 16> RVLocs; 2416 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 2417 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2418 } 2419 2420 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2421 const SDLoc &DL, SelectionDAG &DAG) { 2422 const MachineFunction &MF = DAG.getMachineFunction(); 2423 const Function &F = MF.getFunction(); 2424 2425 StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString(); 2426 2427 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2428 // version of the "preferred return address". These offsets affect the return 2429 // instruction if this is a return from PL1 without hypervisor extensions. 2430 // IRQ/FIQ: +4 "subs pc, lr, #4" 2431 // SWI: 0 "subs pc, lr, #0" 2432 // ABORT: +4 "subs pc, lr, #4" 2433 // UNDEF: +4/+2 "subs pc, lr, #0" 2434 // UNDEF varies depending on where the exception came from ARM or Thumb 2435 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2436 2437 int64_t LROffset; 2438 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2439 IntKind == "ABORT") 2440 LROffset = 4; 2441 else if (IntKind == "SWI" || IntKind == "UNDEF") 2442 LROffset = 0; 2443 else 2444 report_fatal_error("Unsupported interrupt attribute. If present, value " 2445 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2446 2447 RetOps.insert(RetOps.begin() + 1, 2448 DAG.getConstant(LROffset, DL, MVT::i32, false)); 2449 2450 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps); 2451 } 2452 2453 SDValue 2454 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2455 bool isVarArg, 2456 const SmallVectorImpl<ISD::OutputArg> &Outs, 2457 const SmallVectorImpl<SDValue> &OutVals, 2458 const SDLoc &dl, SelectionDAG &DAG) const { 2459 // CCValAssign - represent the assignment of the return value to a location. 2460 SmallVector<CCValAssign, 16> RVLocs; 2461 2462 // CCState - Info about the registers and stack slots. 2463 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2464 *DAG.getContext()); 2465 2466 // Analyze outgoing return values. 2467 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2468 2469 SDValue Flag; 2470 SmallVector<SDValue, 4> RetOps; 2471 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2472 bool isLittleEndian = Subtarget->isLittle(); 2473 2474 MachineFunction &MF = DAG.getMachineFunction(); 2475 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2476 AFI->setReturnRegsCount(RVLocs.size()); 2477 2478 // Copy the result values into the output registers. 2479 for (unsigned i = 0, realRVLocIdx = 0; 2480 i != RVLocs.size(); 2481 ++i, ++realRVLocIdx) { 2482 CCValAssign &VA = RVLocs[i]; 2483 assert(VA.isRegLoc() && "Can only return in registers!"); 2484 2485 SDValue Arg = OutVals[realRVLocIdx]; 2486 bool ReturnF16 = false; 2487 2488 if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) { 2489 // Half-precision return values can be returned like this: 2490 // 2491 // t11 f16 = fadd ... 2492 // t12: i16 = bitcast t11 2493 // t13: i32 = zero_extend t12 2494 // t14: f32 = bitcast t13 2495 // 2496 // to avoid code generation for bitcasts, we simply set Arg to the node 2497 // that produces the f16 value, t11 in this case. 2498 // 2499 if (Arg.getValueType() == MVT::f32) { 2500 SDValue ZE = Arg.getOperand(0); 2501 if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) { 2502 SDValue BC = ZE.getOperand(0); 2503 if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) { 2504 Arg = BC.getOperand(0); 2505 ReturnF16 = true; 2506 } 2507 } 2508 } 2509 } 2510 2511 switch (VA.getLocInfo()) { 2512 default: llvm_unreachable("Unknown loc info!"); 2513 case CCValAssign::Full: break; 2514 case CCValAssign::BCvt: 2515 if (!ReturnF16) 2516 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2517 break; 2518 } 2519 2520 if (VA.needsCustom()) { 2521 if (VA.getLocVT() == MVT::v2f64) { 2522 // Extract the first half and return it in two registers. 2523 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2524 DAG.getConstant(0, dl, MVT::i32)); 2525 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2526 DAG.getVTList(MVT::i32, MVT::i32), Half); 2527 2528 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2529 HalfGPRs.getValue(isLittleEndian ? 0 : 1), 2530 Flag); 2531 Flag = Chain.getValue(1); 2532 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2533 VA = RVLocs[++i]; // skip ahead to next loc 2534 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2535 HalfGPRs.getValue(isLittleEndian ? 1 : 0), 2536 Flag); 2537 Flag = Chain.getValue(1); 2538 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2539 VA = RVLocs[++i]; // skip ahead to next loc 2540 2541 // Extract the 2nd half and fall through to handle it as an f64 value. 2542 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2543 DAG.getConstant(1, dl, MVT::i32)); 2544 } 2545 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2546 // available. 2547 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2548 DAG.getVTList(MVT::i32, MVT::i32), Arg); 2549 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2550 fmrrd.getValue(isLittleEndian ? 0 : 1), 2551 Flag); 2552 Flag = Chain.getValue(1); 2553 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2554 VA = RVLocs[++i]; // skip ahead to next loc 2555 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2556 fmrrd.getValue(isLittleEndian ? 1 : 0), 2557 Flag); 2558 } else 2559 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2560 2561 // Guarantee that all emitted copies are 2562 // stuck together, avoiding something bad. 2563 Flag = Chain.getValue(1); 2564 RetOps.push_back(DAG.getRegister(VA.getLocReg(), 2565 ReturnF16 ? MVT::f16 : VA.getLocVT())); 2566 } 2567 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2568 const MCPhysReg *I = 2569 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2570 if (I) { 2571 for (; *I; ++I) { 2572 if (ARM::GPRRegClass.contains(*I)) 2573 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2574 else if (ARM::DPRRegClass.contains(*I)) 2575 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 2576 else 2577 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2578 } 2579 } 2580 2581 // Update chain and glue. 2582 RetOps[0] = Chain; 2583 if (Flag.getNode()) 2584 RetOps.push_back(Flag); 2585 2586 // CPUs which aren't M-class use a special sequence to return from 2587 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2588 // though we use "subs pc, lr, #N"). 2589 // 2590 // M-class CPUs actually use a normal return sequence with a special 2591 // (hardware-provided) value in LR, so the normal code path works. 2592 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") && 2593 !Subtarget->isMClass()) { 2594 if (Subtarget->isThumb1Only()) 2595 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2596 return LowerInterruptReturn(RetOps, dl, DAG); 2597 } 2598 2599 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps); 2600 } 2601 2602 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2603 if (N->getNumValues() != 1) 2604 return false; 2605 if (!N->hasNUsesOfValue(1, 0)) 2606 return false; 2607 2608 SDValue TCChain = Chain; 2609 SDNode *Copy = *N->use_begin(); 2610 if (Copy->getOpcode() == ISD::CopyToReg) { 2611 // If the copy has a glue operand, we conservatively assume it isn't safe to 2612 // perform a tail call. 2613 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2614 return false; 2615 TCChain = Copy->getOperand(0); 2616 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2617 SDNode *VMov = Copy; 2618 // f64 returned in a pair of GPRs. 2619 SmallPtrSet<SDNode*, 2> Copies; 2620 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2621 UI != UE; ++UI) { 2622 if (UI->getOpcode() != ISD::CopyToReg) 2623 return false; 2624 Copies.insert(*UI); 2625 } 2626 if (Copies.size() > 2) 2627 return false; 2628 2629 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2630 UI != UE; ++UI) { 2631 SDValue UseChain = UI->getOperand(0); 2632 if (Copies.count(UseChain.getNode())) 2633 // Second CopyToReg 2634 Copy = *UI; 2635 else { 2636 // We are at the top of this chain. 2637 // If the copy has a glue operand, we conservatively assume it 2638 // isn't safe to perform a tail call. 2639 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue) 2640 return false; 2641 // First CopyToReg 2642 TCChain = UseChain; 2643 } 2644 } 2645 } else if (Copy->getOpcode() == ISD::BITCAST) { 2646 // f32 returned in a single GPR. 2647 if (!Copy->hasOneUse()) 2648 return false; 2649 Copy = *Copy->use_begin(); 2650 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2651 return false; 2652 // If the copy has a glue operand, we conservatively assume it isn't safe to 2653 // perform a tail call. 2654 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2655 return false; 2656 TCChain = Copy->getOperand(0); 2657 } else { 2658 return false; 2659 } 2660 2661 bool HasRet = false; 2662 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2663 UI != UE; ++UI) { 2664 if (UI->getOpcode() != ARMISD::RET_FLAG && 2665 UI->getOpcode() != ARMISD::INTRET_FLAG) 2666 return false; 2667 HasRet = true; 2668 } 2669 2670 if (!HasRet) 2671 return false; 2672 2673 Chain = TCChain; 2674 return true; 2675 } 2676 2677 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2678 if (!Subtarget->supportsTailCall()) 2679 return false; 2680 2681 auto Attr = 2682 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls"); 2683 if (!CI->isTailCall() || Attr.getValueAsString() == "true") 2684 return false; 2685 2686 return true; 2687 } 2688 2689 // Trying to write a 64 bit value so need to split into two 32 bit values first, 2690 // and pass the lower and high parts through. 2691 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) { 2692 SDLoc DL(Op); 2693 SDValue WriteValue = Op->getOperand(2); 2694 2695 // This function is only supposed to be called for i64 type argument. 2696 assert(WriteValue.getValueType() == MVT::i64 2697 && "LowerWRITE_REGISTER called for non-i64 type argument."); 2698 2699 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2700 DAG.getConstant(0, DL, MVT::i32)); 2701 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue, 2702 DAG.getConstant(1, DL, MVT::i32)); 2703 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi }; 2704 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops); 2705 } 2706 2707 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2708 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2709 // one of the above mentioned nodes. It has to be wrapped because otherwise 2710 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2711 // be used to form addressing mode. These wrapped nodes will be selected 2712 // into MOVi. 2713 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op, 2714 SelectionDAG &DAG) const { 2715 EVT PtrVT = Op.getValueType(); 2716 // FIXME there is no actual debug info here 2717 SDLoc dl(Op); 2718 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2719 SDValue Res; 2720 2721 // When generating execute-only code Constant Pools must be promoted to the 2722 // global data section. It's a bit ugly that we can't share them across basic 2723 // blocks, but this way we guarantee that execute-only behaves correct with 2724 // position-independent addressing modes. 2725 if (Subtarget->genExecuteOnly()) { 2726 auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 2727 auto T = const_cast<Type*>(CP->getType()); 2728 auto C = const_cast<Constant*>(CP->getConstVal()); 2729 auto M = const_cast<Module*>(DAG.getMachineFunction(). 2730 getFunction().getParent()); 2731 auto GV = new GlobalVariable( 2732 *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C, 2733 Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" + 2734 Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" + 2735 Twine(AFI->createPICLabelUId()) 2736 ); 2737 SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV), 2738 dl, PtrVT); 2739 return LowerGlobalAddress(GA, DAG); 2740 } 2741 2742 if (CP->isMachineConstantPoolEntry()) 2743 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2744 CP->getAlignment()); 2745 else 2746 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2747 CP->getAlignment()); 2748 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2749 } 2750 2751 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2752 return MachineJumpTableInfo::EK_Inline; 2753 } 2754 2755 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2756 SelectionDAG &DAG) const { 2757 MachineFunction &MF = DAG.getMachineFunction(); 2758 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2759 unsigned ARMPCLabelIndex = 0; 2760 SDLoc DL(Op); 2761 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2762 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2763 SDValue CPAddr; 2764 bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI(); 2765 if (!IsPositionIndependent) { 2766 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2767 } else { 2768 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2769 ARMPCLabelIndex = AFI->createPICLabelUId(); 2770 ARMConstantPoolValue *CPV = 2771 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2772 ARMCP::CPBlockAddress, PCAdj); 2773 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2774 } 2775 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2776 SDValue Result = DAG.getLoad( 2777 PtrVT, DL, DAG.getEntryNode(), CPAddr, 2778 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2779 if (!IsPositionIndependent) 2780 return Result; 2781 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32); 2782 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2783 } 2784 2785 /// \brief Convert a TLS address reference into the correct sequence of loads 2786 /// and calls to compute the variable's address for Darwin, and return an 2787 /// SDValue containing the final node. 2788 2789 /// Darwin only has one TLS scheme which must be capable of dealing with the 2790 /// fully general situation, in the worst case. This means: 2791 /// + "extern __thread" declaration. 2792 /// + Defined in a possibly unknown dynamic library. 2793 /// 2794 /// The general system is that each __thread variable has a [3 x i32] descriptor 2795 /// which contains information used by the runtime to calculate the address. The 2796 /// only part of this the compiler needs to know about is the first word, which 2797 /// contains a function pointer that must be called with the address of the 2798 /// entire descriptor in "r0". 2799 /// 2800 /// Since this descriptor may be in a different unit, in general access must 2801 /// proceed along the usual ARM rules. A common sequence to produce is: 2802 /// 2803 /// movw rT1, :lower16:_var$non_lazy_ptr 2804 /// movt rT1, :upper16:_var$non_lazy_ptr 2805 /// ldr r0, [rT1] 2806 /// ldr rT2, [r0] 2807 /// blx rT2 2808 /// [...address now in r0...] 2809 SDValue 2810 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op, 2811 SelectionDAG &DAG) const { 2812 assert(Subtarget->isTargetDarwin() && 2813 "This function expects a Darwin target"); 2814 SDLoc DL(Op); 2815 2816 // First step is to get the address of the actua global symbol. This is where 2817 // the TLS descriptor lives. 2818 SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG); 2819 2820 // The first entry in the descriptor is a function pointer that we must call 2821 // to obtain the address of the variable. 2822 SDValue Chain = DAG.getEntryNode(); 2823 SDValue FuncTLVGet = DAG.getLoad( 2824 MVT::i32, DL, Chain, DescAddr, 2825 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 2826 /* Alignment = */ 4, 2827 MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable | 2828 MachineMemOperand::MOInvariant); 2829 Chain = FuncTLVGet.getValue(1); 2830 2831 MachineFunction &F = DAG.getMachineFunction(); 2832 MachineFrameInfo &MFI = F.getFrameInfo(); 2833 MFI.setAdjustsStack(true); 2834 2835 // TLS calls preserve all registers except those that absolutely must be 2836 // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be 2837 // silly). 2838 auto TRI = 2839 getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo(); 2840 auto ARI = static_cast<const ARMRegisterInfo *>(TRI); 2841 const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction()); 2842 2843 // Finally, we can make the call. This is just a degenerate version of a 2844 // normal AArch64 call node: r0 takes the address of the descriptor, and 2845 // returns the address of the variable in this thread. 2846 Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue()); 2847 Chain = 2848 DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 2849 Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32), 2850 DAG.getRegisterMask(Mask), Chain.getValue(1)); 2851 return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1)); 2852 } 2853 2854 SDValue 2855 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op, 2856 SelectionDAG &DAG) const { 2857 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 2858 2859 SDValue Chain = DAG.getEntryNode(); 2860 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2861 SDLoc DL(Op); 2862 2863 // Load the current TEB (thread environment block) 2864 SDValue Ops[] = {Chain, 2865 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 2866 DAG.getConstant(15, DL, MVT::i32), 2867 DAG.getConstant(0, DL, MVT::i32), 2868 DAG.getConstant(13, DL, MVT::i32), 2869 DAG.getConstant(0, DL, MVT::i32), 2870 DAG.getConstant(2, DL, MVT::i32)}; 2871 SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 2872 DAG.getVTList(MVT::i32, MVT::Other), Ops); 2873 2874 SDValue TEB = CurrentTEB.getValue(0); 2875 Chain = CurrentTEB.getValue(1); 2876 2877 // Load the ThreadLocalStoragePointer from the TEB 2878 // A pointer to the TLS array is located at offset 0x2c from the TEB. 2879 SDValue TLSArray = 2880 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL)); 2881 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 2882 2883 // The pointer to the thread's TLS data area is at the TLS Index scaled by 4 2884 // offset into the TLSArray. 2885 2886 // Load the TLS index from the C runtime 2887 SDValue TLSIndex = 2888 DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG); 2889 TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex); 2890 TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo()); 2891 2892 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 2893 DAG.getConstant(2, DL, MVT::i32)); 2894 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 2895 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 2896 MachinePointerInfo()); 2897 2898 // Get the offset of the start of the .tls section (section base) 2899 const auto *GA = cast<GlobalAddressSDNode>(Op); 2900 auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL); 2901 SDValue Offset = DAG.getLoad( 2902 PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32, 2903 DAG.getTargetConstantPool(CPV, PtrVT, 4)), 2904 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2905 2906 return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset); 2907 } 2908 2909 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2910 SDValue 2911 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2912 SelectionDAG &DAG) const { 2913 SDLoc dl(GA); 2914 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2915 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2916 MachineFunction &MF = DAG.getMachineFunction(); 2917 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2918 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2919 ARMConstantPoolValue *CPV = 2920 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2921 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2922 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2923 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2924 Argument = DAG.getLoad( 2925 PtrVT, dl, DAG.getEntryNode(), Argument, 2926 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2927 SDValue Chain = Argument.getValue(1); 2928 2929 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2930 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2931 2932 // call __tls_get_addr. 2933 ArgListTy Args; 2934 ArgListEntry Entry; 2935 Entry.Node = Argument; 2936 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2937 Args.push_back(Entry); 2938 2939 // FIXME: is there useful debug info available here? 2940 TargetLowering::CallLoweringInfo CLI(DAG); 2941 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2942 CallingConv::C, Type::getInt32Ty(*DAG.getContext()), 2943 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args)); 2944 2945 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2946 return CallResult.first; 2947 } 2948 2949 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2950 // "local exec" model. 2951 SDValue 2952 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2953 SelectionDAG &DAG, 2954 TLSModel::Model model) const { 2955 const GlobalValue *GV = GA->getGlobal(); 2956 SDLoc dl(GA); 2957 SDValue Offset; 2958 SDValue Chain = DAG.getEntryNode(); 2959 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2960 // Get the Thread Pointer 2961 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2962 2963 if (model == TLSModel::InitialExec) { 2964 MachineFunction &MF = DAG.getMachineFunction(); 2965 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2966 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2967 // Initial exec model. 2968 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2969 ARMConstantPoolValue *CPV = 2970 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2971 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2972 true); 2973 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2974 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2975 Offset = DAG.getLoad( 2976 PtrVT, dl, Chain, Offset, 2977 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2978 Chain = Offset.getValue(1); 2979 2980 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 2981 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2982 2983 Offset = DAG.getLoad( 2984 PtrVT, dl, Chain, Offset, 2985 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2986 } else { 2987 // local exec model 2988 assert(model == TLSModel::LocalExec); 2989 ARMConstantPoolValue *CPV = 2990 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2991 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2992 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2993 Offset = DAG.getLoad( 2994 PtrVT, dl, Chain, Offset, 2995 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 2996 } 2997 2998 // The address of the thread local variable is the add of the thread 2999 // pointer with the offset of the variable. 3000 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 3001 } 3002 3003 SDValue 3004 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 3005 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3006 if (DAG.getTarget().Options.EmulatedTLS) 3007 return LowerToTLSEmulatedModel(GA, DAG); 3008 3009 if (Subtarget->isTargetDarwin()) 3010 return LowerGlobalTLSAddressDarwin(Op, DAG); 3011 3012 if (Subtarget->isTargetWindows()) 3013 return LowerGlobalTLSAddressWindows(Op, DAG); 3014 3015 // TODO: implement the "local dynamic" model 3016 assert(Subtarget->isTargetELF() && "Only ELF implemented here"); 3017 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 3018 3019 switch (model) { 3020 case TLSModel::GeneralDynamic: 3021 case TLSModel::LocalDynamic: 3022 return LowerToTLSGeneralDynamicModel(GA, DAG); 3023 case TLSModel::InitialExec: 3024 case TLSModel::LocalExec: 3025 return LowerToTLSExecModels(GA, DAG, model); 3026 } 3027 llvm_unreachable("bogus TLS model"); 3028 } 3029 3030 /// Return true if all users of V are within function F, looking through 3031 /// ConstantExprs. 3032 static bool allUsersAreInFunction(const Value *V, const Function *F) { 3033 SmallVector<const User*,4> Worklist; 3034 for (auto *U : V->users()) 3035 Worklist.push_back(U); 3036 while (!Worklist.empty()) { 3037 auto *U = Worklist.pop_back_val(); 3038 if (isa<ConstantExpr>(U)) { 3039 for (auto *UU : U->users()) 3040 Worklist.push_back(UU); 3041 continue; 3042 } 3043 3044 auto *I = dyn_cast<Instruction>(U); 3045 if (!I || I->getParent()->getParent() != F) 3046 return false; 3047 } 3048 return true; 3049 } 3050 3051 /// Return true if all users of V are within some (any) function, looking through 3052 /// ConstantExprs. In other words, are there any global constant users? 3053 static bool allUsersAreInFunctions(const Value *V) { 3054 SmallVector<const User*,4> Worklist; 3055 for (auto *U : V->users()) 3056 Worklist.push_back(U); 3057 while (!Worklist.empty()) { 3058 auto *U = Worklist.pop_back_val(); 3059 if (isa<ConstantExpr>(U)) { 3060 for (auto *UU : U->users()) 3061 Worklist.push_back(UU); 3062 continue; 3063 } 3064 3065 if (!isa<Instruction>(U)) 3066 return false; 3067 } 3068 return true; 3069 } 3070 3071 // Return true if T is an integer, float or an array/vector of either. 3072 static bool isSimpleType(Type *T) { 3073 if (T->isIntegerTy() || T->isFloatingPointTy()) 3074 return true; 3075 Type *SubT = nullptr; 3076 if (T->isArrayTy()) 3077 SubT = T->getArrayElementType(); 3078 else if (T->isVectorTy()) 3079 SubT = T->getVectorElementType(); 3080 else 3081 return false; 3082 return SubT->isIntegerTy() || SubT->isFloatingPointTy(); 3083 } 3084 3085 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG, 3086 EVT PtrVT, const SDLoc &dl) { 3087 // If we're creating a pool entry for a constant global with unnamed address, 3088 // and the global is small enough, we can emit it inline into the constant pool 3089 // to save ourselves an indirection. 3090 // 3091 // This is a win if the constant is only used in one function (so it doesn't 3092 // need to be duplicated) or duplicating the constant wouldn't increase code 3093 // size (implying the constant is no larger than 4 bytes). 3094 const Function &F = DAG.getMachineFunction().getFunction(); 3095 3096 // We rely on this decision to inline being idemopotent and unrelated to the 3097 // use-site. We know that if we inline a variable at one use site, we'll 3098 // inline it elsewhere too (and reuse the constant pool entry). Fast-isel 3099 // doesn't know about this optimization, so bail out if it's enabled else 3100 // we could decide to inline here (and thus never emit the GV) but require 3101 // the GV from fast-isel generated code. 3102 if (!EnableConstpoolPromotion || 3103 DAG.getMachineFunction().getTarget().Options.EnableFastISel) 3104 return SDValue(); 3105 3106 auto *GVar = dyn_cast<GlobalVariable>(GV); 3107 if (!GVar || !GVar->hasInitializer() || 3108 !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() || 3109 !GVar->hasLocalLinkage()) 3110 return SDValue(); 3111 3112 // Ensure that we don't try and inline any type that contains pointers. If 3113 // we inline a value that contains relocations, we move the relocations from 3114 // .data to .text which is not ideal. 3115 auto *Init = GVar->getInitializer(); 3116 if (!isSimpleType(Init->getType())) 3117 return SDValue(); 3118 3119 // The constant islands pass can only really deal with alignment requests 3120 // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote 3121 // any type wanting greater alignment requirements than 4 bytes. We also 3122 // can only promote constants that are multiples of 4 bytes in size or 3123 // are paddable to a multiple of 4. Currently we only try and pad constants 3124 // that are strings for simplicity. 3125 auto *CDAInit = dyn_cast<ConstantDataArray>(Init); 3126 unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType()); 3127 unsigned Align = GVar->getAlignment(); 3128 unsigned RequiredPadding = 4 - (Size % 4); 3129 bool PaddingPossible = 3130 RequiredPadding == 4 || (CDAInit && CDAInit->isString()); 3131 if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize || 3132 Size == 0) 3133 return SDValue(); 3134 3135 unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding); 3136 MachineFunction &MF = DAG.getMachineFunction(); 3137 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3138 3139 // We can't bloat the constant pool too much, else the ConstantIslands pass 3140 // may fail to converge. If we haven't promoted this global yet (it may have 3141 // multiple uses), and promoting it would increase the constant pool size (Sz 3142 // > 4), ensure we have space to do so up to MaxTotal. 3143 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4) 3144 if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >= 3145 ConstpoolPromotionMaxTotal) 3146 return SDValue(); 3147 3148 // This is only valid if all users are in a single function OR it has users 3149 // in multiple functions but it no larger than a pointer. We also check if 3150 // GVar has constant (non-ConstantExpr) users. If so, it essentially has its 3151 // address taken. 3152 if (!allUsersAreInFunction(GVar, &F) && 3153 !(Size <= 4 && allUsersAreInFunctions(GVar))) 3154 return SDValue(); 3155 3156 // We're going to inline this global. Pad it out if needed. 3157 if (RequiredPadding != 4) { 3158 StringRef S = CDAInit->getAsString(); 3159 3160 SmallVector<uint8_t,16> V(S.size()); 3161 std::copy(S.bytes_begin(), S.bytes_end(), V.begin()); 3162 while (RequiredPadding--) 3163 V.push_back(0); 3164 Init = ConstantDataArray::get(*DAG.getContext(), V); 3165 } 3166 3167 auto CPVal = ARMConstantPoolConstant::Create(GVar, Init); 3168 SDValue CPAddr = 3169 DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4); 3170 if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) { 3171 AFI->markGlobalAsPromotedToConstantPool(GVar); 3172 AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() + 3173 PaddedSize - 4); 3174 } 3175 ++NumConstpoolPromoted; 3176 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3177 } 3178 3179 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const { 3180 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 3181 GV = GA->getBaseObject(); 3182 return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) || 3183 isa<Function>(GV); 3184 } 3185 3186 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op, 3187 SelectionDAG &DAG) const { 3188 switch (Subtarget->getTargetTriple().getObjectFormat()) { 3189 default: llvm_unreachable("unknown object format"); 3190 case Triple::COFF: 3191 return LowerGlobalAddressWindows(Op, DAG); 3192 case Triple::ELF: 3193 return LowerGlobalAddressELF(Op, DAG); 3194 case Triple::MachO: 3195 return LowerGlobalAddressDarwin(Op, DAG); 3196 } 3197 } 3198 3199 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 3200 SelectionDAG &DAG) const { 3201 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3202 SDLoc dl(Op); 3203 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3204 const TargetMachine &TM = getTargetMachine(); 3205 bool IsRO = isReadOnly(GV); 3206 3207 // promoteToConstantPool only if not generating XO text section 3208 if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly()) 3209 if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl)) 3210 return V; 3211 3212 if (isPositionIndependent()) { 3213 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV); 3214 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3215 UseGOT_PREL ? ARMII::MO_GOT : 0); 3216 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3217 if (UseGOT_PREL) 3218 Result = 3219 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3220 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3221 return Result; 3222 } else if (Subtarget->isROPI() && IsRO) { 3223 // PC-relative. 3224 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT); 3225 SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G); 3226 return Result; 3227 } else if (Subtarget->isRWPI() && !IsRO) { 3228 // SB-relative. 3229 SDValue RelAddr; 3230 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3231 ++NumMovwMovt; 3232 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL); 3233 RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G); 3234 } else { // use literal pool for address constant 3235 ARMConstantPoolValue *CPV = 3236 ARMConstantPoolConstant::Create(GV, ARMCP::SBREL); 3237 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3238 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3239 RelAddr = DAG.getLoad( 3240 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3241 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3242 } 3243 SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT); 3244 SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr); 3245 return Result; 3246 } 3247 3248 // If we have T2 ops, we can materialize the address directly via movt/movw 3249 // pair. This is always cheaper. 3250 if (Subtarget->useMovt(DAG.getMachineFunction())) { 3251 ++NumMovwMovt; 3252 // FIXME: Once remat is capable of dealing with instructions with register 3253 // operands, expand this into two nodes. 3254 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 3255 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 3256 } else { 3257 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 3258 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3259 return DAG.getLoad( 3260 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3261 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3262 } 3263 } 3264 3265 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 3266 SelectionDAG &DAG) const { 3267 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3268 "ROPI/RWPI not currently supported for Darwin"); 3269 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3270 SDLoc dl(Op); 3271 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3272 3273 if (Subtarget->useMovt(DAG.getMachineFunction())) 3274 ++NumMovwMovt; 3275 3276 // FIXME: Once remat is capable of dealing with instructions with register 3277 // operands, expand this into multiple nodes 3278 unsigned Wrapper = 3279 isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper; 3280 3281 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 3282 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 3283 3284 if (Subtarget->isGVIndirectSymbol(GV)) 3285 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 3286 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3287 return Result; 3288 } 3289 3290 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op, 3291 SelectionDAG &DAG) const { 3292 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported"); 3293 assert(Subtarget->useMovt(DAG.getMachineFunction()) && 3294 "Windows on ARM expects to use movw/movt"); 3295 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 3296 "ROPI/RWPI not currently supported for Windows"); 3297 3298 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3299 const ARMII::TOF TargetFlags = 3300 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG); 3301 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3302 SDValue Result; 3303 SDLoc DL(Op); 3304 3305 ++NumMovwMovt; 3306 3307 // FIXME: Once remat is capable of dealing with instructions with register 3308 // operands, expand this into two nodes. 3309 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, 3310 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0, 3311 TargetFlags)); 3312 if (GV->hasDLLImportStorageClass()) 3313 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 3314 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 3315 return Result; 3316 } 3317 3318 SDValue 3319 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 3320 SDLoc dl(Op); 3321 SDValue Val = DAG.getConstant(0, dl, MVT::i32); 3322 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 3323 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 3324 Op.getOperand(1), Val); 3325 } 3326 3327 SDValue 3328 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 3329 SDLoc dl(Op); 3330 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 3331 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32)); 3332 } 3333 3334 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 3335 SelectionDAG &DAG) const { 3336 SDLoc dl(Op); 3337 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other, 3338 Op.getOperand(0)); 3339 } 3340 3341 SDValue 3342 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 3343 const ARMSubtarget *Subtarget) const { 3344 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3345 SDLoc dl(Op); 3346 switch (IntNo) { 3347 default: return SDValue(); // Don't custom lower most intrinsics. 3348 case Intrinsic::thread_pointer: { 3349 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3350 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 3351 } 3352 case Intrinsic::eh_sjlj_lsda: { 3353 MachineFunction &MF = DAG.getMachineFunction(); 3354 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3355 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 3356 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3357 SDValue CPAddr; 3358 bool IsPositionIndependent = isPositionIndependent(); 3359 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0; 3360 ARMConstantPoolValue *CPV = 3361 ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex, 3362 ARMCP::CPLSDA, PCAdj); 3363 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 3364 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 3365 SDValue Result = DAG.getLoad( 3366 PtrVT, dl, DAG.getEntryNode(), CPAddr, 3367 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 3368 3369 if (IsPositionIndependent) { 3370 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32); 3371 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 3372 } 3373 return Result; 3374 } 3375 case Intrinsic::arm_neon_vabs: 3376 return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(), 3377 Op.getOperand(1)); 3378 case Intrinsic::arm_neon_vmulls: 3379 case Intrinsic::arm_neon_vmullu: { 3380 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 3381 ? ARMISD::VMULLs : ARMISD::VMULLu; 3382 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3383 Op.getOperand(1), Op.getOperand(2)); 3384 } 3385 case Intrinsic::arm_neon_vminnm: 3386 case Intrinsic::arm_neon_vmaxnm: { 3387 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm) 3388 ? ISD::FMINNUM : ISD::FMAXNUM; 3389 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3390 Op.getOperand(1), Op.getOperand(2)); 3391 } 3392 case Intrinsic::arm_neon_vminu: 3393 case Intrinsic::arm_neon_vmaxu: { 3394 if (Op.getValueType().isFloatingPoint()) 3395 return SDValue(); 3396 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu) 3397 ? ISD::UMIN : ISD::UMAX; 3398 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3399 Op.getOperand(1), Op.getOperand(2)); 3400 } 3401 case Intrinsic::arm_neon_vmins: 3402 case Intrinsic::arm_neon_vmaxs: { 3403 // v{min,max}s is overloaded between signed integers and floats. 3404 if (!Op.getValueType().isFloatingPoint()) { 3405 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3406 ? ISD::SMIN : ISD::SMAX; 3407 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3408 Op.getOperand(1), Op.getOperand(2)); 3409 } 3410 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins) 3411 ? ISD::FMINNAN : ISD::FMAXNAN; 3412 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 3413 Op.getOperand(1), Op.getOperand(2)); 3414 } 3415 case Intrinsic::arm_neon_vtbl1: 3416 return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(), 3417 Op.getOperand(1), Op.getOperand(2)); 3418 case Intrinsic::arm_neon_vtbl2: 3419 return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(), 3420 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3421 } 3422 } 3423 3424 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 3425 const ARMSubtarget *Subtarget) { 3426 SDLoc dl(Op); 3427 ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2)); 3428 auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue()); 3429 if (SSID == SyncScope::SingleThread) 3430 return Op; 3431 3432 if (!Subtarget->hasDataBarrier()) { 3433 // Some ARMv6 cpus can support data barriers with an mcr instruction. 3434 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 3435 // here. 3436 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 3437 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 3438 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 3439 DAG.getConstant(0, dl, MVT::i32)); 3440 } 3441 3442 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 3443 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 3444 ARM_MB::MemBOpt Domain = ARM_MB::ISH; 3445 if (Subtarget->isMClass()) { 3446 // Only a full system barrier exists in the M-class architectures. 3447 Domain = ARM_MB::SY; 3448 } else if (Subtarget->preferISHSTBarriers() && 3449 Ord == AtomicOrdering::Release) { 3450 // Swift happens to implement ISHST barriers in a way that's compatible with 3451 // Release semantics but weaker than ISH so we'd be fools not to use 3452 // it. Beware: other processors probably don't! 3453 Domain = ARM_MB::ISHST; 3454 } 3455 3456 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 3457 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32), 3458 DAG.getConstant(Domain, dl, MVT::i32)); 3459 } 3460 3461 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 3462 const ARMSubtarget *Subtarget) { 3463 // ARM pre v5TE and Thumb1 does not have preload instructions. 3464 if (!(Subtarget->isThumb2() || 3465 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 3466 // Just preserve the chain. 3467 return Op.getOperand(0); 3468 3469 SDLoc dl(Op); 3470 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 3471 if (!isRead && 3472 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 3473 // ARMv7 with MP extension has PLDW. 3474 return Op.getOperand(0); 3475 3476 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 3477 if (Subtarget->isThumb()) { 3478 // Invert the bits. 3479 isRead = ~isRead & 1; 3480 isData = ~isData & 1; 3481 } 3482 3483 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 3484 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32), 3485 DAG.getConstant(isData, dl, MVT::i32)); 3486 } 3487 3488 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 3489 MachineFunction &MF = DAG.getMachineFunction(); 3490 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 3491 3492 // vastart just stores the address of the VarArgsFrameIndex slot into the 3493 // memory location argument. 3494 SDLoc dl(Op); 3495 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 3496 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3497 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3498 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3499 MachinePointerInfo(SV)); 3500 } 3501 3502 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, 3503 CCValAssign &NextVA, 3504 SDValue &Root, 3505 SelectionDAG &DAG, 3506 const SDLoc &dl) const { 3507 MachineFunction &MF = DAG.getMachineFunction(); 3508 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3509 3510 const TargetRegisterClass *RC; 3511 if (AFI->isThumb1OnlyFunction()) 3512 RC = &ARM::tGPRRegClass; 3513 else 3514 RC = &ARM::GPRRegClass; 3515 3516 // Transform the arguments stored in physical registers into virtual ones. 3517 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3518 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3519 3520 SDValue ArgValue2; 3521 if (NextVA.isMemLoc()) { 3522 MachineFrameInfo &MFI = MF.getFrameInfo(); 3523 int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true); 3524 3525 // Create load node to retrieve arguments from the stack. 3526 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3527 ArgValue2 = DAG.getLoad( 3528 MVT::i32, dl, Root, FIN, 3529 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 3530 } else { 3531 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 3532 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 3533 } 3534 if (!Subtarget->isLittle()) 3535 std::swap (ArgValue, ArgValue2); 3536 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 3537 } 3538 3539 // The remaining GPRs hold either the beginning of variable-argument 3540 // data, or the beginning of an aggregate passed by value (usually 3541 // byval). Either way, we allocate stack slots adjacent to the data 3542 // provided by our caller, and store the unallocated registers there. 3543 // If this is a variadic function, the va_list pointer will begin with 3544 // these values; otherwise, this reassembles a (byval) structure that 3545 // was split between registers and memory. 3546 // Return: The frame index registers were stored into. 3547 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 3548 const SDLoc &dl, SDValue &Chain, 3549 const Value *OrigArg, 3550 unsigned InRegsParamRecordIdx, 3551 int ArgOffset, unsigned ArgSize) const { 3552 // Currently, two use-cases possible: 3553 // Case #1. Non-var-args function, and we meet first byval parameter. 3554 // Setup first unallocated register as first byval register; 3555 // eat all remained registers 3556 // (these two actions are performed by HandleByVal method). 3557 // Then, here, we initialize stack frame with 3558 // "store-reg" instructions. 3559 // Case #2. Var-args function, that doesn't contain byval parameters. 3560 // The same: eat all remained unallocated registers, 3561 // initialize stack frame. 3562 3563 MachineFunction &MF = DAG.getMachineFunction(); 3564 MachineFrameInfo &MFI = MF.getFrameInfo(); 3565 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3566 unsigned RBegin, REnd; 3567 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 3568 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 3569 } else { 3570 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3571 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx]; 3572 REnd = ARM::R4; 3573 } 3574 3575 if (REnd != RBegin) 3576 ArgOffset = -4 * (ARM::R4 - RBegin); 3577 3578 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3579 int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false); 3580 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT); 3581 3582 SmallVector<SDValue, 4> MemOps; 3583 const TargetRegisterClass *RC = 3584 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 3585 3586 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) { 3587 unsigned VReg = MF.addLiveIn(Reg, RC); 3588 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 3589 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3590 MachinePointerInfo(OrigArg, 4 * i)); 3591 MemOps.push_back(Store); 3592 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT)); 3593 } 3594 3595 if (!MemOps.empty()) 3596 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3597 return FrameIndex; 3598 } 3599 3600 // Setup stack frame, the va_list pointer will start from. 3601 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 3602 const SDLoc &dl, SDValue &Chain, 3603 unsigned ArgOffset, 3604 unsigned TotalArgRegsSaveSize, 3605 bool ForceMutable) const { 3606 MachineFunction &MF = DAG.getMachineFunction(); 3607 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3608 3609 // Try to store any remaining integer argument regs 3610 // to their spots on the stack so that they may be loaded by dereferencing 3611 // the result of va_next. 3612 // If there is no regs to be stored, just point address after last 3613 // argument passed via stack. 3614 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr, 3615 CCInfo.getInRegsParamsCount(), 3616 CCInfo.getNextStackOffset(), 4); 3617 AFI->setVarArgsFrameIndex(FrameIndex); 3618 } 3619 3620 SDValue ARMTargetLowering::LowerFormalArguments( 3621 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3622 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3623 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3624 MachineFunction &MF = DAG.getMachineFunction(); 3625 MachineFrameInfo &MFI = MF.getFrameInfo(); 3626 3627 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3628 3629 // Assign locations to all of the incoming arguments. 3630 SmallVector<CCValAssign, 16> ArgLocs; 3631 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3632 *DAG.getContext()); 3633 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg)); 3634 3635 SmallVector<SDValue, 16> ArgValues; 3636 SDValue ArgValue; 3637 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3638 unsigned CurArgIdx = 0; 3639 3640 // Initially ArgRegsSaveSize is zero. 3641 // Then we increase this value each time we meet byval parameter. 3642 // We also increase this value in case of varargs function. 3643 AFI->setArgRegsSaveSize(0); 3644 3645 // Calculate the amount of stack space that we need to allocate to store 3646 // byval and variadic arguments that are passed in registers. 3647 // We need to know this before we allocate the first byval or variadic 3648 // argument, as they will be allocated a stack slot below the CFA (Canonical 3649 // Frame Address, the stack pointer at entry to the function). 3650 unsigned ArgRegBegin = ARM::R4; 3651 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3652 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount()) 3653 break; 3654 3655 CCValAssign &VA = ArgLocs[i]; 3656 unsigned Index = VA.getValNo(); 3657 ISD::ArgFlagsTy Flags = Ins[Index].Flags; 3658 if (!Flags.isByVal()) 3659 continue; 3660 3661 assert(VA.isMemLoc() && "unexpected byval pointer in reg"); 3662 unsigned RBegin, REnd; 3663 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd); 3664 ArgRegBegin = std::min(ArgRegBegin, RBegin); 3665 3666 CCInfo.nextInRegsParam(); 3667 } 3668 CCInfo.rewindByValRegsInfo(); 3669 3670 int lastInsIndex = -1; 3671 if (isVarArg && MFI.hasVAStart()) { 3672 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs); 3673 if (RegIdx != array_lengthof(GPRArgRegs)) 3674 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]); 3675 } 3676 3677 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin); 3678 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize); 3679 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3680 3681 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3682 CCValAssign &VA = ArgLocs[i]; 3683 if (Ins[VA.getValNo()].isOrigArg()) { 3684 std::advance(CurOrigArg, 3685 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx); 3686 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex(); 3687 } 3688 // Arguments stored in registers. 3689 if (VA.isRegLoc()) { 3690 EVT RegVT = VA.getLocVT(); 3691 3692 if (VA.needsCustom()) { 3693 // f64 and vector types are split up into multiple registers or 3694 // combinations of registers and stack slots. 3695 if (VA.getLocVT() == MVT::v2f64) { 3696 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 3697 Chain, DAG, dl); 3698 VA = ArgLocs[++i]; // skip ahead to next loc 3699 SDValue ArgValue2; 3700 if (VA.isMemLoc()) { 3701 int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true); 3702 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3703 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 3704 MachinePointerInfo::getFixedStack( 3705 DAG.getMachineFunction(), FI)); 3706 } else { 3707 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 3708 Chain, DAG, dl); 3709 } 3710 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 3711 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3712 ArgValue, ArgValue1, 3713 DAG.getIntPtrConstant(0, dl)); 3714 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 3715 ArgValue, ArgValue2, 3716 DAG.getIntPtrConstant(1, dl)); 3717 } else 3718 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 3719 } else { 3720 const TargetRegisterClass *RC; 3721 3722 3723 if (RegVT == MVT::f16) 3724 RC = &ARM::HPRRegClass; 3725 else if (RegVT == MVT::f32) 3726 RC = &ARM::SPRRegClass; 3727 else if (RegVT == MVT::f64) 3728 RC = &ARM::DPRRegClass; 3729 else if (RegVT == MVT::v2f64) 3730 RC = &ARM::QPRRegClass; 3731 else if (RegVT == MVT::i32) 3732 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass 3733 : &ARM::GPRRegClass; 3734 else 3735 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3736 3737 // Transform the arguments in physical registers into virtual ones. 3738 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3739 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 3740 } 3741 3742 // If this is an 8 or 16-bit value, it is really passed promoted 3743 // to 32 bits. Insert an assert[sz]ext to capture this, then 3744 // truncate to the right size. 3745 switch (VA.getLocInfo()) { 3746 default: llvm_unreachable("Unknown loc info!"); 3747 case CCValAssign::Full: break; 3748 case CCValAssign::BCvt: 3749 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 3750 break; 3751 case CCValAssign::SExt: 3752 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 3753 DAG.getValueType(VA.getValVT())); 3754 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3755 break; 3756 case CCValAssign::ZExt: 3757 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 3758 DAG.getValueType(VA.getValVT())); 3759 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 3760 break; 3761 } 3762 3763 InVals.push_back(ArgValue); 3764 } else { // VA.isRegLoc() 3765 // sanity check 3766 assert(VA.isMemLoc()); 3767 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3768 3769 int index = VA.getValNo(); 3770 3771 // Some Ins[] entries become multiple ArgLoc[] entries. 3772 // Process them only once. 3773 if (index != lastInsIndex) 3774 { 3775 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3776 // FIXME: For now, all byval parameter objects are marked mutable. 3777 // This can be changed with more analysis. 3778 // In case of tail call optimization mark all arguments mutable. 3779 // Since they could be overwritten by lowering of arguments in case of 3780 // a tail call. 3781 if (Flags.isByVal()) { 3782 assert(Ins[index].isOrigArg() && 3783 "Byval arguments cannot be implicit"); 3784 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed(); 3785 3786 int FrameIndex = StoreByValRegs( 3787 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex, 3788 VA.getLocMemOffset(), Flags.getByValSize()); 3789 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT)); 3790 CCInfo.nextInRegsParam(); 3791 } else { 3792 unsigned FIOffset = VA.getLocMemOffset(); 3793 int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3794 FIOffset, true); 3795 3796 // Create load nodes to retrieve arguments from the stack. 3797 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3798 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3799 MachinePointerInfo::getFixedStack( 3800 DAG.getMachineFunction(), FI))); 3801 } 3802 lastInsIndex = index; 3803 } 3804 } 3805 } 3806 3807 // varargs 3808 if (isVarArg && MFI.hasVAStart()) 3809 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3810 CCInfo.getNextStackOffset(), 3811 TotalArgRegsSaveSize); 3812 3813 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3814 3815 return Chain; 3816 } 3817 3818 /// isFloatingPointZero - Return true if this is +0.0. 3819 static bool isFloatingPointZero(SDValue Op) { 3820 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3821 return CFP->getValueAPF().isPosZero(); 3822 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3823 // Maybe this has already been legalized into the constant pool? 3824 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3825 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3826 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3827 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3828 return CFP->getValueAPF().isPosZero(); 3829 } 3830 } else if (Op->getOpcode() == ISD::BITCAST && 3831 Op->getValueType(0) == MVT::f64) { 3832 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64) 3833 // created by LowerConstantFP(). 3834 SDValue BitcastOp = Op->getOperand(0); 3835 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM && 3836 isNullConstant(BitcastOp->getOperand(0))) 3837 return true; 3838 } 3839 return false; 3840 } 3841 3842 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3843 /// the given operands. 3844 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3845 SDValue &ARMcc, SelectionDAG &DAG, 3846 const SDLoc &dl) const { 3847 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3848 unsigned C = RHSC->getZExtValue(); 3849 if (!isLegalICmpImmediate(C)) { 3850 // Constant does not fit, try adjusting it by one? 3851 switch (CC) { 3852 default: break; 3853 case ISD::SETLT: 3854 case ISD::SETGE: 3855 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3856 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3857 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3858 } 3859 break; 3860 case ISD::SETULT: 3861 case ISD::SETUGE: 3862 if (C != 0 && isLegalICmpImmediate(C-1)) { 3863 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3864 RHS = DAG.getConstant(C - 1, dl, MVT::i32); 3865 } 3866 break; 3867 case ISD::SETLE: 3868 case ISD::SETGT: 3869 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3870 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3871 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3872 } 3873 break; 3874 case ISD::SETULE: 3875 case ISD::SETUGT: 3876 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3877 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3878 RHS = DAG.getConstant(C + 1, dl, MVT::i32); 3879 } 3880 break; 3881 } 3882 } 3883 } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) && 3884 (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) { 3885 // In ARM and Thumb-2, the compare instructions can shift their second 3886 // operand. 3887 CC = ISD::getSetCCSwappedOperands(CC); 3888 std::swap(LHS, RHS); 3889 } 3890 3891 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3892 ARMISD::NodeType CompareType; 3893 switch (CondCode) { 3894 default: 3895 CompareType = ARMISD::CMP; 3896 break; 3897 case ARMCC::EQ: 3898 case ARMCC::NE: 3899 // Uses only Z Flag 3900 CompareType = ARMISD::CMPZ; 3901 break; 3902 } 3903 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 3904 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3905 } 3906 3907 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3908 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, 3909 SelectionDAG &DAG, const SDLoc &dl, 3910 bool InvalidOnQNaN) const { 3911 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64); 3912 SDValue Cmp; 3913 SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32); 3914 if (!isFloatingPointZero(RHS)) 3915 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C); 3916 else 3917 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C); 3918 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3919 } 3920 3921 /// duplicateCmp - Glue values can have only one use, so this function 3922 /// duplicates a comparison node. 3923 SDValue 3924 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3925 unsigned Opc = Cmp.getOpcode(); 3926 SDLoc DL(Cmp); 3927 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3928 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3929 3930 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3931 Cmp = Cmp.getOperand(0); 3932 Opc = Cmp.getOpcode(); 3933 if (Opc == ARMISD::CMPFP) 3934 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3935 Cmp.getOperand(1), Cmp.getOperand(2)); 3936 else { 3937 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3938 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0), 3939 Cmp.getOperand(1)); 3940 } 3941 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3942 } 3943 3944 // This function returns three things: the arithmetic computation itself 3945 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The 3946 // comparison and the condition code define the case in which the arithmetic 3947 // computation *does not* overflow. 3948 std::pair<SDValue, SDValue> 3949 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG, 3950 SDValue &ARMcc) const { 3951 assert(Op.getValueType() == MVT::i32 && "Unsupported value type"); 3952 3953 SDValue Value, OverflowCmp; 3954 SDValue LHS = Op.getOperand(0); 3955 SDValue RHS = Op.getOperand(1); 3956 SDLoc dl(Op); 3957 3958 // FIXME: We are currently always generating CMPs because we don't support 3959 // generating CMN through the backend. This is not as good as the natural 3960 // CMP case because it causes a register dependency and cannot be folded 3961 // later. 3962 3963 switch (Op.getOpcode()) { 3964 default: 3965 llvm_unreachable("Unknown overflow instruction!"); 3966 case ISD::SADDO: 3967 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3968 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS); 3969 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3970 break; 3971 case ISD::UADDO: 3972 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3973 // We use ADDC here to correspond to its use in LowerUnsignedALUO. 3974 // We do not use it in the USUBO case as Value may not be used. 3975 Value = DAG.getNode(ARMISD::ADDC, dl, 3976 DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS) 3977 .getValue(0); 3978 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS); 3979 break; 3980 case ISD::SSUBO: 3981 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32); 3982 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3983 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3984 break; 3985 case ISD::USUBO: 3986 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32); 3987 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS); 3988 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS); 3989 break; 3990 case ISD::UMULO: 3991 // We generate a UMUL_LOHI and then check if the high word is 0. 3992 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 3993 Value = DAG.getNode(ISD::UMUL_LOHI, dl, 3994 DAG.getVTList(Op.getValueType(), Op.getValueType()), 3995 LHS, RHS); 3996 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1), 3997 DAG.getConstant(0, dl, MVT::i32)); 3998 Value = Value.getValue(0); // We only want the low 32 bits for the result. 3999 break; 4000 case ISD::SMULO: 4001 // We generate a SMUL_LOHI and then check if all the bits of the high word 4002 // are the same as the sign bit of the low word. 4003 ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32); 4004 Value = DAG.getNode(ISD::SMUL_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.getNode(ISD::SRA, dl, Op.getValueType(), 4009 Value.getValue(0), 4010 DAG.getConstant(31, dl, MVT::i32))); 4011 Value = Value.getValue(0); // We only want the low 32 bits for the result. 4012 break; 4013 } // switch (...) 4014 4015 return std::make_pair(Value, OverflowCmp); 4016 } 4017 4018 SDValue 4019 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const { 4020 // Let legalize expand this if it isn't a legal type yet. 4021 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4022 return SDValue(); 4023 4024 SDValue Value, OverflowCmp; 4025 SDValue ARMcc; 4026 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc); 4027 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4028 SDLoc dl(Op); 4029 // We use 0 and 1 as false and true values. 4030 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 4031 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 4032 EVT VT = Op.getValueType(); 4033 4034 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, 4035 ARMcc, CCR, OverflowCmp); 4036 4037 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 4038 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4039 } 4040 4041 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry, 4042 SelectionDAG &DAG) { 4043 SDLoc DL(BoolCarry); 4044 EVT CarryVT = BoolCarry.getValueType(); 4045 4046 APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits()); 4047 // This converts the boolean value carry into the carry flag by doing 4048 // ARMISD::ADDC Carry, ~0 4049 return DAG.getNode(ARMISD::ADDC, DL, DAG.getVTList(CarryVT, MVT::i32), 4050 BoolCarry, DAG.getConstant(NegOne, DL, CarryVT)); 4051 } 4052 4053 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT, 4054 SelectionDAG &DAG) { 4055 SDLoc DL(Flags); 4056 4057 // Now convert the carry flag into a boolean carry. We do this 4058 // using ARMISD:ADDE 0, 0, Carry 4059 return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32), 4060 DAG.getConstant(0, DL, MVT::i32), 4061 DAG.getConstant(0, DL, MVT::i32), Flags); 4062 } 4063 4064 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op, 4065 SelectionDAG &DAG) const { 4066 // Let legalize expand this if it isn't a legal type yet. 4067 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 4068 return SDValue(); 4069 4070 SDValue LHS = Op.getOperand(0); 4071 SDValue RHS = Op.getOperand(1); 4072 SDLoc dl(Op); 4073 4074 EVT VT = Op.getValueType(); 4075 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 4076 SDValue Value; 4077 SDValue Overflow; 4078 switch (Op.getOpcode()) { 4079 default: 4080 llvm_unreachable("Unknown overflow instruction!"); 4081 case ISD::UADDO: 4082 Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS); 4083 // Convert the carry flag into a boolean value. 4084 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4085 break; 4086 case ISD::USUBO: { 4087 Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS); 4088 // Convert the carry flag into a boolean value. 4089 Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG); 4090 // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow 4091 // value. So compute 1 - C. 4092 Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32, 4093 DAG.getConstant(1, dl, MVT::i32), Overflow); 4094 break; 4095 } 4096 } 4097 4098 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 4099 } 4100 4101 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 4102 SDValue Cond = Op.getOperand(0); 4103 SDValue SelectTrue = Op.getOperand(1); 4104 SDValue SelectFalse = Op.getOperand(2); 4105 SDLoc dl(Op); 4106 unsigned Opc = Cond.getOpcode(); 4107 4108 if (Cond.getResNo() == 1 && 4109 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4110 Opc == ISD::USUBO)) { 4111 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4112 return SDValue(); 4113 4114 SDValue Value, OverflowCmp; 4115 SDValue ARMcc; 4116 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4117 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4118 EVT VT = Op.getValueType(); 4119 4120 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR, 4121 OverflowCmp, DAG); 4122 } 4123 4124 // Convert: 4125 // 4126 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 4127 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 4128 // 4129 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 4130 const ConstantSDNode *CMOVTrue = 4131 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 4132 const ConstantSDNode *CMOVFalse = 4133 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 4134 4135 if (CMOVTrue && CMOVFalse) { 4136 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 4137 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 4138 4139 SDValue True; 4140 SDValue False; 4141 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 4142 True = SelectTrue; 4143 False = SelectFalse; 4144 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 4145 True = SelectFalse; 4146 False = SelectTrue; 4147 } 4148 4149 if (True.getNode() && False.getNode()) { 4150 EVT VT = Op.getValueType(); 4151 SDValue ARMcc = Cond.getOperand(2); 4152 SDValue CCR = Cond.getOperand(3); 4153 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 4154 assert(True.getValueType() == VT); 4155 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG); 4156 } 4157 } 4158 } 4159 4160 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 4161 // undefined bits before doing a full-word comparison with zero. 4162 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 4163 DAG.getConstant(1, dl, Cond.getValueType())); 4164 4165 return DAG.getSelectCC(dl, Cond, 4166 DAG.getConstant(0, dl, Cond.getValueType()), 4167 SelectTrue, SelectFalse, ISD::SETNE); 4168 } 4169 4170 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 4171 bool &swpCmpOps, bool &swpVselOps) { 4172 // Start by selecting the GE condition code for opcodes that return true for 4173 // 'equality' 4174 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 4175 CC == ISD::SETULE) 4176 CondCode = ARMCC::GE; 4177 4178 // and GT for opcodes that return false for 'equality'. 4179 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 4180 CC == ISD::SETULT) 4181 CondCode = ARMCC::GT; 4182 4183 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 4184 // to swap the compare operands. 4185 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 4186 CC == ISD::SETULT) 4187 swpCmpOps = true; 4188 4189 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 4190 // If we have an unordered opcode, we need to swap the operands to the VSEL 4191 // instruction (effectively negating the condition). 4192 // 4193 // This also has the effect of swapping which one of 'less' or 'greater' 4194 // returns true, so we also swap the compare operands. It also switches 4195 // whether we return true for 'equality', so we compensate by picking the 4196 // opposite condition code to our original choice. 4197 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 4198 CC == ISD::SETUGT) { 4199 swpCmpOps = !swpCmpOps; 4200 swpVselOps = !swpVselOps; 4201 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 4202 } 4203 4204 // 'ordered' is 'anything but unordered', so use the VS condition code and 4205 // swap the VSEL operands. 4206 if (CC == ISD::SETO) { 4207 CondCode = ARMCC::VS; 4208 swpVselOps = true; 4209 } 4210 4211 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 4212 // code and swap the VSEL operands. 4213 if (CC == ISD::SETUNE) { 4214 CondCode = ARMCC::EQ; 4215 swpVselOps = true; 4216 } 4217 } 4218 4219 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, 4220 SDValue TrueVal, SDValue ARMcc, SDValue CCR, 4221 SDValue Cmp, SelectionDAG &DAG) const { 4222 if (Subtarget->isFPOnlySP() && VT == MVT::f64) { 4223 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4224 DAG.getVTList(MVT::i32, MVT::i32), FalseVal); 4225 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl, 4226 DAG.getVTList(MVT::i32, MVT::i32), TrueVal); 4227 4228 SDValue TrueLow = TrueVal.getValue(0); 4229 SDValue TrueHigh = TrueVal.getValue(1); 4230 SDValue FalseLow = FalseVal.getValue(0); 4231 SDValue FalseHigh = FalseVal.getValue(1); 4232 4233 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow, 4234 ARMcc, CCR, Cmp); 4235 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh, 4236 ARMcc, CCR, duplicateCmp(Cmp, DAG)); 4237 4238 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High); 4239 } else { 4240 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 4241 Cmp); 4242 } 4243 } 4244 4245 static bool isGTorGE(ISD::CondCode CC) { 4246 return CC == ISD::SETGT || CC == ISD::SETGE; 4247 } 4248 4249 static bool isLTorLE(ISD::CondCode CC) { 4250 return CC == ISD::SETLT || CC == ISD::SETLE; 4251 } 4252 4253 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating. 4254 // All of these conditions (and their <= and >= counterparts) will do: 4255 // x < k ? k : x 4256 // x > k ? x : k 4257 // k < x ? x : k 4258 // k > x ? k : x 4259 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS, 4260 const SDValue TrueVal, const SDValue FalseVal, 4261 const ISD::CondCode CC, const SDValue K) { 4262 return (isGTorGE(CC) && 4263 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) || 4264 (isLTorLE(CC) && 4265 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))); 4266 } 4267 4268 // Similar to isLowerSaturate(), but checks for upper-saturating conditions. 4269 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS, 4270 const SDValue TrueVal, const SDValue FalseVal, 4271 const ISD::CondCode CC, const SDValue K) { 4272 return (isGTorGE(CC) && 4273 ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) || 4274 (isLTorLE(CC) && 4275 ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))); 4276 } 4277 4278 // Check if two chained conditionals could be converted into SSAT or USAT. 4279 // 4280 // SSAT can replace a set of two conditional selectors that bound a number to an 4281 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples: 4282 // 4283 // x < -k ? -k : (x > k ? k : x) 4284 // x < -k ? -k : (x < k ? x : k) 4285 // x > -k ? (x > k ? k : x) : -k 4286 // x < k ? (x < -k ? -k : x) : k 4287 // etc. 4288 // 4289 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is 4290 // a power of 2. 4291 // 4292 // It returns true if the conversion can be done, false otherwise. 4293 // Additionally, the variable is returned in parameter V, the constant in K and 4294 // usat is set to true if the conditional represents an unsigned saturation 4295 static bool isSaturatingConditional(const SDValue &Op, SDValue &V, 4296 uint64_t &K, bool &usat) { 4297 SDValue LHS1 = Op.getOperand(0); 4298 SDValue RHS1 = Op.getOperand(1); 4299 SDValue TrueVal1 = Op.getOperand(2); 4300 SDValue FalseVal1 = Op.getOperand(3); 4301 ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4302 4303 const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1; 4304 if (Op2.getOpcode() != ISD::SELECT_CC) 4305 return false; 4306 4307 SDValue LHS2 = Op2.getOperand(0); 4308 SDValue RHS2 = Op2.getOperand(1); 4309 SDValue TrueVal2 = Op2.getOperand(2); 4310 SDValue FalseVal2 = Op2.getOperand(3); 4311 ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get(); 4312 4313 // Find out which are the constants and which are the variables 4314 // in each conditional 4315 SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1) 4316 ? &RHS1 4317 : nullptr; 4318 SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2) 4319 ? &RHS2 4320 : nullptr; 4321 SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2; 4322 SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1; 4323 SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2; 4324 SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2; 4325 4326 // We must detect cases where the original operations worked with 16- or 4327 // 8-bit values. In such case, V2Tmp != V2 because the comparison operations 4328 // must work with sign-extended values but the select operations return 4329 // the original non-extended value. 4330 SDValue V2TmpReg = V2Tmp; 4331 if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG) 4332 V2TmpReg = V2Tmp->getOperand(0); 4333 4334 // Check that the registers and the constants have the correct values 4335 // in both conditionals 4336 if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp || 4337 V2TmpReg != V2) 4338 return false; 4339 4340 // Figure out which conditional is saturating the lower/upper bound. 4341 const SDValue *LowerCheckOp = 4342 isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4343 ? &Op 4344 : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4345 ? &Op2 4346 : nullptr; 4347 const SDValue *UpperCheckOp = 4348 isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1) 4349 ? &Op 4350 : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) 4351 ? &Op2 4352 : nullptr; 4353 4354 if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp) 4355 return false; 4356 4357 // Check that the constant in the lower-bound check is 4358 // the opposite of the constant in the upper-bound check 4359 // in 1's complement. 4360 int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue(); 4361 int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue(); 4362 int64_t PosVal = std::max(Val1, Val2); 4363 int64_t NegVal = std::min(Val1, Val2); 4364 4365 if (((Val1 > Val2 && UpperCheckOp == &Op) || 4366 (Val1 < Val2 && UpperCheckOp == &Op2)) && 4367 isPowerOf2_64(PosVal + 1)) { 4368 4369 // Handle the difference between USAT (unsigned) and SSAT (signed) saturation 4370 if (Val1 == ~Val2) 4371 usat = false; 4372 else if (NegVal == 0) 4373 usat = true; 4374 else 4375 return false; 4376 4377 V = V2; 4378 K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive 4379 4380 return true; 4381 } 4382 4383 return false; 4384 } 4385 4386 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 4387 EVT VT = Op.getValueType(); 4388 SDLoc dl(Op); 4389 4390 // Try to convert two saturating conditional selects into a single SSAT 4391 SDValue SatValue; 4392 uint64_t SatConstant; 4393 bool SatUSat; 4394 if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) && 4395 isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) { 4396 if (SatUSat) 4397 return DAG.getNode(ARMISD::USAT, dl, VT, SatValue, 4398 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4399 else 4400 return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue, 4401 DAG.getConstant(countTrailingOnes(SatConstant), dl, VT)); 4402 } 4403 4404 SDValue LHS = Op.getOperand(0); 4405 SDValue RHS = Op.getOperand(1); 4406 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4407 SDValue TrueVal = Op.getOperand(2); 4408 SDValue FalseVal = Op.getOperand(3); 4409 4410 // Try to convert expressions of the form x < k ? k : x (and similar forms) into 4411 // more efficient bit operations, which is possible when k is 0 or -1 4412 // On ARM and Thumb-2 which has flexible operand 2 this will result in single 4413 // instructions. On Thumb the shift and the bit operation will be two instructions. 4414 SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS) 4415 ? &RHS 4416 : nullptr; 4417 SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal; 4418 SDValue V = (KTmp == TrueVal) ? FalseVal : TrueVal; 4419 4420 if (K && isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K) && *K == KTmp) { 4421 SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, V, DAG.getConstant(31, dl, VT)); 4422 if (isNullConstant(*K)) { 4423 SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV, DAG.getConstant(-1, dl, VT)); 4424 return DAG.getNode(ISD::AND, dl, VT, V, NotShiftV); 4425 } else if (isAllOnesConstant(*K)) { 4426 return DAG.getNode(ISD::OR, dl, VT, V, ShiftV); 4427 } 4428 } 4429 4430 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4431 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4432 dl); 4433 4434 // If softenSetCCOperands only returned one value, we should compare it to 4435 // zero. 4436 if (!RHS.getNode()) { 4437 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4438 CC = ISD::SETNE; 4439 } 4440 } 4441 4442 if (LHS.getValueType() == MVT::i32) { 4443 // Try to generate VSEL on ARMv8. 4444 // The VSEL instruction can't use all the usual ARM condition 4445 // codes: it only has two bits to select the condition code, so it's 4446 // constrained to use only GE, GT, VS and EQ. 4447 // 4448 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 4449 // swap the operands of the previous compare instruction (effectively 4450 // inverting the compare condition, swapping 'less' and 'greater') and 4451 // sometimes need to swap the operands to the VSEL (which inverts the 4452 // condition in the sense of firing whenever the previous condition didn't) 4453 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4454 TrueVal.getValueType() == MVT::f64)) { 4455 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4456 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 4457 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 4458 CC = ISD::getSetCCInverse(CC, true); 4459 std::swap(TrueVal, FalseVal); 4460 } 4461 } 4462 4463 SDValue ARMcc; 4464 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4465 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4466 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4467 } 4468 4469 ARMCC::CondCodes CondCode, CondCode2; 4470 bool InvalidOnQNaN; 4471 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4472 4473 // Try to generate VMAXNM/VMINNM on ARMv8. 4474 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 4475 TrueVal.getValueType() == MVT::f64)) { 4476 bool swpCmpOps = false; 4477 bool swpVselOps = false; 4478 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 4479 4480 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 4481 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 4482 if (swpCmpOps) 4483 std::swap(LHS, RHS); 4484 if (swpVselOps) 4485 std::swap(TrueVal, FalseVal); 4486 } 4487 } 4488 4489 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4490 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4491 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4492 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG); 4493 if (CondCode2 != ARMCC::AL) { 4494 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32); 4495 // FIXME: Needs another CMP because flag can have but one use. 4496 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4497 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG); 4498 } 4499 return Result; 4500 } 4501 4502 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 4503 /// to morph to an integer compare sequence. 4504 static bool canChangeToInt(SDValue Op, bool &SeenZero, 4505 const ARMSubtarget *Subtarget) { 4506 SDNode *N = Op.getNode(); 4507 if (!N->hasOneUse()) 4508 // Otherwise it requires moving the value from fp to integer registers. 4509 return false; 4510 if (!N->getNumValues()) 4511 return false; 4512 EVT VT = Op.getValueType(); 4513 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 4514 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 4515 // vmrs are very slow, e.g. cortex-a8. 4516 return false; 4517 4518 if (isFloatingPointZero(Op)) { 4519 SeenZero = true; 4520 return true; 4521 } 4522 return ISD::isNormalLoad(N); 4523 } 4524 4525 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 4526 if (isFloatingPointZero(Op)) 4527 return DAG.getConstant(0, SDLoc(Op), MVT::i32); 4528 4529 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 4530 return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(), 4531 Ld->getPointerInfo(), Ld->getAlignment(), 4532 Ld->getMemOperand()->getFlags()); 4533 4534 llvm_unreachable("Unknown VFP cmp argument!"); 4535 } 4536 4537 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 4538 SDValue &RetVal1, SDValue &RetVal2) { 4539 SDLoc dl(Op); 4540 4541 if (isFloatingPointZero(Op)) { 4542 RetVal1 = DAG.getConstant(0, dl, MVT::i32); 4543 RetVal2 = DAG.getConstant(0, dl, MVT::i32); 4544 return; 4545 } 4546 4547 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 4548 SDValue Ptr = Ld->getBasePtr(); 4549 RetVal1 = 4550 DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(), 4551 Ld->getAlignment(), Ld->getMemOperand()->getFlags()); 4552 4553 EVT PtrType = Ptr.getValueType(); 4554 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 4555 SDValue NewPtr = DAG.getNode(ISD::ADD, dl, 4556 PtrType, Ptr, DAG.getConstant(4, dl, PtrType)); 4557 RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr, 4558 Ld->getPointerInfo().getWithOffset(4), NewAlign, 4559 Ld->getMemOperand()->getFlags()); 4560 return; 4561 } 4562 4563 llvm_unreachable("Unknown VFP cmp argument!"); 4564 } 4565 4566 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 4567 /// f32 and even f64 comparisons to integer ones. 4568 SDValue 4569 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 4570 SDValue Chain = Op.getOperand(0); 4571 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4572 SDValue LHS = Op.getOperand(2); 4573 SDValue RHS = Op.getOperand(3); 4574 SDValue Dest = Op.getOperand(4); 4575 SDLoc dl(Op); 4576 4577 bool LHSSeenZero = false; 4578 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 4579 bool RHSSeenZero = false; 4580 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 4581 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 4582 // If unsafe fp math optimization is enabled and there are no other uses of 4583 // the CMP operands, and the condition code is EQ or NE, we can optimize it 4584 // to an integer comparison. 4585 if (CC == ISD::SETOEQ) 4586 CC = ISD::SETEQ; 4587 else if (CC == ISD::SETUNE) 4588 CC = ISD::SETNE; 4589 4590 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4591 SDValue ARMcc; 4592 if (LHS.getValueType() == MVT::f32) { 4593 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4594 bitcastf32Toi32(LHS, DAG), Mask); 4595 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 4596 bitcastf32Toi32(RHS, DAG), Mask); 4597 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4598 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4599 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4600 Chain, Dest, ARMcc, CCR, Cmp); 4601 } 4602 4603 SDValue LHS1, LHS2; 4604 SDValue RHS1, RHS2; 4605 expandf64Toi32(LHS, DAG, LHS1, LHS2); 4606 expandf64Toi32(RHS, DAG, RHS1, RHS2); 4607 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 4608 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 4609 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 4610 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4611 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4612 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 4613 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops); 4614 } 4615 4616 return SDValue(); 4617 } 4618 4619 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 4620 SDValue Chain = Op.getOperand(0); 4621 SDValue Cond = Op.getOperand(1); 4622 SDValue Dest = Op.getOperand(2); 4623 SDLoc dl(Op); 4624 4625 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4626 // instruction. 4627 unsigned Opc = Cond.getOpcode(); 4628 if (Cond.getResNo() == 1 && 4629 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4630 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 4631 // Only lower legal XALUO ops. 4632 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0))) 4633 return SDValue(); 4634 4635 // The actual operation with overflow check. 4636 SDValue Value, OverflowCmp; 4637 SDValue ARMcc; 4638 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc); 4639 4640 // Reverse the condition code. 4641 ARMCC::CondCodes CondCode = 4642 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4643 CondCode = ARMCC::getOppositeCondition(CondCode); 4644 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4645 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4646 4647 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4648 OverflowCmp); 4649 } 4650 4651 return SDValue(); 4652 } 4653 4654 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4655 SDValue Chain = Op.getOperand(0); 4656 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4657 SDValue LHS = Op.getOperand(2); 4658 SDValue RHS = Op.getOperand(3); 4659 SDValue Dest = Op.getOperand(4); 4660 SDLoc dl(Op); 4661 4662 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) { 4663 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC, 4664 dl); 4665 4666 // If softenSetCCOperands only returned one value, we should compare it to 4667 // zero. 4668 if (!RHS.getNode()) { 4669 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4670 CC = ISD::SETNE; 4671 } 4672 } 4673 4674 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4675 // instruction. 4676 unsigned Opc = LHS.getOpcode(); 4677 if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) && 4678 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4679 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO) && 4680 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4681 // Only lower legal XALUO ops. 4682 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4683 return SDValue(); 4684 4685 // The actual operation with overflow check. 4686 SDValue Value, OverflowCmp; 4687 SDValue ARMcc; 4688 std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc); 4689 4690 if ((CC == ISD::SETNE) != isOneConstant(RHS)) { 4691 // Reverse the condition code. 4692 ARMCC::CondCodes CondCode = 4693 (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue(); 4694 CondCode = ARMCC::getOppositeCondition(CondCode); 4695 ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32); 4696 } 4697 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4698 4699 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR, 4700 OverflowCmp); 4701 } 4702 4703 if (LHS.getValueType() == MVT::i32) { 4704 SDValue ARMcc; 4705 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 4706 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4707 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 4708 Chain, Dest, ARMcc, CCR, Cmp); 4709 } 4710 4711 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4712 4713 if (getTargetMachine().Options.UnsafeFPMath && 4714 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 4715 CC == ISD::SETNE || CC == ISD::SETUNE)) { 4716 if (SDValue Result = OptimizeVFPBrcond(Op, DAG)) 4717 return Result; 4718 } 4719 4720 ARMCC::CondCodes CondCode, CondCode2; 4721 bool InvalidOnQNaN; 4722 FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN); 4723 4724 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32); 4725 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN); 4726 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 4727 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 4728 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 4729 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4730 if (CondCode2 != ARMCC::AL) { 4731 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32); 4732 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 4733 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops); 4734 } 4735 return Res; 4736 } 4737 4738 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 4739 SDValue Chain = Op.getOperand(0); 4740 SDValue Table = Op.getOperand(1); 4741 SDValue Index = Op.getOperand(2); 4742 SDLoc dl(Op); 4743 4744 EVT PTy = getPointerTy(DAG.getDataLayout()); 4745 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 4746 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 4747 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI); 4748 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy)); 4749 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index); 4750 if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) { 4751 // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table 4752 // which does another jump to the destination. This also makes it easier 4753 // to translate it to TBB / TBH later (Thumb2 only). 4754 // FIXME: This might not work if the function is extremely large. 4755 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 4756 Addr, Op.getOperand(2), JTI); 4757 } 4758 if (isPositionIndependent() || Subtarget->isROPI()) { 4759 Addr = 4760 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 4761 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4762 Chain = Addr.getValue(1); 4763 Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr); 4764 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4765 } else { 4766 Addr = 4767 DAG.getLoad(PTy, dl, Chain, Addr, 4768 MachinePointerInfo::getJumpTable(DAG.getMachineFunction())); 4769 Chain = Addr.getValue(1); 4770 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI); 4771 } 4772 } 4773 4774 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 4775 EVT VT = Op.getValueType(); 4776 SDLoc dl(Op); 4777 4778 if (Op.getValueType().getVectorElementType() == MVT::i32) { 4779 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 4780 return Op; 4781 return DAG.UnrollVectorOp(Op.getNode()); 4782 } 4783 4784 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 4785 "Invalid type for custom lowering!"); 4786 if (VT != MVT::v4i16) 4787 return DAG.UnrollVectorOp(Op.getNode()); 4788 4789 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 4790 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 4791 } 4792 4793 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { 4794 EVT VT = Op.getValueType(); 4795 if (VT.isVector()) 4796 return LowerVectorFP_TO_INT(Op, DAG); 4797 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) { 4798 RTLIB::Libcall LC; 4799 if (Op.getOpcode() == ISD::FP_TO_SINT) 4800 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), 4801 Op.getValueType()); 4802 else 4803 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), 4804 Op.getValueType()); 4805 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4806 /*isSigned*/ false, SDLoc(Op)).first; 4807 } 4808 4809 return Op; 4810 } 4811 4812 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 4813 EVT VT = Op.getValueType(); 4814 SDLoc dl(Op); 4815 4816 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 4817 if (VT.getVectorElementType() == MVT::f32) 4818 return Op; 4819 return DAG.UnrollVectorOp(Op.getNode()); 4820 } 4821 4822 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 4823 "Invalid type for custom lowering!"); 4824 if (VT != MVT::v4f32) 4825 return DAG.UnrollVectorOp(Op.getNode()); 4826 4827 unsigned CastOpc; 4828 unsigned Opc; 4829 switch (Op.getOpcode()) { 4830 default: llvm_unreachable("Invalid opcode!"); 4831 case ISD::SINT_TO_FP: 4832 CastOpc = ISD::SIGN_EXTEND; 4833 Opc = ISD::SINT_TO_FP; 4834 break; 4835 case ISD::UINT_TO_FP: 4836 CastOpc = ISD::ZERO_EXTEND; 4837 Opc = ISD::UINT_TO_FP; 4838 break; 4839 } 4840 4841 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 4842 return DAG.getNode(Opc, dl, VT, Op); 4843 } 4844 4845 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { 4846 EVT VT = Op.getValueType(); 4847 if (VT.isVector()) 4848 return LowerVectorINT_TO_FP(Op, DAG); 4849 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) { 4850 RTLIB::Libcall LC; 4851 if (Op.getOpcode() == ISD::SINT_TO_FP) 4852 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), 4853 Op.getValueType()); 4854 else 4855 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), 4856 Op.getValueType()); 4857 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0), 4858 /*isSigned*/ false, SDLoc(Op)).first; 4859 } 4860 4861 return Op; 4862 } 4863 4864 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 4865 // Implement fcopysign with a fabs and a conditional fneg. 4866 SDValue Tmp0 = Op.getOperand(0); 4867 SDValue Tmp1 = Op.getOperand(1); 4868 SDLoc dl(Op); 4869 EVT VT = Op.getValueType(); 4870 EVT SrcVT = Tmp1.getValueType(); 4871 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 4872 Tmp0.getOpcode() == ARMISD::VMOVDRR; 4873 bool UseNEON = !InGPR && Subtarget->hasNEON(); 4874 4875 if (UseNEON) { 4876 // Use VBSL to copy the sign bit. 4877 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 4878 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 4879 DAG.getTargetConstant(EncodedVal, dl, MVT::i32)); 4880 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 4881 if (VT == MVT::f64) 4882 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4883 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 4884 DAG.getConstant(32, dl, MVT::i32)); 4885 else /*if (VT == MVT::f32)*/ 4886 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 4887 if (SrcVT == MVT::f32) { 4888 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 4889 if (VT == MVT::f64) 4890 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 4891 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 4892 DAG.getConstant(32, dl, MVT::i32)); 4893 } else if (VT == MVT::f32) 4894 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 4895 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 4896 DAG.getConstant(32, dl, MVT::i32)); 4897 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 4898 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 4899 4900 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 4901 dl, MVT::i32); 4902 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 4903 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 4904 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 4905 4906 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 4907 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 4908 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 4909 if (VT == MVT::f32) { 4910 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 4911 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 4912 DAG.getConstant(0, dl, MVT::i32)); 4913 } else { 4914 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 4915 } 4916 4917 return Res; 4918 } 4919 4920 // Bitcast operand 1 to i32. 4921 if (SrcVT == MVT::f64) 4922 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4923 Tmp1).getValue(1); 4924 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 4925 4926 // Or in the signbit with integer operations. 4927 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32); 4928 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32); 4929 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 4930 if (VT == MVT::f32) { 4931 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 4932 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 4933 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4934 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 4935 } 4936 4937 // f64: Or the high part with signbit and then combine two parts. 4938 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 4939 Tmp0); 4940 SDValue Lo = Tmp0.getValue(0); 4941 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 4942 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 4943 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 4944 } 4945 4946 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 4947 MachineFunction &MF = DAG.getMachineFunction(); 4948 MachineFrameInfo &MFI = MF.getFrameInfo(); 4949 MFI.setReturnAddressIsTaken(true); 4950 4951 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4952 return SDValue(); 4953 4954 EVT VT = Op.getValueType(); 4955 SDLoc dl(Op); 4956 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4957 if (Depth) { 4958 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4959 SDValue Offset = DAG.getConstant(4, dl, MVT::i32); 4960 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 4961 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 4962 MachinePointerInfo()); 4963 } 4964 4965 // Return LR, which contains the return address. Mark it an implicit live-in. 4966 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 4967 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 4968 } 4969 4970 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 4971 const ARMBaseRegisterInfo &ARI = 4972 *static_cast<const ARMBaseRegisterInfo*>(RegInfo); 4973 MachineFunction &MF = DAG.getMachineFunction(); 4974 MachineFrameInfo &MFI = MF.getFrameInfo(); 4975 MFI.setFrameAddressIsTaken(true); 4976 4977 EVT VT = Op.getValueType(); 4978 SDLoc dl(Op); // FIXME probably not meaningful 4979 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4980 unsigned FrameReg = ARI.getFrameRegister(MF); 4981 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 4982 while (Depth--) 4983 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 4984 MachinePointerInfo()); 4985 return FrameAddr; 4986 } 4987 4988 // FIXME? Maybe this could be a TableGen attribute on some registers and 4989 // this table could be generated automatically from RegInfo. 4990 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT, 4991 SelectionDAG &DAG) const { 4992 unsigned Reg = StringSwitch<unsigned>(RegName) 4993 .Case("sp", ARM::SP) 4994 .Default(0); 4995 if (Reg) 4996 return Reg; 4997 report_fatal_error(Twine("Invalid register name \"" 4998 + StringRef(RegName) + "\".")); 4999 } 5000 5001 // Result is 64 bit value so split into two 32 bit values and return as a 5002 // pair of values. 5003 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results, 5004 SelectionDAG &DAG) { 5005 SDLoc DL(N); 5006 5007 // This function is only supposed to be called for i64 type destination. 5008 assert(N->getValueType(0) == MVT::i64 5009 && "ExpandREAD_REGISTER called for non-i64 type result."); 5010 5011 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL, 5012 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other), 5013 N->getOperand(0), 5014 N->getOperand(1)); 5015 5016 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0), 5017 Read.getValue(1))); 5018 Results.push_back(Read.getOperand(0)); 5019 } 5020 5021 /// \p BC is a bitcast that is about to be turned into a VMOVDRR. 5022 /// When \p DstVT, the destination type of \p BC, is on the vector 5023 /// register bank and the source of bitcast, \p Op, operates on the same bank, 5024 /// it might be possible to combine them, such that everything stays on the 5025 /// vector register bank. 5026 /// \p return The node that would replace \p BT, if the combine 5027 /// is possible. 5028 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC, 5029 SelectionDAG &DAG) { 5030 SDValue Op = BC->getOperand(0); 5031 EVT DstVT = BC->getValueType(0); 5032 5033 // The only vector instruction that can produce a scalar (remember, 5034 // since the bitcast was about to be turned into VMOVDRR, the source 5035 // type is i64) from a vector is EXTRACT_VECTOR_ELT. 5036 // Moreover, we can do this combine only if there is one use. 5037 // Finally, if the destination type is not a vector, there is not 5038 // much point on forcing everything on the vector bank. 5039 if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5040 !Op.hasOneUse()) 5041 return SDValue(); 5042 5043 // If the index is not constant, we will introduce an additional 5044 // multiply that will stick. 5045 // Give up in that case. 5046 ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 5047 if (!Index) 5048 return SDValue(); 5049 unsigned DstNumElt = DstVT.getVectorNumElements(); 5050 5051 // Compute the new index. 5052 const APInt &APIntIndex = Index->getAPIntValue(); 5053 APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt); 5054 NewIndex *= APIntIndex; 5055 // Check if the new constant index fits into i32. 5056 if (NewIndex.getBitWidth() > 32) 5057 return SDValue(); 5058 5059 // vMTy bitcast(i64 extractelt vNi64 src, i32 index) -> 5060 // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M) 5061 SDLoc dl(Op); 5062 SDValue ExtractSrc = Op.getOperand(0); 5063 EVT VecVT = EVT::getVectorVT( 5064 *DAG.getContext(), DstVT.getScalarType(), 5065 ExtractSrc.getValueType().getVectorNumElements() * DstNumElt); 5066 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc); 5067 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast, 5068 DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32)); 5069 } 5070 5071 /// ExpandBITCAST - If the target supports VFP, this function is called to 5072 /// expand a bit convert where either the source or destination type is i64 to 5073 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 5074 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 5075 /// vectors), since the legalizer won't know what to do with that. 5076 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG, 5077 const ARMSubtarget *Subtarget) { 5078 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5079 SDLoc dl(N); 5080 SDValue Op = N->getOperand(0); 5081 5082 // This function is only supposed to be called for i64 types, either as the 5083 // source or destination of the bit convert. 5084 EVT SrcVT = Op.getValueType(); 5085 EVT DstVT = N->getValueType(0); 5086 const bool HasFullFP16 = Subtarget->hasFullFP16(); 5087 5088 if (SrcVT == MVT::f32 && DstVT == MVT::i32) { 5089 // FullFP16: half values are passed in S-registers, and we don't 5090 // need any of the bitcast and moves: 5091 // 5092 // t2: f32,ch = CopyFromReg t0, Register:f32 %0 5093 // t5: i32 = bitcast t2 5094 // t18: f16 = ARMISD::VMOVhr t5 5095 if (Op.getOpcode() != ISD::CopyFromReg || 5096 Op.getValueType() != MVT::f32) 5097 return SDValue(); 5098 5099 auto Move = N->use_begin(); 5100 if (Move->getOpcode() != ARMISD::VMOVhr) 5101 return SDValue(); 5102 5103 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) }; 5104 SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops); 5105 DAG.ReplaceAllUsesWith(*Move, &Copy); 5106 return Copy; 5107 } 5108 5109 if (SrcVT == MVT::i16 && DstVT == MVT::f16) { 5110 if (!HasFullFP16) 5111 return SDValue(); 5112 // SoftFP: read half-precision arguments: 5113 // 5114 // t2: i32,ch = ... 5115 // t7: i16 = truncate t2 <~~~~ Op 5116 // t8: f16 = bitcast t7 <~~~~ N 5117 // 5118 if (Op.getOperand(0).getValueType() == MVT::i32) 5119 return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op), 5120 MVT::f16, Op.getOperand(0)); 5121 5122 return SDValue(); 5123 } 5124 5125 // Half-precision return values 5126 if (SrcVT == MVT::f16 && DstVT == MVT::i16) { 5127 if (!HasFullFP16) 5128 return SDValue(); 5129 // 5130 // t11: f16 = fadd t8, t10 5131 // t12: i16 = bitcast t11 <~~~ SDNode N 5132 // t13: i32 = zero_extend t12 5133 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13 5134 // t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1 5135 // 5136 // transform this into: 5137 // 5138 // t20: i32 = ARMISD::VMOVrh t11 5139 // t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20 5140 // 5141 auto ZeroExtend = N->use_begin(); 5142 if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND || 5143 ZeroExtend->getValueType(0) != MVT::i32) 5144 return SDValue(); 5145 5146 auto Copy = ZeroExtend->use_begin(); 5147 if (Copy->getOpcode() == ISD::CopyToReg && 5148 Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) { 5149 SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op); 5150 DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt); 5151 return Cvt; 5152 } 5153 return SDValue(); 5154 } 5155 5156 if (!(SrcVT == MVT::i64 || DstVT == MVT::i64)) 5157 return SDValue(); 5158 5159 // Turn i64->f64 into VMOVDRR. 5160 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 5161 // Do not force values to GPRs (this is what VMOVDRR does for the inputs) 5162 // if we can combine the bitcast with its source. 5163 if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG)) 5164 return Val; 5165 5166 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5167 DAG.getConstant(0, dl, MVT::i32)); 5168 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 5169 DAG.getConstant(1, dl, MVT::i32)); 5170 return DAG.getNode(ISD::BITCAST, dl, DstVT, 5171 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 5172 } 5173 5174 // Turn f64->i64 into VMOVRRD. 5175 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 5176 SDValue Cvt; 5177 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() && 5178 SrcVT.getVectorNumElements() > 1) 5179 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5180 DAG.getVTList(MVT::i32, MVT::i32), 5181 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op)); 5182 else 5183 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 5184 DAG.getVTList(MVT::i32, MVT::i32), Op); 5185 // Merge the pieces into a single i64 value. 5186 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 5187 } 5188 5189 return SDValue(); 5190 } 5191 5192 /// getZeroVector - Returns a vector of specified type with all zero elements. 5193 /// Zero vectors are used to represent vector negation and in those cases 5194 /// will be implemented with the NEON VNEG instruction. However, VNEG does 5195 /// not support i64 elements, so sometimes the zero vectors will need to be 5196 /// explicitly constructed. Regardless, use a canonical VMOV to create the 5197 /// zero vector. 5198 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) { 5199 assert(VT.isVector() && "Expected a vector type"); 5200 // The canonical modified immediate encoding of a zero vector is....0! 5201 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32); 5202 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 5203 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 5204 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 5205 } 5206 5207 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5208 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5209 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 5210 SelectionDAG &DAG) const { 5211 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5212 EVT VT = Op.getValueType(); 5213 unsigned VTBits = VT.getSizeInBits(); 5214 SDLoc dl(Op); 5215 SDValue ShOpLo = Op.getOperand(0); 5216 SDValue ShOpHi = Op.getOperand(1); 5217 SDValue ShAmt = Op.getOperand(2); 5218 SDValue ARMcc; 5219 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5220 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5221 5222 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5223 5224 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5225 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5226 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5227 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5228 DAG.getConstant(VTBits, dl, MVT::i32)); 5229 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5230 SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5231 SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5232 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5233 ISD::SETGE, ARMcc, DAG, dl); 5234 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, 5235 ARMcc, CCR, CmpLo); 5236 5237 SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5238 SDValue HiBigShift = Opc == ISD::SRA 5239 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5240 DAG.getConstant(VTBits - 1, dl, VT)) 5241 : DAG.getConstant(0, dl, VT); 5242 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5243 ISD::SETGE, ARMcc, DAG, dl); 5244 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5245 ARMcc, CCR, CmpHi); 5246 5247 SDValue Ops[2] = { Lo, Hi }; 5248 return DAG.getMergeValues(Ops, dl); 5249 } 5250 5251 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5252 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 5253 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 5254 SelectionDAG &DAG) const { 5255 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5256 EVT VT = Op.getValueType(); 5257 unsigned VTBits = VT.getSizeInBits(); 5258 SDLoc dl(Op); 5259 SDValue ShOpLo = Op.getOperand(0); 5260 SDValue ShOpHi = Op.getOperand(1); 5261 SDValue ShAmt = Op.getOperand(2); 5262 SDValue ARMcc; 5263 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5264 5265 assert(Op.getOpcode() == ISD::SHL_PARTS); 5266 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 5267 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt); 5268 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5269 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5270 SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 5271 5272 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 5273 DAG.getConstant(VTBits, dl, MVT::i32)); 5274 SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5275 SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5276 ISD::SETGE, ARMcc, DAG, dl); 5277 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, 5278 ARMcc, CCR, CmpHi); 5279 5280 SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32), 5281 ISD::SETGE, ARMcc, DAG, dl); 5282 SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5283 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, 5284 DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo); 5285 5286 SDValue Ops[2] = { Lo, Hi }; 5287 return DAG.getMergeValues(Ops, dl); 5288 } 5289 5290 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 5291 SelectionDAG &DAG) const { 5292 // The rounding mode is in bits 23:22 of the FPSCR. 5293 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 5294 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 5295 // so that the shift + and get folded into a bitfield extract. 5296 SDLoc dl(Op); 5297 SDValue Ops[] = { DAG.getEntryNode(), 5298 DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) }; 5299 5300 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops); 5301 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 5302 DAG.getConstant(1U << 22, dl, MVT::i32)); 5303 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 5304 DAG.getConstant(22, dl, MVT::i32)); 5305 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 5306 DAG.getConstant(3, dl, MVT::i32)); 5307 } 5308 5309 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 5310 const ARMSubtarget *ST) { 5311 SDLoc dl(N); 5312 EVT VT = N->getValueType(0); 5313 if (VT.isVector()) { 5314 assert(ST->hasNEON()); 5315 5316 // Compute the least significant set bit: LSB = X & -X 5317 SDValue X = N->getOperand(0); 5318 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X); 5319 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX); 5320 5321 EVT ElemTy = VT.getVectorElementType(); 5322 5323 if (ElemTy == MVT::i8) { 5324 // Compute with: cttz(x) = ctpop(lsb - 1) 5325 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5326 DAG.getTargetConstant(1, dl, ElemTy)); 5327 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5328 return DAG.getNode(ISD::CTPOP, dl, VT, Bits); 5329 } 5330 5331 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) && 5332 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) { 5333 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0 5334 unsigned NumBits = ElemTy.getSizeInBits(); 5335 SDValue WidthMinus1 = 5336 DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5337 DAG.getTargetConstant(NumBits - 1, dl, ElemTy)); 5338 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB); 5339 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ); 5340 } 5341 5342 // Compute with: cttz(x) = ctpop(lsb - 1) 5343 5344 // Since we can only compute the number of bits in a byte with vcnt.8, we 5345 // have to gather the result with pairwise addition (vpaddl) for i16, i32, 5346 // and i64. 5347 5348 // Compute LSB - 1. 5349 SDValue Bits; 5350 if (ElemTy == MVT::i64) { 5351 // Load constant 0xffff'ffff'ffff'ffff to register. 5352 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5353 DAG.getTargetConstant(0x1eff, dl, MVT::i32)); 5354 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF); 5355 } else { 5356 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT, 5357 DAG.getTargetConstant(1, dl, ElemTy)); 5358 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One); 5359 } 5360 5361 // Count #bits with vcnt.8. 5362 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5363 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits); 5364 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8); 5365 5366 // Gather the #bits with vpaddl (pairwise add.) 5367 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5368 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit, 5369 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5370 Cnt8); 5371 if (ElemTy == MVT::i16) 5372 return Cnt16; 5373 5374 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32; 5375 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit, 5376 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5377 Cnt16); 5378 if (ElemTy == MVT::i32) 5379 return Cnt32; 5380 5381 assert(ElemTy == MVT::i64); 5382 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5383 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32), 5384 Cnt32); 5385 return Cnt64; 5386 } 5387 5388 if (!ST->hasV6T2Ops()) 5389 return SDValue(); 5390 5391 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0)); 5392 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 5393 } 5394 5395 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 5396 /// for each 16-bit element from operand, repeated. The basic idea is to 5397 /// leverage vcnt to get the 8-bit counts, gather and add the results. 5398 /// 5399 /// Trace for v4i16: 5400 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5401 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 5402 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 5403 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 5404 /// [b0 b1 b2 b3 b4 b5 b6 b7] 5405 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 5406 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 5407 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 5408 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 5409 EVT VT = N->getValueType(0); 5410 SDLoc DL(N); 5411 5412 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5413 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 5414 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 5415 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 5416 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 5417 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 5418 } 5419 5420 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 5421 /// bit-count for each 16-bit element from the operand. We need slightly 5422 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 5423 /// 64/128-bit registers. 5424 /// 5425 /// Trace for v4i16: 5426 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 5427 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 5428 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 5429 /// v4i16:Extracted = [k0 k1 k2 k3 ] 5430 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 5431 EVT VT = N->getValueType(0); 5432 SDLoc DL(N); 5433 5434 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 5435 if (VT.is64BitVector()) { 5436 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 5437 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 5438 DAG.getIntPtrConstant(0, DL)); 5439 } else { 5440 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 5441 BitCounts, DAG.getIntPtrConstant(0, DL)); 5442 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 5443 } 5444 } 5445 5446 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 5447 /// bit-count for each 32-bit element from the operand. The idea here is 5448 /// to split the vector into 16-bit elements, leverage the 16-bit count 5449 /// routine, and then combine the results. 5450 /// 5451 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 5452 /// input = [v0 v1 ] (vi: 32-bit elements) 5453 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 5454 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 5455 /// vrev: N0 = [k1 k0 k3 k2 ] 5456 /// [k0 k1 k2 k3 ] 5457 /// N1 =+[k1 k0 k3 k2 ] 5458 /// [k0 k2 k1 k3 ] 5459 /// N2 =+[k1 k3 k0 k2 ] 5460 /// [k0 k2 k1 k3 ] 5461 /// Extended =+[k1 k3 k0 k2 ] 5462 /// [k0 k2 ] 5463 /// Extracted=+[k1 k3 ] 5464 /// 5465 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 5466 EVT VT = N->getValueType(0); 5467 SDLoc DL(N); 5468 5469 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 5470 5471 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 5472 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 5473 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 5474 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 5475 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 5476 5477 if (VT.is64BitVector()) { 5478 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 5479 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 5480 DAG.getIntPtrConstant(0, DL)); 5481 } else { 5482 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 5483 DAG.getIntPtrConstant(0, DL)); 5484 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 5485 } 5486 } 5487 5488 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 5489 const ARMSubtarget *ST) { 5490 EVT VT = N->getValueType(0); 5491 5492 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 5493 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 5494 VT == MVT::v4i16 || VT == MVT::v8i16) && 5495 "Unexpected type for custom ctpop lowering"); 5496 5497 if (VT.getVectorElementType() == MVT::i32) 5498 return lowerCTPOP32BitElements(N, DAG); 5499 else 5500 return lowerCTPOP16BitElements(N, DAG); 5501 } 5502 5503 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 5504 const ARMSubtarget *ST) { 5505 EVT VT = N->getValueType(0); 5506 SDLoc dl(N); 5507 5508 if (!VT.isVector()) 5509 return SDValue(); 5510 5511 // Lower vector shifts on NEON to use VSHL. 5512 assert(ST->hasNEON() && "unexpected vector shift"); 5513 5514 // Left shifts translate directly to the vshiftu intrinsic. 5515 if (N->getOpcode() == ISD::SHL) 5516 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5517 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl, 5518 MVT::i32), 5519 N->getOperand(0), N->getOperand(1)); 5520 5521 assert((N->getOpcode() == ISD::SRA || 5522 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 5523 5524 // NEON uses the same intrinsics for both left and right shifts. For 5525 // right shifts, the shift amounts are negative, so negate the vector of 5526 // shift amounts. 5527 EVT ShiftVT = N->getOperand(1).getValueType(); 5528 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 5529 getZeroVector(ShiftVT, DAG, dl), 5530 N->getOperand(1)); 5531 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 5532 Intrinsic::arm_neon_vshifts : 5533 Intrinsic::arm_neon_vshiftu); 5534 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 5535 DAG.getConstant(vshiftInt, dl, MVT::i32), 5536 N->getOperand(0), NegatedCount); 5537 } 5538 5539 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 5540 const ARMSubtarget *ST) { 5541 EVT VT = N->getValueType(0); 5542 SDLoc dl(N); 5543 5544 // We can get here for a node like i32 = ISD::SHL i32, i64 5545 if (VT != MVT::i64) 5546 return SDValue(); 5547 5548 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 5549 "Unknown shift to lower!"); 5550 5551 // We only lower SRA, SRL of 1 here, all others use generic lowering. 5552 if (!isOneConstant(N->getOperand(1))) 5553 return SDValue(); 5554 5555 // If we are in thumb mode, we don't have RRX. 5556 if (ST->isThumb1Only()) return SDValue(); 5557 5558 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 5559 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5560 DAG.getConstant(0, dl, MVT::i32)); 5561 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 5562 DAG.getConstant(1, dl, MVT::i32)); 5563 5564 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 5565 // captures the result into a carry flag. 5566 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 5567 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi); 5568 5569 // The low part is an ARMISD::RRX operand, which shifts the carry in. 5570 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 5571 5572 // Merge the pieces into a single i64 value. 5573 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5574 } 5575 5576 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 5577 SDValue TmpOp0, TmpOp1; 5578 bool Invert = false; 5579 bool Swap = false; 5580 unsigned Opc = 0; 5581 5582 SDValue Op0 = Op.getOperand(0); 5583 SDValue Op1 = Op.getOperand(1); 5584 SDValue CC = Op.getOperand(2); 5585 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger(); 5586 EVT VT = Op.getValueType(); 5587 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 5588 SDLoc dl(Op); 5589 5590 if (Op0.getValueType().getVectorElementType() == MVT::i64 && 5591 (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) { 5592 // Special-case integer 64-bit equality comparisons. They aren't legal, 5593 // but they can be lowered with a few vector instructions. 5594 unsigned CmpElements = CmpVT.getVectorNumElements() * 2; 5595 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements); 5596 SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0); 5597 SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1); 5598 SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1, 5599 DAG.getCondCode(ISD::SETEQ)); 5600 SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp); 5601 SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed); 5602 Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged); 5603 if (SetCCOpcode == ISD::SETNE) 5604 Merged = DAG.getNOT(dl, Merged, CmpVT); 5605 Merged = DAG.getSExtOrTrunc(Merged, dl, VT); 5606 return Merged; 5607 } 5608 5609 if (CmpVT.getVectorElementType() == MVT::i64) 5610 // 64-bit comparisons are not legal in general. 5611 return SDValue(); 5612 5613 if (Op1.getValueType().isFloatingPoint()) { 5614 switch (SetCCOpcode) { 5615 default: llvm_unreachable("Illegal FP comparison"); 5616 case ISD::SETUNE: 5617 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5618 case ISD::SETOEQ: 5619 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5620 case ISD::SETOLT: 5621 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5622 case ISD::SETOGT: 5623 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5624 case ISD::SETOLE: 5625 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5626 case ISD::SETOGE: 5627 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5628 case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH; 5629 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 5630 case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH; 5631 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 5632 case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH; 5633 case ISD::SETONE: 5634 // Expand this to (OLT | OGT). 5635 TmpOp0 = Op0; 5636 TmpOp1 = Op1; 5637 Opc = ISD::OR; 5638 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5639 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1); 5640 break; 5641 case ISD::SETUO: 5642 Invert = true; 5643 LLVM_FALLTHROUGH; 5644 case ISD::SETO: 5645 // Expand this to (OLT | OGE). 5646 TmpOp0 = Op0; 5647 TmpOp1 = Op1; 5648 Opc = ISD::OR; 5649 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0); 5650 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1); 5651 break; 5652 } 5653 } else { 5654 // Integer comparisons. 5655 switch (SetCCOpcode) { 5656 default: llvm_unreachable("Illegal integer comparison"); 5657 case ISD::SETNE: Invert = true; LLVM_FALLTHROUGH; 5658 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 5659 case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH; 5660 case ISD::SETGT: Opc = ARMISD::VCGT; break; 5661 case ISD::SETLE: Swap = true; LLVM_FALLTHROUGH; 5662 case ISD::SETGE: Opc = ARMISD::VCGE; break; 5663 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH; 5664 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 5665 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH; 5666 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 5667 } 5668 5669 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 5670 if (Opc == ARMISD::VCEQ) { 5671 SDValue AndOp; 5672 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5673 AndOp = Op0; 5674 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 5675 AndOp = Op1; 5676 5677 // Ignore bitconvert. 5678 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 5679 AndOp = AndOp.getOperand(0); 5680 5681 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 5682 Opc = ARMISD::VTST; 5683 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0)); 5684 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1)); 5685 Invert = !Invert; 5686 } 5687 } 5688 } 5689 5690 if (Swap) 5691 std::swap(Op0, Op1); 5692 5693 // If one of the operands is a constant vector zero, attempt to fold the 5694 // comparison to a specialized compare-against-zero form. 5695 SDValue SingleOp; 5696 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 5697 SingleOp = Op0; 5698 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 5699 if (Opc == ARMISD::VCGE) 5700 Opc = ARMISD::VCLEZ; 5701 else if (Opc == ARMISD::VCGT) 5702 Opc = ARMISD::VCLTZ; 5703 SingleOp = Op1; 5704 } 5705 5706 SDValue Result; 5707 if (SingleOp.getNode()) { 5708 switch (Opc) { 5709 case ARMISD::VCEQ: 5710 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break; 5711 case ARMISD::VCGE: 5712 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break; 5713 case ARMISD::VCLEZ: 5714 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break; 5715 case ARMISD::VCGT: 5716 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break; 5717 case ARMISD::VCLTZ: 5718 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break; 5719 default: 5720 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5721 } 5722 } else { 5723 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1); 5724 } 5725 5726 Result = DAG.getSExtOrTrunc(Result, dl, VT); 5727 5728 if (Invert) 5729 Result = DAG.getNOT(dl, Result, VT); 5730 5731 return Result; 5732 } 5733 5734 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) { 5735 SDValue LHS = Op.getOperand(0); 5736 SDValue RHS = Op.getOperand(1); 5737 SDValue Carry = Op.getOperand(2); 5738 SDValue Cond = Op.getOperand(3); 5739 SDLoc DL(Op); 5740 5741 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only."); 5742 5743 assert(Carry.getOpcode() != ISD::CARRY_FALSE); 5744 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 5745 SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry); 5746 5747 SDValue FVal = DAG.getConstant(0, DL, MVT::i32); 5748 SDValue TVal = DAG.getConstant(1, DL, MVT::i32); 5749 SDValue ARMcc = DAG.getConstant( 5750 IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32); 5751 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 5752 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR, 5753 Cmp.getValue(1), SDValue()); 5754 return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc, 5755 CCR, Chain.getValue(1)); 5756 } 5757 5758 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 5759 /// valid vector constant for a NEON instruction with a "modified immediate" 5760 /// operand (e.g., VMOV). If so, return the encoded value. 5761 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 5762 unsigned SplatBitSize, SelectionDAG &DAG, 5763 const SDLoc &dl, EVT &VT, bool is128Bits, 5764 NEONModImmType type) { 5765 unsigned OpCmode, Imm; 5766 5767 // SplatBitSize is set to the smallest size that splats the vector, so a 5768 // zero vector will always have SplatBitSize == 8. However, NEON modified 5769 // immediate instructions others than VMOV do not support the 8-bit encoding 5770 // of a zero vector, and the default encoding of zero is supposed to be the 5771 // 32-bit version. 5772 if (SplatBits == 0) 5773 SplatBitSize = 32; 5774 5775 switch (SplatBitSize) { 5776 case 8: 5777 if (type != VMOVModImm) 5778 return SDValue(); 5779 // Any 1-byte value is OK. Op=0, Cmode=1110. 5780 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 5781 OpCmode = 0xe; 5782 Imm = SplatBits; 5783 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 5784 break; 5785 5786 case 16: 5787 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 5788 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 5789 if ((SplatBits & ~0xff) == 0) { 5790 // Value = 0x00nn: Op=x, Cmode=100x. 5791 OpCmode = 0x8; 5792 Imm = SplatBits; 5793 break; 5794 } 5795 if ((SplatBits & ~0xff00) == 0) { 5796 // Value = 0xnn00: Op=x, Cmode=101x. 5797 OpCmode = 0xa; 5798 Imm = SplatBits >> 8; 5799 break; 5800 } 5801 return SDValue(); 5802 5803 case 32: 5804 // NEON's 32-bit VMOV supports splat values where: 5805 // * only one byte is nonzero, or 5806 // * the least significant byte is 0xff and the second byte is nonzero, or 5807 // * the least significant 2 bytes are 0xff and the third is nonzero. 5808 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 5809 if ((SplatBits & ~0xff) == 0) { 5810 // Value = 0x000000nn: Op=x, Cmode=000x. 5811 OpCmode = 0; 5812 Imm = SplatBits; 5813 break; 5814 } 5815 if ((SplatBits & ~0xff00) == 0) { 5816 // Value = 0x0000nn00: Op=x, Cmode=001x. 5817 OpCmode = 0x2; 5818 Imm = SplatBits >> 8; 5819 break; 5820 } 5821 if ((SplatBits & ~0xff0000) == 0) { 5822 // Value = 0x00nn0000: Op=x, Cmode=010x. 5823 OpCmode = 0x4; 5824 Imm = SplatBits >> 16; 5825 break; 5826 } 5827 if ((SplatBits & ~0xff000000) == 0) { 5828 // Value = 0xnn000000: Op=x, Cmode=011x. 5829 OpCmode = 0x6; 5830 Imm = SplatBits >> 24; 5831 break; 5832 } 5833 5834 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 5835 if (type == OtherModImm) return SDValue(); 5836 5837 if ((SplatBits & ~0xffff) == 0 && 5838 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 5839 // Value = 0x0000nnff: Op=x, Cmode=1100. 5840 OpCmode = 0xc; 5841 Imm = SplatBits >> 8; 5842 break; 5843 } 5844 5845 if ((SplatBits & ~0xffffff) == 0 && 5846 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 5847 // Value = 0x00nnffff: Op=x, Cmode=1101. 5848 OpCmode = 0xd; 5849 Imm = SplatBits >> 16; 5850 break; 5851 } 5852 5853 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 5854 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 5855 // VMOV.I32. A (very) minor optimization would be to replicate the value 5856 // and fall through here to test for a valid 64-bit splat. But, then the 5857 // caller would also need to check and handle the change in size. 5858 return SDValue(); 5859 5860 case 64: { 5861 if (type != VMOVModImm) 5862 return SDValue(); 5863 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 5864 uint64_t BitMask = 0xff; 5865 uint64_t Val = 0; 5866 unsigned ImmMask = 1; 5867 Imm = 0; 5868 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 5869 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 5870 Val |= BitMask; 5871 Imm |= ImmMask; 5872 } else if ((SplatBits & BitMask) != 0) { 5873 return SDValue(); 5874 } 5875 BitMask <<= 8; 5876 ImmMask <<= 1; 5877 } 5878 5879 if (DAG.getDataLayout().isBigEndian()) 5880 // swap higher and lower 32 bit word 5881 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4); 5882 5883 // Op=1, Cmode=1110. 5884 OpCmode = 0x1e; 5885 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 5886 break; 5887 } 5888 5889 default: 5890 llvm_unreachable("unexpected size for isNEONModifiedImm"); 5891 } 5892 5893 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 5894 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32); 5895 } 5896 5897 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 5898 const ARMSubtarget *ST) const { 5899 bool IsDouble = Op.getValueType() == MVT::f64; 5900 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 5901 const APFloat &FPVal = CFP->getValueAPF(); 5902 5903 // Prevent floating-point constants from using literal loads 5904 // when execute-only is enabled. 5905 if (ST->genExecuteOnly()) { 5906 APInt INTVal = FPVal.bitcastToAPInt(); 5907 SDLoc DL(CFP); 5908 if (IsDouble) { 5909 SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32); 5910 SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32); 5911 if (!ST->isLittle()) 5912 std::swap(Lo, Hi); 5913 return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi); 5914 } else { 5915 return DAG.getConstant(INTVal, DL, MVT::i32); 5916 } 5917 } 5918 5919 if (!ST->hasVFP3()) 5920 return SDValue(); 5921 5922 // Use the default (constant pool) lowering for double constants when we have 5923 // an SP-only FPU 5924 if (IsDouble && Subtarget->isFPOnlySP()) 5925 return SDValue(); 5926 5927 // Try splatting with a VMOV.f32... 5928 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 5929 5930 if (ImmVal != -1) { 5931 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 5932 // We have code in place to select a valid ConstantFP already, no need to 5933 // do any mangling. 5934 return Op; 5935 } 5936 5937 // It's a float and we are trying to use NEON operations where 5938 // possible. Lower it to a splat followed by an extract. 5939 SDLoc DL(Op); 5940 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32); 5941 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 5942 NewVal); 5943 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 5944 DAG.getConstant(0, DL, MVT::i32)); 5945 } 5946 5947 // The rest of our options are NEON only, make sure that's allowed before 5948 // proceeding.. 5949 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 5950 return SDValue(); 5951 5952 EVT VMovVT; 5953 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 5954 5955 // It wouldn't really be worth bothering for doubles except for one very 5956 // important value, which does happen to match: 0.0. So make sure we don't do 5957 // anything stupid. 5958 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 5959 return SDValue(); 5960 5961 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 5962 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 5963 VMovVT, false, VMOVModImm); 5964 if (NewVal != SDValue()) { 5965 SDLoc DL(Op); 5966 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 5967 NewVal); 5968 if (IsDouble) 5969 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5970 5971 // It's a float: cast and extract a vector element. 5972 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5973 VecConstant); 5974 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5975 DAG.getConstant(0, DL, MVT::i32)); 5976 } 5977 5978 // Finally, try a VMVN.i32 5979 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT, 5980 false, VMVNModImm); 5981 if (NewVal != SDValue()) { 5982 SDLoc DL(Op); 5983 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 5984 5985 if (IsDouble) 5986 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 5987 5988 // It's a float: cast and extract a vector element. 5989 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 5990 VecConstant); 5991 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 5992 DAG.getConstant(0, DL, MVT::i32)); 5993 } 5994 5995 return SDValue(); 5996 } 5997 5998 // check if an VEXT instruction can handle the shuffle mask when the 5999 // vector sources of the shuffle are the same. 6000 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6001 unsigned NumElts = VT.getVectorNumElements(); 6002 6003 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6004 if (M[0] < 0) 6005 return false; 6006 6007 Imm = M[0]; 6008 6009 // If this is a VEXT shuffle, the immediate value is the index of the first 6010 // element. The other shuffle indices must be the successive elements after 6011 // the first one. 6012 unsigned ExpectedElt = Imm; 6013 for (unsigned i = 1; i < NumElts; ++i) { 6014 // Increment the expected index. If it wraps around, just follow it 6015 // back to index zero and keep going. 6016 ++ExpectedElt; 6017 if (ExpectedElt == NumElts) 6018 ExpectedElt = 0; 6019 6020 if (M[i] < 0) continue; // ignore UNDEF indices 6021 if (ExpectedElt != static_cast<unsigned>(M[i])) 6022 return false; 6023 } 6024 6025 return true; 6026 } 6027 6028 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 6029 bool &ReverseVEXT, unsigned &Imm) { 6030 unsigned NumElts = VT.getVectorNumElements(); 6031 ReverseVEXT = false; 6032 6033 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6034 if (M[0] < 0) 6035 return false; 6036 6037 Imm = M[0]; 6038 6039 // If this is a VEXT shuffle, the immediate value is the index of the first 6040 // element. The other shuffle indices must be the successive elements after 6041 // the first one. 6042 unsigned ExpectedElt = Imm; 6043 for (unsigned i = 1; i < NumElts; ++i) { 6044 // Increment the expected index. If it wraps around, it may still be 6045 // a VEXT but the source vectors must be swapped. 6046 ExpectedElt += 1; 6047 if (ExpectedElt == NumElts * 2) { 6048 ExpectedElt = 0; 6049 ReverseVEXT = true; 6050 } 6051 6052 if (M[i] < 0) continue; // ignore UNDEF indices 6053 if (ExpectedElt != static_cast<unsigned>(M[i])) 6054 return false; 6055 } 6056 6057 // Adjust the index value if the source operands will be swapped. 6058 if (ReverseVEXT) 6059 Imm -= NumElts; 6060 6061 return true; 6062 } 6063 6064 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 6065 /// instruction with the specified blocksize. (The order of the elements 6066 /// within each block of the vector is reversed.) 6067 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6068 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 6069 "Only possible block sizes for VREV are: 16, 32, 64"); 6070 6071 unsigned EltSz = VT.getScalarSizeInBits(); 6072 if (EltSz == 64) 6073 return false; 6074 6075 unsigned NumElts = VT.getVectorNumElements(); 6076 unsigned BlockElts = M[0] + 1; 6077 // If the first shuffle index is UNDEF, be optimistic. 6078 if (M[0] < 0) 6079 BlockElts = BlockSize / EltSz; 6080 6081 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6082 return false; 6083 6084 for (unsigned i = 0; i < NumElts; ++i) { 6085 if (M[i] < 0) continue; // ignore UNDEF indices 6086 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 6087 return false; 6088 } 6089 6090 return true; 6091 } 6092 6093 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 6094 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 6095 // range, then 0 is placed into the resulting vector. So pretty much any mask 6096 // of 8 elements can work here. 6097 return VT == MVT::v8i8 && M.size() == 8; 6098 } 6099 6100 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask, 6101 unsigned Index) { 6102 if (Mask.size() == Elements * 2) 6103 return Index / Elements; 6104 return Mask[Index] == 0 ? 0 : 1; 6105 } 6106 6107 // Checks whether the shuffle mask represents a vector transpose (VTRN) by 6108 // checking that pairs of elements in the shuffle mask represent the same index 6109 // in each vector, incrementing the expected index by 2 at each step. 6110 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6] 6111 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g} 6112 // v2={e,f,g,h} 6113 // WhichResult gives the offset for each element in the mask based on which 6114 // of the two results it belongs to. 6115 // 6116 // The transpose can be represented either as: 6117 // result1 = shufflevector v1, v2, result1_shuffle_mask 6118 // result2 = shufflevector v1, v2, result2_shuffle_mask 6119 // where v1/v2 and the shuffle masks have the same number of elements 6120 // (here WhichResult (see below) indicates which result is being checked) 6121 // 6122 // or as: 6123 // results = shufflevector v1, v2, shuffle_mask 6124 // where both results are returned in one vector and the shuffle mask has twice 6125 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we 6126 // want to check the low half and high half of the shuffle mask as if it were 6127 // the other case 6128 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6129 unsigned EltSz = VT.getScalarSizeInBits(); 6130 if (EltSz == 64) 6131 return false; 6132 6133 unsigned NumElts = VT.getVectorNumElements(); 6134 if (M.size() != NumElts && M.size() != NumElts*2) 6135 return false; 6136 6137 // If the mask is twice as long as the input vector then we need to check the 6138 // upper and lower parts of the mask with a matching value for WhichResult 6139 // FIXME: A mask with only even values will be rejected in case the first 6140 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only 6141 // M[0] is used to determine WhichResult 6142 for (unsigned i = 0; i < M.size(); i += NumElts) { 6143 WhichResult = SelectPairHalf(NumElts, M, i); 6144 for (unsigned j = 0; j < NumElts; j += 2) { 6145 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6146 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult)) 6147 return false; 6148 } 6149 } 6150 6151 if (M.size() == NumElts*2) 6152 WhichResult = 0; 6153 6154 return true; 6155 } 6156 6157 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 6158 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6159 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6160 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6161 unsigned EltSz = VT.getScalarSizeInBits(); 6162 if (EltSz == 64) 6163 return false; 6164 6165 unsigned NumElts = VT.getVectorNumElements(); 6166 if (M.size() != NumElts && M.size() != NumElts*2) 6167 return false; 6168 6169 for (unsigned i = 0; i < M.size(); i += NumElts) { 6170 WhichResult = SelectPairHalf(NumElts, M, i); 6171 for (unsigned j = 0; j < NumElts; j += 2) { 6172 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) || 6173 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult)) 6174 return false; 6175 } 6176 } 6177 6178 if (M.size() == NumElts*2) 6179 WhichResult = 0; 6180 6181 return true; 6182 } 6183 6184 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking 6185 // that the mask elements are either all even and in steps of size 2 or all odd 6186 // and in steps of size 2. 6187 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6] 6188 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g} 6189 // v2={e,f,g,h} 6190 // Requires similar checks to that of isVTRNMask with 6191 // respect the how results are returned. 6192 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6193 unsigned EltSz = VT.getScalarSizeInBits(); 6194 if (EltSz == 64) 6195 return false; 6196 6197 unsigned NumElts = VT.getVectorNumElements(); 6198 if (M.size() != NumElts && M.size() != NumElts*2) 6199 return false; 6200 6201 for (unsigned i = 0; i < M.size(); i += NumElts) { 6202 WhichResult = SelectPairHalf(NumElts, M, i); 6203 for (unsigned j = 0; j < NumElts; ++j) { 6204 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult) 6205 return false; 6206 } 6207 } 6208 6209 if (M.size() == NumElts*2) 6210 WhichResult = 0; 6211 6212 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6213 if (VT.is64BitVector() && EltSz == 32) 6214 return false; 6215 6216 return true; 6217 } 6218 6219 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 6220 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6221 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6222 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6223 unsigned EltSz = VT.getScalarSizeInBits(); 6224 if (EltSz == 64) 6225 return false; 6226 6227 unsigned NumElts = VT.getVectorNumElements(); 6228 if (M.size() != NumElts && M.size() != NumElts*2) 6229 return false; 6230 6231 unsigned Half = NumElts / 2; 6232 for (unsigned i = 0; i < M.size(); i += NumElts) { 6233 WhichResult = SelectPairHalf(NumElts, M, i); 6234 for (unsigned j = 0; j < NumElts; j += Half) { 6235 unsigned Idx = WhichResult; 6236 for (unsigned k = 0; k < Half; ++k) { 6237 int MIdx = M[i + j + k]; 6238 if (MIdx >= 0 && (unsigned) MIdx != Idx) 6239 return false; 6240 Idx += 2; 6241 } 6242 } 6243 } 6244 6245 if (M.size() == NumElts*2) 6246 WhichResult = 0; 6247 6248 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6249 if (VT.is64BitVector() && EltSz == 32) 6250 return false; 6251 6252 return true; 6253 } 6254 6255 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking 6256 // that pairs of elements of the shufflemask represent the same index in each 6257 // vector incrementing sequentially through the vectors. 6258 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5] 6259 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f} 6260 // v2={e,f,g,h} 6261 // Requires similar checks to that of isVTRNMask with respect the how results 6262 // are returned. 6263 static bool isVZIPMask(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 unsigned Idx = WhichResult * NumElts / 2; 6275 for (unsigned j = 0; j < NumElts; j += 2) { 6276 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6277 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts)) 6278 return false; 6279 Idx += 1; 6280 } 6281 } 6282 6283 if (M.size() == NumElts*2) 6284 WhichResult = 0; 6285 6286 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 6287 if (VT.is64BitVector() && EltSz == 32) 6288 return false; 6289 6290 return true; 6291 } 6292 6293 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 6294 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6295 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6296 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 6297 unsigned EltSz = VT.getScalarSizeInBits(); 6298 if (EltSz == 64) 6299 return false; 6300 6301 unsigned NumElts = VT.getVectorNumElements(); 6302 if (M.size() != NumElts && M.size() != NumElts*2) 6303 return false; 6304 6305 for (unsigned i = 0; i < M.size(); i += NumElts) { 6306 WhichResult = SelectPairHalf(NumElts, M, i); 6307 unsigned Idx = WhichResult * NumElts / 2; 6308 for (unsigned j = 0; j < NumElts; j += 2) { 6309 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) || 6310 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx)) 6311 return false; 6312 Idx += 1; 6313 } 6314 } 6315 6316 if (M.size() == NumElts*2) 6317 WhichResult = 0; 6318 6319 // VZIP.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 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN), 6327 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't. 6328 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT, 6329 unsigned &WhichResult, 6330 bool &isV_UNDEF) { 6331 isV_UNDEF = false; 6332 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 6333 return ARMISD::VTRN; 6334 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 6335 return ARMISD::VUZP; 6336 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 6337 return ARMISD::VZIP; 6338 6339 isV_UNDEF = true; 6340 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6341 return ARMISD::VTRN; 6342 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6343 return ARMISD::VUZP; 6344 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 6345 return ARMISD::VZIP; 6346 6347 return 0; 6348 } 6349 6350 /// \return true if this is a reverse operation on an vector. 6351 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 6352 unsigned NumElts = VT.getVectorNumElements(); 6353 // Make sure the mask has the right size. 6354 if (NumElts != M.size()) 6355 return false; 6356 6357 // Look for <15, ..., 3, -1, 1, 0>. 6358 for (unsigned i = 0; i != NumElts; ++i) 6359 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 6360 return false; 6361 6362 return true; 6363 } 6364 6365 // If N is an integer constant that can be moved into a register in one 6366 // instruction, return an SDValue of such a constant (will become a MOV 6367 // instruction). Otherwise return null. 6368 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 6369 const ARMSubtarget *ST, const SDLoc &dl) { 6370 uint64_t Val; 6371 if (!isa<ConstantSDNode>(N)) 6372 return SDValue(); 6373 Val = cast<ConstantSDNode>(N)->getZExtValue(); 6374 6375 if (ST->isThumb1Only()) { 6376 if (Val <= 255 || ~Val <= 255) 6377 return DAG.getConstant(Val, dl, MVT::i32); 6378 } else { 6379 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 6380 return DAG.getConstant(Val, dl, MVT::i32); 6381 } 6382 return SDValue(); 6383 } 6384 6385 // If this is a case we can't handle, return null and let the default 6386 // expansion code take care of it. 6387 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 6388 const ARMSubtarget *ST) const { 6389 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6390 SDLoc dl(Op); 6391 EVT VT = Op.getValueType(); 6392 6393 APInt SplatBits, SplatUndef; 6394 unsigned SplatBitSize; 6395 bool HasAnyUndefs; 6396 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6397 if (SplatUndef.isAllOnesValue()) 6398 return DAG.getUNDEF(VT); 6399 6400 if (SplatBitSize <= 64) { 6401 // Check if an immediate VMOV works. 6402 EVT VmovVT; 6403 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 6404 SplatUndef.getZExtValue(), SplatBitSize, 6405 DAG, dl, VmovVT, VT.is128BitVector(), 6406 VMOVModImm); 6407 if (Val.getNode()) { 6408 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 6409 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6410 } 6411 6412 // Try an immediate VMVN. 6413 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 6414 Val = isNEONModifiedImm(NegatedImm, 6415 SplatUndef.getZExtValue(), SplatBitSize, 6416 DAG, dl, VmovVT, VT.is128BitVector(), 6417 VMVNModImm); 6418 if (Val.getNode()) { 6419 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 6420 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 6421 } 6422 6423 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 6424 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 6425 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 6426 if (ImmVal != -1) { 6427 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32); 6428 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 6429 } 6430 } 6431 } 6432 } 6433 6434 // Scan through the operands to see if only one value is used. 6435 // 6436 // As an optimisation, even if more than one value is used it may be more 6437 // profitable to splat with one value then change some lanes. 6438 // 6439 // Heuristically we decide to do this if the vector has a "dominant" value, 6440 // defined as splatted to more than half of the lanes. 6441 unsigned NumElts = VT.getVectorNumElements(); 6442 bool isOnlyLowElement = true; 6443 bool usesOnlyOneValue = true; 6444 bool hasDominantValue = false; 6445 bool isConstant = true; 6446 6447 // Map of the number of times a particular SDValue appears in the 6448 // element list. 6449 DenseMap<SDValue, unsigned> ValueCounts; 6450 SDValue Value; 6451 for (unsigned i = 0; i < NumElts; ++i) { 6452 SDValue V = Op.getOperand(i); 6453 if (V.isUndef()) 6454 continue; 6455 if (i > 0) 6456 isOnlyLowElement = false; 6457 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6458 isConstant = false; 6459 6460 ValueCounts.insert(std::make_pair(V, 0)); 6461 unsigned &Count = ValueCounts[V]; 6462 6463 // Is this value dominant? (takes up more than half of the lanes) 6464 if (++Count > (NumElts / 2)) { 6465 hasDominantValue = true; 6466 Value = V; 6467 } 6468 } 6469 if (ValueCounts.size() != 1) 6470 usesOnlyOneValue = false; 6471 if (!Value.getNode() && !ValueCounts.empty()) 6472 Value = ValueCounts.begin()->first; 6473 6474 if (ValueCounts.empty()) 6475 return DAG.getUNDEF(VT); 6476 6477 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 6478 // Keep going if we are hitting this case. 6479 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 6480 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6481 6482 unsigned EltSize = VT.getScalarSizeInBits(); 6483 6484 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 6485 // i32 and try again. 6486 if (hasDominantValue && EltSize <= 32) { 6487 if (!isConstant) { 6488 SDValue N; 6489 6490 // If we are VDUPing a value that comes directly from a vector, that will 6491 // cause an unnecessary move to and from a GPR, where instead we could 6492 // just use VDUPLANE. We can only do this if the lane being extracted 6493 // is at a constant index, as the VDUP from lane instructions only have 6494 // constant-index forms. 6495 ConstantSDNode *constIndex; 6496 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6497 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) { 6498 // We need to create a new undef vector to use for the VDUPLANE if the 6499 // size of the vector from which we get the value is different than the 6500 // size of the vector that we need to create. We will insert the element 6501 // such that the register coalescer will remove unnecessary copies. 6502 if (VT != Value->getOperand(0).getValueType()) { 6503 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 6504 VT.getVectorNumElements(); 6505 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6506 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 6507 Value, DAG.getConstant(index, dl, MVT::i32)), 6508 DAG.getConstant(index, dl, MVT::i32)); 6509 } else 6510 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6511 Value->getOperand(0), Value->getOperand(1)); 6512 } else 6513 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 6514 6515 if (!usesOnlyOneValue) { 6516 // The dominant value was splatted as 'N', but we now have to insert 6517 // all differing elements. 6518 for (unsigned I = 0; I < NumElts; ++I) { 6519 if (Op.getOperand(I) == Value) 6520 continue; 6521 SmallVector<SDValue, 3> Ops; 6522 Ops.push_back(N); 6523 Ops.push_back(Op.getOperand(I)); 6524 Ops.push_back(DAG.getConstant(I, dl, MVT::i32)); 6525 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops); 6526 } 6527 } 6528 return N; 6529 } 6530 if (VT.getVectorElementType().isFloatingPoint()) { 6531 SmallVector<SDValue, 8> Ops; 6532 for (unsigned i = 0; i < NumElts; ++i) 6533 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 6534 Op.getOperand(i))); 6535 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 6536 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6537 Val = LowerBUILD_VECTOR(Val, DAG, ST); 6538 if (Val.getNode()) 6539 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6540 } 6541 if (usesOnlyOneValue) { 6542 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 6543 if (isConstant && Val.getNode()) 6544 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 6545 } 6546 } 6547 6548 // If all elements are constants and the case above didn't get hit, fall back 6549 // to the default expansion, which will generate a load from the constant 6550 // pool. 6551 if (isConstant) 6552 return SDValue(); 6553 6554 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6555 if (NumElts >= 4) { 6556 SDValue shuffle = ReconstructShuffle(Op, DAG); 6557 if (shuffle != SDValue()) 6558 return shuffle; 6559 } 6560 6561 if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) { 6562 // If we haven't found an efficient lowering, try splitting a 128-bit vector 6563 // into two 64-bit vectors; we might discover a better way to lower it. 6564 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts); 6565 EVT ExtVT = VT.getVectorElementType(); 6566 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2); 6567 SDValue Lower = 6568 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2)); 6569 if (Lower.getOpcode() == ISD::BUILD_VECTOR) 6570 Lower = LowerBUILD_VECTOR(Lower, DAG, ST); 6571 SDValue Upper = DAG.getBuildVector( 6572 HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2)); 6573 if (Upper.getOpcode() == ISD::BUILD_VECTOR) 6574 Upper = LowerBUILD_VECTOR(Upper, DAG, ST); 6575 if (Lower && Upper) 6576 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper); 6577 } 6578 6579 // Vectors with 32- or 64-bit elements can be built by directly assigning 6580 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 6581 // will be legalized. 6582 if (EltSize >= 32) { 6583 // Do the expansion with floating-point types, since that is what the VFP 6584 // registers are defined to use, and since i64 is not legal. 6585 EVT EltVT = EVT::getFloatingPointVT(EltSize); 6586 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 6587 SmallVector<SDValue, 8> Ops; 6588 for (unsigned i = 0; i < NumElts; ++i) 6589 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 6590 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 6591 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6592 } 6593 6594 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6595 // know the default expansion would otherwise fall back on something even 6596 // worse. For a vector with one or two non-undef values, that's 6597 // scalar_to_vector for the elements followed by a shuffle (provided the 6598 // shuffle is valid for the target) and materialization element by element 6599 // on the stack followed by a load for everything else. 6600 if (!isConstant && !usesOnlyOneValue) { 6601 SDValue Vec = DAG.getUNDEF(VT); 6602 for (unsigned i = 0 ; i < NumElts; ++i) { 6603 SDValue V = Op.getOperand(i); 6604 if (V.isUndef()) 6605 continue; 6606 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32); 6607 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6608 } 6609 return Vec; 6610 } 6611 6612 return SDValue(); 6613 } 6614 6615 // Gather data to see if the operation can be modelled as a 6616 // shuffle in combination with VEXTs. 6617 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 6618 SelectionDAG &DAG) const { 6619 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6620 SDLoc dl(Op); 6621 EVT VT = Op.getValueType(); 6622 unsigned NumElts = VT.getVectorNumElements(); 6623 6624 struct ShuffleSourceInfo { 6625 SDValue Vec; 6626 unsigned MinElt = std::numeric_limits<unsigned>::max(); 6627 unsigned MaxElt = 0; 6628 6629 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6630 // be compatible with the shuffle we intend to construct. As a result 6631 // ShuffleVec will be some sliding window into the original Vec. 6632 SDValue ShuffleVec; 6633 6634 // Code should guarantee that element i in Vec starts at element "WindowBase 6635 // + i * WindowScale in ShuffleVec". 6636 int WindowBase = 0; 6637 int WindowScale = 1; 6638 6639 ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {} 6640 6641 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6642 }; 6643 6644 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6645 // node. 6646 SmallVector<ShuffleSourceInfo, 2> Sources; 6647 for (unsigned i = 0; i < NumElts; ++i) { 6648 SDValue V = Op.getOperand(i); 6649 if (V.isUndef()) 6650 continue; 6651 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 6652 // A shuffle can only come from building a vector from various 6653 // elements of other vectors. 6654 return SDValue(); 6655 } else if (!isa<ConstantSDNode>(V.getOperand(1))) { 6656 // Furthermore, shuffles require a constant mask, whereas extractelts 6657 // accept variable indices. 6658 return SDValue(); 6659 } 6660 6661 // Add this element source to the list if it's not already there. 6662 SDValue SourceVec = V.getOperand(0); 6663 auto Source = llvm::find(Sources, SourceVec); 6664 if (Source == Sources.end()) 6665 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6666 6667 // Update the minimum and maximum lane number seen. 6668 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6669 Source->MinElt = std::min(Source->MinElt, EltNo); 6670 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6671 } 6672 6673 // Currently only do something sane when at most two source vectors 6674 // are involved. 6675 if (Sources.size() > 2) 6676 return SDValue(); 6677 6678 // Find out the smallest element size among result and two sources, and use 6679 // it as element size to build the shuffle_vector. 6680 EVT SmallestEltTy = VT.getVectorElementType(); 6681 for (auto &Source : Sources) { 6682 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6683 if (SrcEltTy.bitsLT(SmallestEltTy)) 6684 SmallestEltTy = SrcEltTy; 6685 } 6686 unsigned ResMultiplier = 6687 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6688 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6689 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6690 6691 // If the source vector is too wide or too narrow, we may nevertheless be able 6692 // to construct a compatible shuffle either by concatenating it with UNDEF or 6693 // extracting a suitable range of elements. 6694 for (auto &Src : Sources) { 6695 EVT SrcVT = Src.ShuffleVec.getValueType(); 6696 6697 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6698 continue; 6699 6700 // This stage of the search produces a source with the same element type as 6701 // the original, but with a total width matching the BUILD_VECTOR output. 6702 EVT EltVT = SrcVT.getVectorElementType(); 6703 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6704 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6705 6706 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6707 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits()) 6708 return SDValue(); 6709 // We can pad out the smaller vector for free, so if it's part of a 6710 // shuffle... 6711 Src.ShuffleVec = 6712 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6713 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6714 continue; 6715 } 6716 6717 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) 6718 return SDValue(); 6719 6720 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6721 // Span too large for a VEXT to cope 6722 return SDValue(); 6723 } 6724 6725 if (Src.MinElt >= NumSrcElts) { 6726 // The extraction can just take the second half 6727 Src.ShuffleVec = 6728 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6729 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6730 Src.WindowBase = -NumSrcElts; 6731 } else if (Src.MaxElt < NumSrcElts) { 6732 // The extraction can just take the first half 6733 Src.ShuffleVec = 6734 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6735 DAG.getConstant(0, dl, MVT::i32)); 6736 } else { 6737 // An actual VEXT is needed 6738 SDValue VEXTSrc1 = 6739 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6740 DAG.getConstant(0, dl, MVT::i32)); 6741 SDValue VEXTSrc2 = 6742 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6743 DAG.getConstant(NumSrcElts, dl, MVT::i32)); 6744 6745 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1, 6746 VEXTSrc2, 6747 DAG.getConstant(Src.MinElt, dl, MVT::i32)); 6748 Src.WindowBase = -Src.MinElt; 6749 } 6750 } 6751 6752 // Another possible incompatibility occurs from the vector element types. We 6753 // can fix this by bitcasting the source vectors to the same type we intend 6754 // for the shuffle. 6755 for (auto &Src : Sources) { 6756 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6757 if (SrcEltTy == SmallestEltTy) 6758 continue; 6759 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6760 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6761 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6762 Src.WindowBase *= Src.WindowScale; 6763 } 6764 6765 // Final sanity check before we try to actually produce a shuffle. 6766 DEBUG( 6767 for (auto Src : Sources) 6768 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 6769 ); 6770 6771 // The stars all align, our next step is to produce the mask for the shuffle. 6772 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6773 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6774 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6775 SDValue Entry = Op.getOperand(i); 6776 if (Entry.isUndef()) 6777 continue; 6778 6779 auto Src = llvm::find(Sources, Entry.getOperand(0)); 6780 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6781 6782 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6783 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6784 // segment. 6785 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6786 int BitsDefined = std::min(OrigEltTy.getSizeInBits(), 6787 VT.getScalarSizeInBits()); 6788 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6789 6790 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6791 // starting at the appropriate offset. 6792 int *LaneMask = &Mask[i * ResMultiplier]; 6793 6794 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6795 ExtractBase += NumElts * (Src - Sources.begin()); 6796 for (int j = 0; j < LanesDefined; ++j) 6797 LaneMask[j] = ExtractBase + j; 6798 } 6799 6800 // Final check before we try to produce nonsense... 6801 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 6802 return SDValue(); 6803 6804 // We can't handle more than two sources. This should have already 6805 // been checked before this point. 6806 assert(Sources.size() <= 2 && "Too many sources!"); 6807 6808 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6809 for (unsigned i = 0; i < Sources.size(); ++i) 6810 ShuffleOps[i] = Sources[i].ShuffleVec; 6811 6812 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6813 ShuffleOps[1], Mask); 6814 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6815 } 6816 6817 /// isShuffleMaskLegal - Targets can use this to indicate that they only 6818 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 6819 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 6820 /// are assumed to be legal. 6821 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 6822 if (VT.getVectorNumElements() == 4 && 6823 (VT.is128BitVector() || VT.is64BitVector())) { 6824 unsigned PFIndexes[4]; 6825 for (unsigned i = 0; i != 4; ++i) { 6826 if (M[i] < 0) 6827 PFIndexes[i] = 8; 6828 else 6829 PFIndexes[i] = M[i]; 6830 } 6831 6832 // Compute the index in the perfect shuffle table. 6833 unsigned PFTableIndex = 6834 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 6835 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6836 unsigned Cost = (PFEntry >> 30); 6837 6838 if (Cost <= 4) 6839 return true; 6840 } 6841 6842 bool ReverseVEXT, isV_UNDEF; 6843 unsigned Imm, WhichResult; 6844 6845 unsigned EltSize = VT.getScalarSizeInBits(); 6846 return (EltSize >= 32 || 6847 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 6848 isVREVMask(M, VT, 64) || 6849 isVREVMask(M, VT, 32) || 6850 isVREVMask(M, VT, 16) || 6851 isVEXTMask(M, VT, ReverseVEXT, Imm) || 6852 isVTBLMask(M, VT) || 6853 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) || 6854 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 6855 } 6856 6857 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6858 /// the specified operations to build the shuffle. 6859 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6860 SDValue RHS, SelectionDAG &DAG, 6861 const SDLoc &dl) { 6862 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6863 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 6864 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 6865 6866 enum { 6867 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6868 OP_VREV, 6869 OP_VDUP0, 6870 OP_VDUP1, 6871 OP_VDUP2, 6872 OP_VDUP3, 6873 OP_VEXT1, 6874 OP_VEXT2, 6875 OP_VEXT3, 6876 OP_VUZPL, // VUZP, left result 6877 OP_VUZPR, // VUZP, right result 6878 OP_VZIPL, // VZIP, left result 6879 OP_VZIPR, // VZIP, right result 6880 OP_VTRNL, // VTRN, left result 6881 OP_VTRNR // VTRN, right result 6882 }; 6883 6884 if (OpNum == OP_COPY) { 6885 if (LHSID == (1*9+2)*9+3) return LHS; 6886 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 6887 return RHS; 6888 } 6889 6890 SDValue OpLHS, OpRHS; 6891 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6892 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6893 EVT VT = OpLHS.getValueType(); 6894 6895 switch (OpNum) { 6896 default: llvm_unreachable("Unknown shuffle opcode!"); 6897 case OP_VREV: 6898 // VREV divides the vector in half and swaps within the half. 6899 if (VT.getVectorElementType() == MVT::i32 || 6900 VT.getVectorElementType() == MVT::f32) 6901 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 6902 // vrev <4 x i16> -> VREV32 6903 if (VT.getVectorElementType() == MVT::i16) 6904 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 6905 // vrev <4 x i8> -> VREV16 6906 assert(VT.getVectorElementType() == MVT::i8); 6907 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 6908 case OP_VDUP0: 6909 case OP_VDUP1: 6910 case OP_VDUP2: 6911 case OP_VDUP3: 6912 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 6913 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32)); 6914 case OP_VEXT1: 6915 case OP_VEXT2: 6916 case OP_VEXT3: 6917 return DAG.getNode(ARMISD::VEXT, dl, VT, 6918 OpLHS, OpRHS, 6919 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32)); 6920 case OP_VUZPL: 6921 case OP_VUZPR: 6922 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 6923 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 6924 case OP_VZIPL: 6925 case OP_VZIPR: 6926 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 6927 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 6928 case OP_VTRNL: 6929 case OP_VTRNR: 6930 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 6931 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 6932 } 6933 } 6934 6935 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 6936 ArrayRef<int> ShuffleMask, 6937 SelectionDAG &DAG) { 6938 // Check to see if we can use the VTBL instruction. 6939 SDValue V1 = Op.getOperand(0); 6940 SDValue V2 = Op.getOperand(1); 6941 SDLoc DL(Op); 6942 6943 SmallVector<SDValue, 8> VTBLMask; 6944 for (ArrayRef<int>::iterator 6945 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 6946 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32)); 6947 6948 if (V2.getNode()->isUndef()) 6949 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 6950 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6951 6952 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 6953 DAG.getBuildVector(MVT::v8i8, DL, VTBLMask)); 6954 } 6955 6956 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 6957 SelectionDAG &DAG) { 6958 SDLoc DL(Op); 6959 SDValue OpLHS = Op.getOperand(0); 6960 EVT VT = OpLHS.getValueType(); 6961 6962 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 6963 "Expect an v8i16/v16i8 type"); 6964 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 6965 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 6966 // extract the first 8 bytes into the top double word and the last 8 bytes 6967 // into the bottom double word. The v8i16 case is similar. 6968 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 6969 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 6970 DAG.getConstant(ExtractNum, DL, MVT::i32)); 6971 } 6972 6973 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 6974 SDValue V1 = Op.getOperand(0); 6975 SDValue V2 = Op.getOperand(1); 6976 SDLoc dl(Op); 6977 EVT VT = Op.getValueType(); 6978 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6979 6980 // Convert shuffles that are directly supported on NEON to target-specific 6981 // DAG nodes, instead of keeping them as shuffles and matching them again 6982 // during code selection. This is more efficient and avoids the possibility 6983 // of inconsistencies between legalization and selection. 6984 // FIXME: floating-point vectors should be canonicalized to integer vectors 6985 // of the same time so that they get CSEd properly. 6986 ArrayRef<int> ShuffleMask = SVN->getMask(); 6987 6988 unsigned EltSize = VT.getScalarSizeInBits(); 6989 if (EltSize <= 32) { 6990 if (SVN->isSplat()) { 6991 int Lane = SVN->getSplatIndex(); 6992 // If this is undef splat, generate it via "just" vdup, if possible. 6993 if (Lane == -1) Lane = 0; 6994 6995 // Test if V1 is a SCALAR_TO_VECTOR. 6996 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 6997 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 6998 } 6999 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 7000 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 7001 // reaches it). 7002 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 7003 !isa<ConstantSDNode>(V1.getOperand(0))) { 7004 bool IsScalarToVector = true; 7005 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 7006 if (!V1.getOperand(i).isUndef()) { 7007 IsScalarToVector = false; 7008 break; 7009 } 7010 if (IsScalarToVector) 7011 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 7012 } 7013 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 7014 DAG.getConstant(Lane, dl, MVT::i32)); 7015 } 7016 7017 bool ReverseVEXT; 7018 unsigned Imm; 7019 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 7020 if (ReverseVEXT) 7021 std::swap(V1, V2); 7022 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 7023 DAG.getConstant(Imm, dl, MVT::i32)); 7024 } 7025 7026 if (isVREVMask(ShuffleMask, VT, 64)) 7027 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 7028 if (isVREVMask(ShuffleMask, VT, 32)) 7029 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 7030 if (isVREVMask(ShuffleMask, VT, 16)) 7031 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 7032 7033 if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 7034 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 7035 DAG.getConstant(Imm, dl, MVT::i32)); 7036 } 7037 7038 // Check for Neon shuffles that modify both input vectors in place. 7039 // If both results are used, i.e., if there are two shuffles with the same 7040 // source operands and with masks corresponding to both results of one of 7041 // these operations, DAG memoization will ensure that a single node is 7042 // used for both shuffles. 7043 unsigned WhichResult; 7044 bool isV_UNDEF; 7045 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7046 ShuffleMask, VT, WhichResult, isV_UNDEF)) { 7047 if (isV_UNDEF) 7048 V2 = V1; 7049 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2) 7050 .getValue(WhichResult); 7051 } 7052 7053 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize 7054 // shuffles that produce a result larger than their operands with: 7055 // shuffle(concat(v1, undef), concat(v2, undef)) 7056 // -> 7057 // shuffle(concat(v1, v2), undef) 7058 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine). 7059 // 7060 // This is useful in the general case, but there are special cases where 7061 // native shuffles produce larger results: the two-result ops. 7062 // 7063 // Look through the concat when lowering them: 7064 // shuffle(concat(v1, v2), undef) 7065 // -> 7066 // concat(VZIP(v1, v2):0, :1) 7067 // 7068 if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) { 7069 SDValue SubV1 = V1->getOperand(0); 7070 SDValue SubV2 = V1->getOperand(1); 7071 EVT SubVT = SubV1.getValueType(); 7072 7073 // We expect these to have been canonicalized to -1. 7074 assert(llvm::all_of(ShuffleMask, [&](int i) { 7075 return i < (int)VT.getVectorNumElements(); 7076 }) && "Unexpected shuffle index into UNDEF operand!"); 7077 7078 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask( 7079 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) { 7080 if (isV_UNDEF) 7081 SubV2 = SubV1; 7082 assert((WhichResult == 0) && 7083 "In-place shuffle of concat can only have one result!"); 7084 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT), 7085 SubV1, SubV2); 7086 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0), 7087 Res.getValue(1)); 7088 } 7089 } 7090 } 7091 7092 // If the shuffle is not directly supported and it has 4 elements, use 7093 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7094 unsigned NumElts = VT.getVectorNumElements(); 7095 if (NumElts == 4) { 7096 unsigned PFIndexes[4]; 7097 for (unsigned i = 0; i != 4; ++i) { 7098 if (ShuffleMask[i] < 0) 7099 PFIndexes[i] = 8; 7100 else 7101 PFIndexes[i] = ShuffleMask[i]; 7102 } 7103 7104 // Compute the index in the perfect shuffle table. 7105 unsigned PFTableIndex = 7106 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 7107 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7108 unsigned Cost = (PFEntry >> 30); 7109 7110 if (Cost <= 4) 7111 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7112 } 7113 7114 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 7115 if (EltSize >= 32) { 7116 // Do the expansion with floating-point types, since that is what the VFP 7117 // registers are defined to use, and since i64 is not legal. 7118 EVT EltVT = EVT::getFloatingPointVT(EltSize); 7119 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 7120 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 7121 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 7122 SmallVector<SDValue, 8> Ops; 7123 for (unsigned i = 0; i < NumElts; ++i) { 7124 if (ShuffleMask[i] < 0) 7125 Ops.push_back(DAG.getUNDEF(EltVT)); 7126 else 7127 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 7128 ShuffleMask[i] < (int)NumElts ? V1 : V2, 7129 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 7130 dl, MVT::i32))); 7131 } 7132 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops); 7133 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7134 } 7135 7136 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 7137 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 7138 7139 if (VT == MVT::v8i8) 7140 if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG)) 7141 return NewOp; 7142 7143 return SDValue(); 7144 } 7145 7146 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7147 // INSERT_VECTOR_ELT is legal only for immediate indexes. 7148 SDValue Lane = Op.getOperand(2); 7149 if (!isa<ConstantSDNode>(Lane)) 7150 return SDValue(); 7151 7152 return Op; 7153 } 7154 7155 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 7156 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 7157 SDValue Lane = Op.getOperand(1); 7158 if (!isa<ConstantSDNode>(Lane)) 7159 return SDValue(); 7160 7161 SDValue Vec = Op.getOperand(0); 7162 if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) { 7163 SDLoc dl(Op); 7164 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 7165 } 7166 7167 return Op; 7168 } 7169 7170 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 7171 // The only time a CONCAT_VECTORS operation can have legal types is when 7172 // two 64-bit vectors are concatenated to a 128-bit vector. 7173 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 7174 "unexpected CONCAT_VECTORS"); 7175 SDLoc dl(Op); 7176 SDValue Val = DAG.getUNDEF(MVT::v2f64); 7177 SDValue Op0 = Op.getOperand(0); 7178 SDValue Op1 = Op.getOperand(1); 7179 if (!Op0.isUndef()) 7180 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7181 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 7182 DAG.getIntPtrConstant(0, dl)); 7183 if (!Op1.isUndef()) 7184 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 7185 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 7186 DAG.getIntPtrConstant(1, dl)); 7187 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 7188 } 7189 7190 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 7191 /// element has been zero/sign-extended, depending on the isSigned parameter, 7192 /// from an integer type half its size. 7193 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 7194 bool isSigned) { 7195 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 7196 EVT VT = N->getValueType(0); 7197 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 7198 SDNode *BVN = N->getOperand(0).getNode(); 7199 if (BVN->getValueType(0) != MVT::v4i32 || 7200 BVN->getOpcode() != ISD::BUILD_VECTOR) 7201 return false; 7202 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7203 unsigned HiElt = 1 - LoElt; 7204 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 7205 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 7206 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 7207 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 7208 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 7209 return false; 7210 if (isSigned) { 7211 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 7212 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 7213 return true; 7214 } else { 7215 if (Hi0->isNullValue() && Hi1->isNullValue()) 7216 return true; 7217 } 7218 return false; 7219 } 7220 7221 if (N->getOpcode() != ISD::BUILD_VECTOR) 7222 return false; 7223 7224 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 7225 SDNode *Elt = N->getOperand(i).getNode(); 7226 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 7227 unsigned EltSize = VT.getScalarSizeInBits(); 7228 unsigned HalfSize = EltSize / 2; 7229 if (isSigned) { 7230 if (!isIntN(HalfSize, C->getSExtValue())) 7231 return false; 7232 } else { 7233 if (!isUIntN(HalfSize, C->getZExtValue())) 7234 return false; 7235 } 7236 continue; 7237 } 7238 return false; 7239 } 7240 7241 return true; 7242 } 7243 7244 /// isSignExtended - Check if a node is a vector value that is sign-extended 7245 /// or a constant BUILD_VECTOR with sign-extended elements. 7246 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 7247 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 7248 return true; 7249 if (isExtendedBUILD_VECTOR(N, DAG, true)) 7250 return true; 7251 return false; 7252 } 7253 7254 /// isZeroExtended - Check if a node is a vector value that is zero-extended 7255 /// or a constant BUILD_VECTOR with zero-extended elements. 7256 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 7257 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 7258 return true; 7259 if (isExtendedBUILD_VECTOR(N, DAG, false)) 7260 return true; 7261 return false; 7262 } 7263 7264 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 7265 if (OrigVT.getSizeInBits() >= 64) 7266 return OrigVT; 7267 7268 assert(OrigVT.isSimple() && "Expecting a simple value type"); 7269 7270 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 7271 switch (OrigSimpleTy) { 7272 default: llvm_unreachable("Unexpected Vector Type"); 7273 case MVT::v2i8: 7274 case MVT::v2i16: 7275 return MVT::v2i32; 7276 case MVT::v4i8: 7277 return MVT::v4i16; 7278 } 7279 } 7280 7281 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 7282 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 7283 /// We insert the required extension here to get the vector to fill a D register. 7284 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 7285 const EVT &OrigTy, 7286 const EVT &ExtTy, 7287 unsigned ExtOpcode) { 7288 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 7289 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 7290 // 64-bits we need to insert a new extension so that it will be 64-bits. 7291 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 7292 if (OrigTy.getSizeInBits() >= 64) 7293 return N; 7294 7295 // Must extend size to at least 64 bits to be used as an operand for VMULL. 7296 EVT NewVT = getExtensionTo64Bits(OrigTy); 7297 7298 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 7299 } 7300 7301 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 7302 /// does not do any sign/zero extension. If the original vector is less 7303 /// than 64 bits, an appropriate extension will be added after the load to 7304 /// reach a total size of 64 bits. We have to add the extension separately 7305 /// because ARM does not have a sign/zero extending load for vectors. 7306 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 7307 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 7308 7309 // The load already has the right type. 7310 if (ExtendedTy == LD->getMemoryVT()) 7311 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 7312 LD->getBasePtr(), LD->getPointerInfo(), 7313 LD->getAlignment(), LD->getMemOperand()->getFlags()); 7314 7315 // We need to create a zextload/sextload. We cannot just create a load 7316 // followed by a zext/zext node because LowerMUL is also run during normal 7317 // operation legalization where we can't create illegal types. 7318 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 7319 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 7320 LD->getMemoryVT(), LD->getAlignment(), 7321 LD->getMemOperand()->getFlags()); 7322 } 7323 7324 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 7325 /// extending load, or BUILD_VECTOR with extended elements, return the 7326 /// unextended value. The unextended vector should be 64 bits so that it can 7327 /// be used as an operand to a VMULL instruction. If the original vector size 7328 /// before extension is less than 64 bits we add a an extension to resize 7329 /// the vector to 64 bits. 7330 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 7331 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 7332 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 7333 N->getOperand(0)->getValueType(0), 7334 N->getValueType(0), 7335 N->getOpcode()); 7336 7337 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 7338 assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) && 7339 "Expected extending load"); 7340 7341 SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG); 7342 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1)); 7343 unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 7344 SDValue extLoad = 7345 DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad); 7346 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad); 7347 7348 return newLoad; 7349 } 7350 7351 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 7352 // have been legalized as a BITCAST from v4i32. 7353 if (N->getOpcode() == ISD::BITCAST) { 7354 SDNode *BVN = N->getOperand(0).getNode(); 7355 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 7356 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 7357 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0; 7358 return DAG.getBuildVector( 7359 MVT::v2i32, SDLoc(N), 7360 {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)}); 7361 } 7362 // Construct a new BUILD_VECTOR with elements truncated to half the size. 7363 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 7364 EVT VT = N->getValueType(0); 7365 unsigned EltSize = VT.getScalarSizeInBits() / 2; 7366 unsigned NumElts = VT.getVectorNumElements(); 7367 MVT TruncVT = MVT::getIntegerVT(EltSize); 7368 SmallVector<SDValue, 8> Ops; 7369 SDLoc dl(N); 7370 for (unsigned i = 0; i != NumElts; ++i) { 7371 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 7372 const APInt &CInt = C->getAPIntValue(); 7373 // Element types smaller than 32 bits are not legal, so use i32 elements. 7374 // The values are implicitly truncated so sext vs. zext doesn't matter. 7375 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 7376 } 7377 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 7378 } 7379 7380 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 7381 unsigned Opcode = N->getOpcode(); 7382 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7383 SDNode *N0 = N->getOperand(0).getNode(); 7384 SDNode *N1 = N->getOperand(1).getNode(); 7385 return N0->hasOneUse() && N1->hasOneUse() && 7386 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 7387 } 7388 return false; 7389 } 7390 7391 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 7392 unsigned Opcode = N->getOpcode(); 7393 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 7394 SDNode *N0 = N->getOperand(0).getNode(); 7395 SDNode *N1 = N->getOperand(1).getNode(); 7396 return N0->hasOneUse() && N1->hasOneUse() && 7397 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 7398 } 7399 return false; 7400 } 7401 7402 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 7403 // Multiplications are only custom-lowered for 128-bit vectors so that 7404 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 7405 EVT VT = Op.getValueType(); 7406 assert(VT.is128BitVector() && VT.isInteger() && 7407 "unexpected type for custom-lowering ISD::MUL"); 7408 SDNode *N0 = Op.getOperand(0).getNode(); 7409 SDNode *N1 = Op.getOperand(1).getNode(); 7410 unsigned NewOpc = 0; 7411 bool isMLA = false; 7412 bool isN0SExt = isSignExtended(N0, DAG); 7413 bool isN1SExt = isSignExtended(N1, DAG); 7414 if (isN0SExt && isN1SExt) 7415 NewOpc = ARMISD::VMULLs; 7416 else { 7417 bool isN0ZExt = isZeroExtended(N0, DAG); 7418 bool isN1ZExt = isZeroExtended(N1, DAG); 7419 if (isN0ZExt && isN1ZExt) 7420 NewOpc = ARMISD::VMULLu; 7421 else if (isN1SExt || isN1ZExt) { 7422 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 7423 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 7424 if (isN1SExt && isAddSubSExt(N0, DAG)) { 7425 NewOpc = ARMISD::VMULLs; 7426 isMLA = true; 7427 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 7428 NewOpc = ARMISD::VMULLu; 7429 isMLA = true; 7430 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 7431 std::swap(N0, N1); 7432 NewOpc = ARMISD::VMULLu; 7433 isMLA = true; 7434 } 7435 } 7436 7437 if (!NewOpc) { 7438 if (VT == MVT::v2i64) 7439 // Fall through to expand this. It is not legal. 7440 return SDValue(); 7441 else 7442 // Other vector multiplications are legal. 7443 return Op; 7444 } 7445 } 7446 7447 // Legalize to a VMULL instruction. 7448 SDLoc DL(Op); 7449 SDValue Op0; 7450 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 7451 if (!isMLA) { 7452 Op0 = SkipExtensionForVMULL(N0, DAG); 7453 assert(Op0.getValueType().is64BitVector() && 7454 Op1.getValueType().is64BitVector() && 7455 "unexpected types for extended operands to VMULL"); 7456 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 7457 } 7458 7459 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 7460 // isel lowering to take advantage of no-stall back to back vmul + vmla. 7461 // vmull q0, d4, d6 7462 // vmlal q0, d5, d6 7463 // is faster than 7464 // vaddl q0, d4, d5 7465 // vmovl q1, d6 7466 // vmul q0, q0, q1 7467 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 7468 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 7469 EVT Op1VT = Op1.getValueType(); 7470 return DAG.getNode(N0->getOpcode(), DL, VT, 7471 DAG.getNode(NewOpc, DL, VT, 7472 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 7473 DAG.getNode(NewOpc, DL, VT, 7474 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 7475 } 7476 7477 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl, 7478 SelectionDAG &DAG) { 7479 // TODO: Should this propagate fast-math-flags? 7480 7481 // Convert to float 7482 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 7483 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 7484 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 7485 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 7486 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 7487 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 7488 // Get reciprocal estimate. 7489 // float4 recip = vrecpeq_f32(yf); 7490 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7491 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7492 Y); 7493 // Because char has a smaller range than uchar, we can actually get away 7494 // without any newton steps. This requires that we use a weird bias 7495 // of 0xb000, however (again, this has been exhaustively tested). 7496 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 7497 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 7498 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 7499 Y = DAG.getConstant(0xb000, dl, MVT::v4i32); 7500 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 7501 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 7502 // Convert back to short. 7503 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 7504 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 7505 return X; 7506 } 7507 7508 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl, 7509 SelectionDAG &DAG) { 7510 // TODO: Should this propagate fast-math-flags? 7511 7512 SDValue N2; 7513 // Convert to float. 7514 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 7515 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 7516 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 7517 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 7518 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7519 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7520 7521 // Use reciprocal estimate and one refinement step. 7522 // float4 recip = vrecpeq_f32(yf); 7523 // recip *= vrecpsq_f32(yf, recip); 7524 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7525 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7526 N1); 7527 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7528 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7529 N1, N2); 7530 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7531 // Because short has a smaller range than ushort, we can actually get away 7532 // with only a single newton step. This requires that we use a weird bias 7533 // of 89, however (again, this has been exhaustively tested). 7534 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 7535 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7536 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7537 N1 = DAG.getConstant(0x89, dl, MVT::v4i32); 7538 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7539 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7540 // Convert back to integer and return. 7541 // return vmovn_s32(vcvt_s32_f32(result)); 7542 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7543 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7544 return N0; 7545 } 7546 7547 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 7548 EVT VT = Op.getValueType(); 7549 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7550 "unexpected type for custom-lowering ISD::SDIV"); 7551 7552 SDLoc dl(Op); 7553 SDValue N0 = Op.getOperand(0); 7554 SDValue N1 = Op.getOperand(1); 7555 SDValue N2, N3; 7556 7557 if (VT == MVT::v8i8) { 7558 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 7559 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 7560 7561 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7562 DAG.getIntPtrConstant(4, dl)); 7563 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7564 DAG.getIntPtrConstant(4, dl)); 7565 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7566 DAG.getIntPtrConstant(0, dl)); 7567 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7568 DAG.getIntPtrConstant(0, dl)); 7569 7570 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 7571 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 7572 7573 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7574 N0 = LowerCONCAT_VECTORS(N0, DAG); 7575 7576 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 7577 return N0; 7578 } 7579 return LowerSDIV_v4i16(N0, N1, dl, DAG); 7580 } 7581 7582 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 7583 // TODO: Should this propagate fast-math-flags? 7584 EVT VT = Op.getValueType(); 7585 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 7586 "unexpected type for custom-lowering ISD::UDIV"); 7587 7588 SDLoc dl(Op); 7589 SDValue N0 = Op.getOperand(0); 7590 SDValue N1 = Op.getOperand(1); 7591 SDValue N2, N3; 7592 7593 if (VT == MVT::v8i8) { 7594 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 7595 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 7596 7597 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7598 DAG.getIntPtrConstant(4, dl)); 7599 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7600 DAG.getIntPtrConstant(4, dl)); 7601 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 7602 DAG.getIntPtrConstant(0, dl)); 7603 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 7604 DAG.getIntPtrConstant(0, dl)); 7605 7606 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 7607 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 7608 7609 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 7610 N0 = LowerCONCAT_VECTORS(N0, DAG); 7611 7612 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 7613 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl, 7614 MVT::i32), 7615 N0); 7616 return N0; 7617 } 7618 7619 // v4i16 sdiv ... Convert to float. 7620 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 7621 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 7622 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 7623 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 7624 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 7625 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 7626 7627 // Use reciprocal estimate and two refinement steps. 7628 // float4 recip = vrecpeq_f32(yf); 7629 // recip *= vrecpsq_f32(yf, recip); 7630 // recip *= vrecpsq_f32(yf, recip); 7631 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7632 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32), 7633 BN1); 7634 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7635 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7636 BN1, N2); 7637 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7638 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 7639 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32), 7640 BN1, N2); 7641 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 7642 // Simply multiplying by the reciprocal estimate can leave us a few ulps 7643 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 7644 // and that it will never cause us to return an answer too large). 7645 // float4 result = as_float4(as_int4(xf*recip) + 2); 7646 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 7647 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 7648 N1 = DAG.getConstant(2, dl, MVT::v4i32); 7649 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 7650 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 7651 // Convert back to integer and return. 7652 // return vmovn_u32(vcvt_s32_f32(result)); 7653 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 7654 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 7655 return N0; 7656 } 7657 7658 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 7659 EVT VT = Op.getNode()->getValueType(0); 7660 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7661 7662 unsigned Opc; 7663 bool ExtraOp = false; 7664 switch (Op.getOpcode()) { 7665 default: llvm_unreachable("Invalid code"); 7666 case ISD::ADDC: Opc = ARMISD::ADDC; break; 7667 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 7668 case ISD::SUBC: Opc = ARMISD::SUBC; break; 7669 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 7670 } 7671 7672 if (!ExtraOp) 7673 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7674 Op.getOperand(1)); 7675 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 7676 Op.getOperand(1), Op.getOperand(2)); 7677 } 7678 7679 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) { 7680 SDNode *N = Op.getNode(); 7681 EVT VT = N->getValueType(0); 7682 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 7683 7684 SDValue Carry = Op.getOperand(2); 7685 EVT CarryVT = Carry.getValueType(); 7686 7687 SDLoc DL(Op); 7688 7689 APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits()); 7690 7691 SDValue Result; 7692 if (Op.getOpcode() == ISD::ADDCARRY) { 7693 // This converts the boolean value carry into the carry flag. 7694 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7695 7696 // Do the addition proper using the carry flag we wanted. 7697 Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0), 7698 Op.getOperand(1), Carry.getValue(1)); 7699 7700 // Now convert the carry flag into a boolean value. 7701 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7702 } else { 7703 // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we 7704 // have to invert the carry first. 7705 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7706 DAG.getConstant(1, DL, MVT::i32), Carry); 7707 // This converts the boolean value carry into the carry flag. 7708 Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG); 7709 7710 // Do the subtraction proper using the carry flag we wanted. 7711 Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0), 7712 Op.getOperand(1), Carry.getValue(1)); 7713 7714 // Now convert the carry flag into a boolean value. 7715 Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG); 7716 // But the carry returned by ARMISD::SUBE is not a borrow as expected 7717 // by ISD::SUBCARRY, so compute 1 - C. 7718 Carry = DAG.getNode(ISD::SUB, DL, MVT::i32, 7719 DAG.getConstant(1, DL, MVT::i32), Carry); 7720 } 7721 7722 // Return both values. 7723 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry); 7724 } 7725 7726 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 7727 assert(Subtarget->isTargetDarwin()); 7728 7729 // For iOS, we want to call an alternative entry point: __sincos_stret, 7730 // return values are passed via sret. 7731 SDLoc dl(Op); 7732 SDValue Arg = Op.getOperand(0); 7733 EVT ArgVT = Arg.getValueType(); 7734 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 7735 auto PtrVT = getPointerTy(DAG.getDataLayout()); 7736 7737 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7738 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7739 7740 // Pair of floats / doubles used to pass the result. 7741 Type *RetTy = StructType::get(ArgTy, ArgTy); 7742 auto &DL = DAG.getDataLayout(); 7743 7744 ArgListTy Args; 7745 bool ShouldUseSRet = Subtarget->isAPCS_ABI(); 7746 SDValue SRet; 7747 if (ShouldUseSRet) { 7748 // Create stack object for sret. 7749 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy); 7750 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy); 7751 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false); 7752 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL)); 7753 7754 ArgListEntry Entry; 7755 Entry.Node = SRet; 7756 Entry.Ty = RetTy->getPointerTo(); 7757 Entry.IsSExt = false; 7758 Entry.IsZExt = false; 7759 Entry.IsSRet = true; 7760 Args.push_back(Entry); 7761 RetTy = Type::getVoidTy(*DAG.getContext()); 7762 } 7763 7764 ArgListEntry Entry; 7765 Entry.Node = Arg; 7766 Entry.Ty = ArgTy; 7767 Entry.IsSExt = false; 7768 Entry.IsZExt = false; 7769 Args.push_back(Entry); 7770 7771 RTLIB::Libcall LC = 7772 (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; 7773 const char *LibcallName = getLibcallName(LC); 7774 CallingConv::ID CC = getLibcallCallingConv(LC); 7775 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL)); 7776 7777 TargetLowering::CallLoweringInfo CLI(DAG); 7778 CLI.setDebugLoc(dl) 7779 .setChain(DAG.getEntryNode()) 7780 .setCallee(CC, RetTy, Callee, std::move(Args)) 7781 .setDiscardResult(ShouldUseSRet); 7782 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 7783 7784 if (!ShouldUseSRet) 7785 return CallResult.first; 7786 7787 SDValue LoadSin = 7788 DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo()); 7789 7790 // Address of cos field. 7791 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet, 7792 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl)); 7793 SDValue LoadCos = 7794 DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo()); 7795 7796 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 7797 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 7798 LoadSin.getValue(0), LoadCos.getValue(0)); 7799 } 7800 7801 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, 7802 bool Signed, 7803 SDValue &Chain) const { 7804 EVT VT = Op.getValueType(); 7805 assert((VT == MVT::i32 || VT == MVT::i64) && 7806 "unexpected type for custom lowering DIV"); 7807 SDLoc dl(Op); 7808 7809 const auto &DL = DAG.getDataLayout(); 7810 const auto &TLI = DAG.getTargetLoweringInfo(); 7811 7812 const char *Name = nullptr; 7813 if (Signed) 7814 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64"; 7815 else 7816 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64"; 7817 7818 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL)); 7819 7820 ARMTargetLowering::ArgListTy Args; 7821 7822 for (auto AI : {1, 0}) { 7823 ArgListEntry Arg; 7824 Arg.Node = Op.getOperand(AI); 7825 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext()); 7826 Args.push_back(Arg); 7827 } 7828 7829 CallLoweringInfo CLI(DAG); 7830 CLI.setDebugLoc(dl) 7831 .setChain(Chain) 7832 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()), 7833 ES, std::move(Args)); 7834 7835 return LowerCallTo(CLI).first; 7836 } 7837 7838 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, 7839 bool Signed) const { 7840 assert(Op.getValueType() == MVT::i32 && 7841 "unexpected type for custom lowering DIV"); 7842 SDLoc dl(Op); 7843 7844 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, 7845 DAG.getEntryNode(), Op.getOperand(1)); 7846 7847 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7848 } 7849 7850 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) { 7851 SDLoc DL(N); 7852 SDValue Op = N->getOperand(1); 7853 if (N->getValueType(0) == MVT::i32) 7854 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op); 7855 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7856 DAG.getConstant(0, DL, MVT::i32)); 7857 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op, 7858 DAG.getConstant(1, DL, MVT::i32)); 7859 return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, 7860 DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi)); 7861 } 7862 7863 void ARMTargetLowering::ExpandDIV_Windows( 7864 SDValue Op, SelectionDAG &DAG, bool Signed, 7865 SmallVectorImpl<SDValue> &Results) const { 7866 const auto &DL = DAG.getDataLayout(); 7867 const auto &TLI = DAG.getTargetLoweringInfo(); 7868 7869 assert(Op.getValueType() == MVT::i64 && 7870 "unexpected type for custom lowering DIV"); 7871 SDLoc dl(Op); 7872 7873 SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode()); 7874 7875 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK); 7876 7877 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result); 7878 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result, 7879 DAG.getConstant(32, dl, TLI.getPointerTy(DL))); 7880 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper); 7881 7882 Results.push_back(Lower); 7883 Results.push_back(Upper); 7884 } 7885 7886 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 7887 if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering())) 7888 // Acquire/Release load/store is not legal for targets without a dmb or 7889 // equivalent available. 7890 return SDValue(); 7891 7892 // Monotonic load/store is legal for all targets. 7893 return Op; 7894 } 7895 7896 static void ReplaceREADCYCLECOUNTER(SDNode *N, 7897 SmallVectorImpl<SDValue> &Results, 7898 SelectionDAG &DAG, 7899 const ARMSubtarget *Subtarget) { 7900 SDLoc DL(N); 7901 // Under Power Management extensions, the cycle-count is: 7902 // mrc p15, #0, <Rt>, c9, c13, #0 7903 SDValue Ops[] = { N->getOperand(0), // Chain 7904 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32), 7905 DAG.getConstant(15, DL, MVT::i32), 7906 DAG.getConstant(0, DL, MVT::i32), 7907 DAG.getConstant(9, DL, MVT::i32), 7908 DAG.getConstant(13, DL, MVT::i32), 7909 DAG.getConstant(0, DL, MVT::i32) 7910 }; 7911 7912 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 7913 DAG.getVTList(MVT::i32, MVT::Other), Ops); 7914 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32, 7915 DAG.getConstant(0, DL, MVT::i32))); 7916 Results.push_back(Cycles32.getValue(1)); 7917 } 7918 7919 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 7920 SDLoc dl(V.getNode()); 7921 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32); 7922 SDValue VHi = DAG.getAnyExtOrTrunc( 7923 DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)), 7924 dl, MVT::i32); 7925 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7926 if (isBigEndian) 7927 std::swap (VLo, VHi); 7928 SDValue RegClass = 7929 DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32); 7930 SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32); 7931 SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32); 7932 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 7933 return SDValue( 7934 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 7935 } 7936 7937 static void ReplaceCMP_SWAP_64Results(SDNode *N, 7938 SmallVectorImpl<SDValue> & Results, 7939 SelectionDAG &DAG) { 7940 assert(N->getValueType(0) == MVT::i64 && 7941 "AtomicCmpSwap on types less than 64 should be legal"); 7942 SDValue Ops[] = {N->getOperand(1), 7943 createGPRPairNode(DAG, N->getOperand(2)), 7944 createGPRPairNode(DAG, N->getOperand(3)), 7945 N->getOperand(0)}; 7946 SDNode *CmpSwap = DAG.getMachineNode( 7947 ARM::CMP_SWAP_64, SDLoc(N), 7948 DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops); 7949 7950 MachineFunction &MF = DAG.getMachineFunction(); 7951 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 7952 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 7953 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 7954 7955 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 7956 7957 Results.push_back( 7958 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0, 7959 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7960 Results.push_back( 7961 DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1, 7962 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0))); 7963 Results.push_back(SDValue(CmpSwap, 2)); 7964 } 7965 7966 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget, 7967 SelectionDAG &DAG) { 7968 const auto &TLI = DAG.getTargetLoweringInfo(); 7969 7970 assert(Subtarget.getTargetTriple().isOSMSVCRT() && 7971 "Custom lowering is MSVCRT specific!"); 7972 7973 SDLoc dl(Op); 7974 SDValue Val = Op.getOperand(0); 7975 MVT Ty = Val->getSimpleValueType(0); 7976 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1)); 7977 SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow", 7978 TLI.getPointerTy(DAG.getDataLayout())); 7979 7980 TargetLowering::ArgListTy Args; 7981 TargetLowering::ArgListEntry Entry; 7982 7983 Entry.Node = Val; 7984 Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7985 Entry.IsZExt = true; 7986 Args.push_back(Entry); 7987 7988 Entry.Node = Exponent; 7989 Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext()); 7990 Entry.IsZExt = true; 7991 Args.push_back(Entry); 7992 7993 Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext()); 7994 7995 // In the in-chain to the call is the entry node If we are emitting a 7996 // tailcall, the chain will be mutated if the node has a non-entry input 7997 // chain. 7998 SDValue InChain = DAG.getEntryNode(); 7999 SDValue TCChain = InChain; 8000 8001 const Function &F = DAG.getMachineFunction().getFunction(); 8002 bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 8003 F.getReturnType() == LCRTy; 8004 if (IsTC) 8005 InChain = TCChain; 8006 8007 TargetLowering::CallLoweringInfo CLI(DAG); 8008 CLI.setDebugLoc(dl) 8009 .setChain(InChain) 8010 .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args)) 8011 .setTailCall(IsTC); 8012 std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI); 8013 8014 // Return the chain (the DAG root) if it is a tail call 8015 return !CI.second.getNode() ? DAG.getRoot() : CI.first; 8016 } 8017 8018 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8019 DEBUG(dbgs() << "Lowering node: "; Op.dump()); 8020 switch (Op.getOpcode()) { 8021 default: llvm_unreachable("Don't know how to custom lower this!"); 8022 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG); 8023 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 8024 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 8025 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 8026 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 8027 case ISD::SELECT: return LowerSELECT(Op, DAG); 8028 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 8029 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 8030 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 8031 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 8032 case ISD::VASTART: return LowerVASTART(Op, DAG); 8033 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 8034 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 8035 case ISD::SINT_TO_FP: 8036 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 8037 case ISD::FP_TO_SINT: 8038 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 8039 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 8040 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 8041 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 8042 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 8043 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 8044 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 8045 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 8046 Subtarget); 8047 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG, Subtarget); 8048 case ISD::SHL: 8049 case ISD::SRL: 8050 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 8051 case ISD::SREM: return LowerREM(Op.getNode(), DAG); 8052 case ISD::UREM: return LowerREM(Op.getNode(), DAG); 8053 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 8054 case ISD::SRL_PARTS: 8055 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 8056 case ISD::CTTZ: 8057 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 8058 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 8059 case ISD::SETCC: return LowerVSETCC(Op, DAG); 8060 case ISD::SETCCE: return LowerSETCCE(Op, DAG); 8061 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 8062 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 8063 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 8064 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 8065 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 8066 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 8067 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 8068 case ISD::MUL: return LowerMUL(Op, DAG); 8069 case ISD::SDIV: 8070 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8071 return LowerDIV_Windows(Op, DAG, /* Signed */ true); 8072 return LowerSDIV(Op, DAG); 8073 case ISD::UDIV: 8074 if (Subtarget->isTargetWindows() && !Op.getValueType().isVector()) 8075 return LowerDIV_Windows(Op, DAG, /* Signed */ false); 8076 return LowerUDIV(Op, DAG); 8077 case ISD::ADDC: 8078 case ISD::ADDE: 8079 case ISD::SUBC: 8080 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 8081 case ISD::ADDCARRY: 8082 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG); 8083 case ISD::SADDO: 8084 case ISD::SSUBO: 8085 return LowerSignedALUO(Op, DAG); 8086 case ISD::UADDO: 8087 case ISD::USUBO: 8088 return LowerUnsignedALUO(Op, DAG); 8089 case ISD::ATOMIC_LOAD: 8090 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 8091 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 8092 case ISD::SDIVREM: 8093 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 8094 case ISD::DYNAMIC_STACKALLOC: 8095 if (Subtarget->isTargetWindows()) 8096 return LowerDYNAMIC_STACKALLOC(Op, DAG); 8097 llvm_unreachable("Don't know how to custom lower this!"); 8098 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); 8099 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 8100 case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG); 8101 case ARMISD::WIN__DBZCHK: return SDValue(); 8102 } 8103 } 8104 8105 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results, 8106 SelectionDAG &DAG) { 8107 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8108 unsigned Opc = 0; 8109 if (IntNo == Intrinsic::arm_smlald) 8110 Opc = ARMISD::SMLALD; 8111 else if (IntNo == Intrinsic::arm_smlaldx) 8112 Opc = ARMISD::SMLALDX; 8113 else if (IntNo == Intrinsic::arm_smlsld) 8114 Opc = ARMISD::SMLSLD; 8115 else if (IntNo == Intrinsic::arm_smlsldx) 8116 Opc = ARMISD::SMLSLDX; 8117 else 8118 return; 8119 8120 SDLoc dl(N); 8121 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8122 N->getOperand(3), 8123 DAG.getConstant(0, dl, MVT::i32)); 8124 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 8125 N->getOperand(3), 8126 DAG.getConstant(1, dl, MVT::i32)); 8127 8128 SDValue LongMul = DAG.getNode(Opc, dl, 8129 DAG.getVTList(MVT::i32, MVT::i32), 8130 N->getOperand(1), N->getOperand(2), 8131 Lo, Hi); 8132 Results.push_back(LongMul.getValue(0)); 8133 Results.push_back(LongMul.getValue(1)); 8134 } 8135 8136 /// ReplaceNodeResults - Replace the results of node with an illegal result 8137 /// type with new values built out of custom code. 8138 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 8139 SmallVectorImpl<SDValue> &Results, 8140 SelectionDAG &DAG) const { 8141 SDValue Res; 8142 switch (N->getOpcode()) { 8143 default: 8144 llvm_unreachable("Don't know how to custom expand this!"); 8145 case ISD::READ_REGISTER: 8146 ExpandREAD_REGISTER(N, Results, DAG); 8147 break; 8148 case ISD::BITCAST: 8149 Res = ExpandBITCAST(N, DAG, Subtarget); 8150 break; 8151 case ISD::SRL: 8152 case ISD::SRA: 8153 Res = Expand64BitShift(N, DAG, Subtarget); 8154 break; 8155 case ISD::SREM: 8156 case ISD::UREM: 8157 Res = LowerREM(N, DAG); 8158 break; 8159 case ISD::SDIVREM: 8160 case ISD::UDIVREM: 8161 Res = LowerDivRem(SDValue(N, 0), DAG); 8162 assert(Res.getNumOperands() == 2 && "DivRem needs two values"); 8163 Results.push_back(Res.getValue(0)); 8164 Results.push_back(Res.getValue(1)); 8165 return; 8166 case ISD::READCYCLECOUNTER: 8167 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 8168 return; 8169 case ISD::UDIV: 8170 case ISD::SDIV: 8171 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows"); 8172 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV, 8173 Results); 8174 case ISD::ATOMIC_CMP_SWAP: 8175 ReplaceCMP_SWAP_64Results(N, Results, DAG); 8176 return; 8177 case ISD::INTRINSIC_WO_CHAIN: 8178 return ReplaceLongIntrinsic(N, Results, DAG); 8179 } 8180 if (Res.getNode()) 8181 Results.push_back(Res); 8182 } 8183 8184 //===----------------------------------------------------------------------===// 8185 // ARM Scheduler Hooks 8186 //===----------------------------------------------------------------------===// 8187 8188 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 8189 /// registers the function context. 8190 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI, 8191 MachineBasicBlock *MBB, 8192 MachineBasicBlock *DispatchBB, 8193 int FI) const { 8194 assert(!Subtarget->isROPI() && !Subtarget->isRWPI() && 8195 "ROPI/RWPI not currently supported with SjLj"); 8196 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8197 DebugLoc dl = MI.getDebugLoc(); 8198 MachineFunction *MF = MBB->getParent(); 8199 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8200 MachineConstantPool *MCP = MF->getConstantPool(); 8201 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 8202 const Function &F = MF->getFunction(); 8203 8204 bool isThumb = Subtarget->isThumb(); 8205 bool isThumb2 = Subtarget->isThumb2(); 8206 8207 unsigned PCLabelId = AFI->createPICLabelUId(); 8208 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 8209 ARMConstantPoolValue *CPV = 8210 ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj); 8211 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 8212 8213 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass 8214 : &ARM::GPRRegClass; 8215 8216 // Grab constant pool and fixed stack memory operands. 8217 MachineMemOperand *CPMMO = 8218 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF), 8219 MachineMemOperand::MOLoad, 4, 4); 8220 8221 MachineMemOperand *FIMMOSt = 8222 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 8223 MachineMemOperand::MOStore, 4, 4); 8224 8225 // Load the address of the dispatch MBB into the jump buffer. 8226 if (isThumb2) { 8227 // Incoming value: jbuf 8228 // ldr.n r5, LCPI1_1 8229 // orr r5, r5, #1 8230 // add r5, pc 8231 // str r5, [$jbuf, #+4] ; &jbuf[1] 8232 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8233 BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 8234 .addConstantPoolIndex(CPI) 8235 .addMemOperand(CPMMO) 8236 .add(predOps(ARMCC::AL)); 8237 // Set the low bit because of thumb mode. 8238 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8239 BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 8240 .addReg(NewVReg1, RegState::Kill) 8241 .addImm(0x01) 8242 .add(predOps(ARMCC::AL)) 8243 .add(condCodeOp()); 8244 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8245 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 8246 .addReg(NewVReg2, RegState::Kill) 8247 .addImm(PCLabelId); 8248 BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 8249 .addReg(NewVReg3, RegState::Kill) 8250 .addFrameIndex(FI) 8251 .addImm(36) // &jbuf[1] :: pc 8252 .addMemOperand(FIMMOSt) 8253 .add(predOps(ARMCC::AL)); 8254 } else if (isThumb) { 8255 // Incoming value: jbuf 8256 // ldr.n r1, LCPI1_4 8257 // add r1, pc 8258 // mov r2, #1 8259 // orrs r1, r2 8260 // add r2, $jbuf, #+4 ; &jbuf[1] 8261 // str r1, [r2] 8262 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8263 BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 8264 .addConstantPoolIndex(CPI) 8265 .addMemOperand(CPMMO) 8266 .add(predOps(ARMCC::AL)); 8267 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8268 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 8269 .addReg(NewVReg1, RegState::Kill) 8270 .addImm(PCLabelId); 8271 // Set the low bit because of thumb mode. 8272 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8273 BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 8274 .addReg(ARM::CPSR, RegState::Define) 8275 .addImm(1) 8276 .add(predOps(ARMCC::AL)); 8277 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8278 BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 8279 .addReg(ARM::CPSR, RegState::Define) 8280 .addReg(NewVReg2, RegState::Kill) 8281 .addReg(NewVReg3, RegState::Kill) 8282 .add(predOps(ARMCC::AL)); 8283 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8284 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5) 8285 .addFrameIndex(FI) 8286 .addImm(36); // &jbuf[1] :: pc 8287 BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 8288 .addReg(NewVReg4, RegState::Kill) 8289 .addReg(NewVReg5, RegState::Kill) 8290 .addImm(0) 8291 .addMemOperand(FIMMOSt) 8292 .add(predOps(ARMCC::AL)); 8293 } else { 8294 // Incoming value: jbuf 8295 // ldr r1, LCPI1_1 8296 // add r1, pc, r1 8297 // str r1, [$jbuf, #+4] ; &jbuf[1] 8298 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8299 BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 8300 .addConstantPoolIndex(CPI) 8301 .addImm(0) 8302 .addMemOperand(CPMMO) 8303 .add(predOps(ARMCC::AL)); 8304 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8305 BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 8306 .addReg(NewVReg1, RegState::Kill) 8307 .addImm(PCLabelId) 8308 .add(predOps(ARMCC::AL)); 8309 BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 8310 .addReg(NewVReg2, RegState::Kill) 8311 .addFrameIndex(FI) 8312 .addImm(36) // &jbuf[1] :: pc 8313 .addMemOperand(FIMMOSt) 8314 .add(predOps(ARMCC::AL)); 8315 } 8316 } 8317 8318 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI, 8319 MachineBasicBlock *MBB) const { 8320 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8321 DebugLoc dl = MI.getDebugLoc(); 8322 MachineFunction *MF = MBB->getParent(); 8323 MachineRegisterInfo *MRI = &MF->getRegInfo(); 8324 MachineFrameInfo &MFI = MF->getFrameInfo(); 8325 int FI = MFI.getFunctionContextIndex(); 8326 8327 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass 8328 : &ARM::GPRnopcRegClass; 8329 8330 // Get a mapping of the call site numbers to all of the landing pads they're 8331 // associated with. 8332 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad; 8333 unsigned MaxCSNum = 0; 8334 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 8335 ++BB) { 8336 if (!BB->isEHPad()) continue; 8337 8338 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 8339 // pad. 8340 for (MachineBasicBlock::iterator 8341 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 8342 if (!II->isEHLabel()) continue; 8343 8344 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 8345 if (!MF->hasCallSiteLandingPad(Sym)) continue; 8346 8347 SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym); 8348 for (SmallVectorImpl<unsigned>::iterator 8349 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 8350 CSI != CSE; ++CSI) { 8351 CallSiteNumToLPad[*CSI].push_back(&*BB); 8352 MaxCSNum = std::max(MaxCSNum, *CSI); 8353 } 8354 break; 8355 } 8356 } 8357 8358 // Get an ordered list of the machine basic blocks for the jump table. 8359 std::vector<MachineBasicBlock*> LPadList; 8360 SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs; 8361 LPadList.reserve(CallSiteNumToLPad.size()); 8362 for (unsigned I = 1; I <= MaxCSNum; ++I) { 8363 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 8364 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8365 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 8366 LPadList.push_back(*II); 8367 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 8368 } 8369 } 8370 8371 assert(!LPadList.empty() && 8372 "No landing pad destinations for the dispatch jump table!"); 8373 8374 // Create the jump table and associated information. 8375 MachineJumpTableInfo *JTI = 8376 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 8377 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 8378 8379 // Create the MBBs for the dispatch code. 8380 8381 // Shove the dispatch's address into the return slot in the function context. 8382 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 8383 DispatchBB->setIsEHPad(); 8384 8385 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 8386 unsigned trap_opcode; 8387 if (Subtarget->isThumb()) 8388 trap_opcode = ARM::tTRAP; 8389 else 8390 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 8391 8392 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 8393 DispatchBB->addSuccessor(TrapBB); 8394 8395 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 8396 DispatchBB->addSuccessor(DispContBB); 8397 8398 // Insert and MBBs. 8399 MF->insert(MF->end(), DispatchBB); 8400 MF->insert(MF->end(), DispContBB); 8401 MF->insert(MF->end(), TrapBB); 8402 8403 // Insert code into the entry block that creates and registers the function 8404 // context. 8405 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 8406 8407 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand( 8408 MachinePointerInfo::getFixedStack(*MF, FI), 8409 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4); 8410 8411 MachineInstrBuilder MIB; 8412 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 8413 8414 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 8415 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 8416 8417 // Add a register mask with no preserved registers. This results in all 8418 // registers being marked as clobbered. This can't work if the dispatch block 8419 // is in a Thumb1 function and is linked with ARM code which uses the FP 8420 // registers, as there is no way to preserve the FP registers in Thumb1 mode. 8421 MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF)); 8422 8423 bool IsPositionIndependent = isPositionIndependent(); 8424 unsigned NumLPads = LPadList.size(); 8425 if (Subtarget->isThumb2()) { 8426 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8427 BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 8428 .addFrameIndex(FI) 8429 .addImm(4) 8430 .addMemOperand(FIMMOLd) 8431 .add(predOps(ARMCC::AL)); 8432 8433 if (NumLPads < 256) { 8434 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 8435 .addReg(NewVReg1) 8436 .addImm(LPadList.size()) 8437 .add(predOps(ARMCC::AL)); 8438 } else { 8439 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8440 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 8441 .addImm(NumLPads & 0xFFFF) 8442 .add(predOps(ARMCC::AL)); 8443 8444 unsigned VReg2 = VReg1; 8445 if ((NumLPads & 0xFFFF0000) != 0) { 8446 VReg2 = MRI->createVirtualRegister(TRC); 8447 BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 8448 .addReg(VReg1) 8449 .addImm(NumLPads >> 16) 8450 .add(predOps(ARMCC::AL)); 8451 } 8452 8453 BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 8454 .addReg(NewVReg1) 8455 .addReg(VReg2) 8456 .add(predOps(ARMCC::AL)); 8457 } 8458 8459 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 8460 .addMBB(TrapBB) 8461 .addImm(ARMCC::HI) 8462 .addReg(ARM::CPSR); 8463 8464 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8465 BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3) 8466 .addJumpTableIndex(MJTI) 8467 .add(predOps(ARMCC::AL)); 8468 8469 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8470 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 8471 .addReg(NewVReg3, RegState::Kill) 8472 .addReg(NewVReg1) 8473 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8474 .add(predOps(ARMCC::AL)) 8475 .add(condCodeOp()); 8476 8477 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 8478 .addReg(NewVReg4, RegState::Kill) 8479 .addReg(NewVReg1) 8480 .addJumpTableIndex(MJTI); 8481 } else if (Subtarget->isThumb()) { 8482 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8483 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 8484 .addFrameIndex(FI) 8485 .addImm(1) 8486 .addMemOperand(FIMMOLd) 8487 .add(predOps(ARMCC::AL)); 8488 8489 if (NumLPads < 256) { 8490 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 8491 .addReg(NewVReg1) 8492 .addImm(NumLPads) 8493 .add(predOps(ARMCC::AL)); 8494 } else { 8495 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8496 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8497 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8498 8499 // MachineConstantPool wants an explicit alignment. 8500 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8501 if (Align == 0) 8502 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8503 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8504 8505 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8506 BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 8507 .addReg(VReg1, RegState::Define) 8508 .addConstantPoolIndex(Idx) 8509 .add(predOps(ARMCC::AL)); 8510 BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 8511 .addReg(NewVReg1) 8512 .addReg(VReg1) 8513 .add(predOps(ARMCC::AL)); 8514 } 8515 8516 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 8517 .addMBB(TrapBB) 8518 .addImm(ARMCC::HI) 8519 .addReg(ARM::CPSR); 8520 8521 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 8522 BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 8523 .addReg(ARM::CPSR, RegState::Define) 8524 .addReg(NewVReg1) 8525 .addImm(2) 8526 .add(predOps(ARMCC::AL)); 8527 8528 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8529 BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 8530 .addJumpTableIndex(MJTI) 8531 .add(predOps(ARMCC::AL)); 8532 8533 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8534 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 8535 .addReg(ARM::CPSR, RegState::Define) 8536 .addReg(NewVReg2, RegState::Kill) 8537 .addReg(NewVReg3) 8538 .add(predOps(ARMCC::AL)); 8539 8540 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8541 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8542 8543 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8544 BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 8545 .addReg(NewVReg4, RegState::Kill) 8546 .addImm(0) 8547 .addMemOperand(JTMMOLd) 8548 .add(predOps(ARMCC::AL)); 8549 8550 unsigned NewVReg6 = NewVReg5; 8551 if (IsPositionIndependent) { 8552 NewVReg6 = MRI->createVirtualRegister(TRC); 8553 BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 8554 .addReg(ARM::CPSR, RegState::Define) 8555 .addReg(NewVReg5, RegState::Kill) 8556 .addReg(NewVReg3) 8557 .add(predOps(ARMCC::AL)); 8558 } 8559 8560 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 8561 .addReg(NewVReg6, RegState::Kill) 8562 .addJumpTableIndex(MJTI); 8563 } else { 8564 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 8565 BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 8566 .addFrameIndex(FI) 8567 .addImm(4) 8568 .addMemOperand(FIMMOLd) 8569 .add(predOps(ARMCC::AL)); 8570 8571 if (NumLPads < 256) { 8572 BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 8573 .addReg(NewVReg1) 8574 .addImm(NumLPads) 8575 .add(predOps(ARMCC::AL)); 8576 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 8577 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8578 BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 8579 .addImm(NumLPads & 0xFFFF) 8580 .add(predOps(ARMCC::AL)); 8581 8582 unsigned VReg2 = VReg1; 8583 if ((NumLPads & 0xFFFF0000) != 0) { 8584 VReg2 = MRI->createVirtualRegister(TRC); 8585 BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 8586 .addReg(VReg1) 8587 .addImm(NumLPads >> 16) 8588 .add(predOps(ARMCC::AL)); 8589 } 8590 8591 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8592 .addReg(NewVReg1) 8593 .addReg(VReg2) 8594 .add(predOps(ARMCC::AL)); 8595 } else { 8596 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8597 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 8598 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 8599 8600 // MachineConstantPool wants an explicit alignment. 8601 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 8602 if (Align == 0) 8603 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 8604 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 8605 8606 unsigned VReg1 = MRI->createVirtualRegister(TRC); 8607 BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 8608 .addReg(VReg1, RegState::Define) 8609 .addConstantPoolIndex(Idx) 8610 .addImm(0) 8611 .add(predOps(ARMCC::AL)); 8612 BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 8613 .addReg(NewVReg1) 8614 .addReg(VReg1, RegState::Kill) 8615 .add(predOps(ARMCC::AL)); 8616 } 8617 8618 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 8619 .addMBB(TrapBB) 8620 .addImm(ARMCC::HI) 8621 .addReg(ARM::CPSR); 8622 8623 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 8624 BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 8625 .addReg(NewVReg1) 8626 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)) 8627 .add(predOps(ARMCC::AL)) 8628 .add(condCodeOp()); 8629 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 8630 BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 8631 .addJumpTableIndex(MJTI) 8632 .add(predOps(ARMCC::AL)); 8633 8634 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand( 8635 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4); 8636 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 8637 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 8638 .addReg(NewVReg3, RegState::Kill) 8639 .addReg(NewVReg4) 8640 .addImm(0) 8641 .addMemOperand(JTMMOLd) 8642 .add(predOps(ARMCC::AL)); 8643 8644 if (IsPositionIndependent) { 8645 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 8646 .addReg(NewVReg5, RegState::Kill) 8647 .addReg(NewVReg4) 8648 .addJumpTableIndex(MJTI); 8649 } else { 8650 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 8651 .addReg(NewVReg5, RegState::Kill) 8652 .addJumpTableIndex(MJTI); 8653 } 8654 } 8655 8656 // Add the jump table entries as successors to the MBB. 8657 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 8658 for (std::vector<MachineBasicBlock*>::iterator 8659 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 8660 MachineBasicBlock *CurMBB = *I; 8661 if (SeenMBBs.insert(CurMBB).second) 8662 DispContBB->addSuccessor(CurMBB); 8663 } 8664 8665 // N.B. the order the invoke BBs are processed in doesn't matter here. 8666 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 8667 SmallVector<MachineBasicBlock*, 64> MBBLPads; 8668 for (MachineBasicBlock *BB : InvokeBBs) { 8669 8670 // Remove the landing pad successor from the invoke block and replace it 8671 // with the new dispatch block. 8672 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 8673 BB->succ_end()); 8674 while (!Successors.empty()) { 8675 MachineBasicBlock *SMBB = Successors.pop_back_val(); 8676 if (SMBB->isEHPad()) { 8677 BB->removeSuccessor(SMBB); 8678 MBBLPads.push_back(SMBB); 8679 } 8680 } 8681 8682 BB->addSuccessor(DispatchBB, BranchProbability::getZero()); 8683 BB->normalizeSuccProbs(); 8684 8685 // Find the invoke call and mark all of the callee-saved registers as 8686 // 'implicit defined' so that they're spilled. This prevents code from 8687 // moving instructions to before the EH block, where they will never be 8688 // executed. 8689 for (MachineBasicBlock::reverse_iterator 8690 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 8691 if (!II->isCall()) continue; 8692 8693 DenseMap<unsigned, bool> DefRegs; 8694 for (MachineInstr::mop_iterator 8695 OI = II->operands_begin(), OE = II->operands_end(); 8696 OI != OE; ++OI) { 8697 if (!OI->isReg()) continue; 8698 DefRegs[OI->getReg()] = true; 8699 } 8700 8701 MachineInstrBuilder MIB(*MF, &*II); 8702 8703 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 8704 unsigned Reg = SavedRegs[i]; 8705 if (Subtarget->isThumb2() && 8706 !ARM::tGPRRegClass.contains(Reg) && 8707 !ARM::hGPRRegClass.contains(Reg)) 8708 continue; 8709 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 8710 continue; 8711 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 8712 continue; 8713 if (!DefRegs[Reg]) 8714 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 8715 } 8716 8717 break; 8718 } 8719 } 8720 8721 // Mark all former landing pads as non-landing pads. The dispatch is the only 8722 // landing pad now. 8723 for (SmallVectorImpl<MachineBasicBlock*>::iterator 8724 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 8725 (*I)->setIsEHPad(false); 8726 8727 // The instruction is gone now. 8728 MI.eraseFromParent(); 8729 } 8730 8731 static 8732 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 8733 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 8734 E = MBB->succ_end(); I != E; ++I) 8735 if (*I != Succ) 8736 return *I; 8737 llvm_unreachable("Expecting a BB with two successors!"); 8738 } 8739 8740 /// Return the load opcode for a given load size. If load size >= 8, 8741 /// neon opcode will be returned. 8742 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 8743 if (LdSize >= 8) 8744 return LdSize == 16 ? ARM::VLD1q32wb_fixed 8745 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 8746 if (IsThumb1) 8747 return LdSize == 4 ? ARM::tLDRi 8748 : LdSize == 2 ? ARM::tLDRHi 8749 : LdSize == 1 ? ARM::tLDRBi : 0; 8750 if (IsThumb2) 8751 return LdSize == 4 ? ARM::t2LDR_POST 8752 : LdSize == 2 ? ARM::t2LDRH_POST 8753 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 8754 return LdSize == 4 ? ARM::LDR_POST_IMM 8755 : LdSize == 2 ? ARM::LDRH_POST 8756 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 8757 } 8758 8759 /// Return the store opcode for a given store size. If store size >= 8, 8760 /// neon opcode will be returned. 8761 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 8762 if (StSize >= 8) 8763 return StSize == 16 ? ARM::VST1q32wb_fixed 8764 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 8765 if (IsThumb1) 8766 return StSize == 4 ? ARM::tSTRi 8767 : StSize == 2 ? ARM::tSTRHi 8768 : StSize == 1 ? ARM::tSTRBi : 0; 8769 if (IsThumb2) 8770 return StSize == 4 ? ARM::t2STR_POST 8771 : StSize == 2 ? ARM::t2STRH_POST 8772 : StSize == 1 ? ARM::t2STRB_POST : 0; 8773 return StSize == 4 ? ARM::STR_POST_IMM 8774 : StSize == 2 ? ARM::STRH_POST 8775 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 8776 } 8777 8778 /// Emit a post-increment load operation with given size. The instructions 8779 /// will be added to BB at Pos. 8780 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8781 const TargetInstrInfo *TII, const DebugLoc &dl, 8782 unsigned LdSize, unsigned Data, unsigned AddrIn, 8783 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8784 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 8785 assert(LdOpc != 0 && "Should have a load opcode"); 8786 if (LdSize >= 8) { 8787 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8788 .addReg(AddrOut, RegState::Define) 8789 .addReg(AddrIn) 8790 .addImm(0) 8791 .add(predOps(ARMCC::AL)); 8792 } else if (IsThumb1) { 8793 // load + update AddrIn 8794 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8795 .addReg(AddrIn) 8796 .addImm(0) 8797 .add(predOps(ARMCC::AL)); 8798 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut) 8799 .add(t1CondCodeOp()) 8800 .addReg(AddrIn) 8801 .addImm(LdSize) 8802 .add(predOps(ARMCC::AL)); 8803 } else if (IsThumb2) { 8804 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8805 .addReg(AddrOut, RegState::Define) 8806 .addReg(AddrIn) 8807 .addImm(LdSize) 8808 .add(predOps(ARMCC::AL)); 8809 } else { // arm 8810 BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 8811 .addReg(AddrOut, RegState::Define) 8812 .addReg(AddrIn) 8813 .addReg(0) 8814 .addImm(LdSize) 8815 .add(predOps(ARMCC::AL)); 8816 } 8817 } 8818 8819 /// Emit a post-increment store operation with given size. The instructions 8820 /// will be added to BB at Pos. 8821 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos, 8822 const TargetInstrInfo *TII, const DebugLoc &dl, 8823 unsigned StSize, unsigned Data, unsigned AddrIn, 8824 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 8825 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 8826 assert(StOpc != 0 && "Should have a store opcode"); 8827 if (StSize >= 8) { 8828 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8829 .addReg(AddrIn) 8830 .addImm(0) 8831 .addReg(Data) 8832 .add(predOps(ARMCC::AL)); 8833 } else if (IsThumb1) { 8834 // store + update AddrIn 8835 BuildMI(*BB, Pos, dl, TII->get(StOpc)) 8836 .addReg(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(StSize) 8844 .add(predOps(ARMCC::AL)); 8845 } else if (IsThumb2) { 8846 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8847 .addReg(Data) 8848 .addReg(AddrIn) 8849 .addImm(StSize) 8850 .add(predOps(ARMCC::AL)); 8851 } else { // arm 8852 BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 8853 .addReg(Data) 8854 .addReg(AddrIn) 8855 .addReg(0) 8856 .addImm(StSize) 8857 .add(predOps(ARMCC::AL)); 8858 } 8859 } 8860 8861 MachineBasicBlock * 8862 ARMTargetLowering::EmitStructByval(MachineInstr &MI, 8863 MachineBasicBlock *BB) const { 8864 // This pseudo instruction has 3 operands: dst, src, size 8865 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 8866 // Otherwise, we will generate unrolled scalar copies. 8867 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 8868 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 8869 MachineFunction::iterator It = ++BB->getIterator(); 8870 8871 unsigned dest = MI.getOperand(0).getReg(); 8872 unsigned src = MI.getOperand(1).getReg(); 8873 unsigned SizeVal = MI.getOperand(2).getImm(); 8874 unsigned Align = MI.getOperand(3).getImm(); 8875 DebugLoc dl = MI.getDebugLoc(); 8876 8877 MachineFunction *MF = BB->getParent(); 8878 MachineRegisterInfo &MRI = MF->getRegInfo(); 8879 unsigned UnitSize = 0; 8880 const TargetRegisterClass *TRC = nullptr; 8881 const TargetRegisterClass *VecTRC = nullptr; 8882 8883 bool IsThumb1 = Subtarget->isThumb1Only(); 8884 bool IsThumb2 = Subtarget->isThumb2(); 8885 bool IsThumb = Subtarget->isThumb(); 8886 8887 if (Align & 1) { 8888 UnitSize = 1; 8889 } else if (Align & 2) { 8890 UnitSize = 2; 8891 } else { 8892 // Check whether we can use NEON instructions. 8893 if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) && 8894 Subtarget->hasNEON()) { 8895 if ((Align % 16 == 0) && SizeVal >= 16) 8896 UnitSize = 16; 8897 else if ((Align % 8 == 0) && SizeVal >= 8) 8898 UnitSize = 8; 8899 } 8900 // Can't use NEON instructions. 8901 if (UnitSize == 0) 8902 UnitSize = 4; 8903 } 8904 8905 // Select the correct opcode and register class for unit size load/store 8906 bool IsNeon = UnitSize >= 8; 8907 TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass; 8908 if (IsNeon) 8909 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass 8910 : UnitSize == 8 ? &ARM::DPRRegClass 8911 : nullptr; 8912 8913 unsigned BytesLeft = SizeVal % UnitSize; 8914 unsigned LoopSize = SizeVal - BytesLeft; 8915 8916 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 8917 // Use LDR and STR to copy. 8918 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 8919 // [destOut] = STR_POST(scratch, destIn, UnitSize) 8920 unsigned srcIn = src; 8921 unsigned destIn = dest; 8922 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 8923 unsigned srcOut = MRI.createVirtualRegister(TRC); 8924 unsigned destOut = MRI.createVirtualRegister(TRC); 8925 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 8926 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 8927 IsThumb1, IsThumb2); 8928 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 8929 IsThumb1, IsThumb2); 8930 srcIn = srcOut; 8931 destIn = destOut; 8932 } 8933 8934 // Handle the leftover bytes with LDRB and STRB. 8935 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 8936 // [destOut] = STRB_POST(scratch, destIn, 1) 8937 for (unsigned i = 0; i < BytesLeft; i++) { 8938 unsigned srcOut = MRI.createVirtualRegister(TRC); 8939 unsigned destOut = MRI.createVirtualRegister(TRC); 8940 unsigned scratch = MRI.createVirtualRegister(TRC); 8941 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 8942 IsThumb1, IsThumb2); 8943 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 8944 IsThumb1, IsThumb2); 8945 srcIn = srcOut; 8946 destIn = destOut; 8947 } 8948 MI.eraseFromParent(); // The instruction is gone now. 8949 return BB; 8950 } 8951 8952 // Expand the pseudo op to a loop. 8953 // thisMBB: 8954 // ... 8955 // movw varEnd, # --> with thumb2 8956 // movt varEnd, # 8957 // ldrcp varEnd, idx --> without thumb2 8958 // fallthrough --> loopMBB 8959 // loopMBB: 8960 // PHI varPhi, varEnd, varLoop 8961 // PHI srcPhi, src, srcLoop 8962 // PHI destPhi, dst, destLoop 8963 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 8964 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 8965 // subs varLoop, varPhi, #UnitSize 8966 // bne loopMBB 8967 // fallthrough --> exitMBB 8968 // exitMBB: 8969 // epilogue to handle left-over bytes 8970 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 8971 // [destOut] = STRB_POST(scratch, destLoop, 1) 8972 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8973 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 8974 MF->insert(It, loopMBB); 8975 MF->insert(It, exitMBB); 8976 8977 // Transfer the remainder of BB and its successor edges to exitMBB. 8978 exitMBB->splice(exitMBB->begin(), BB, 8979 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 8980 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 8981 8982 // Load an immediate to varEnd. 8983 unsigned varEnd = MRI.createVirtualRegister(TRC); 8984 if (Subtarget->useMovt(*MF)) { 8985 unsigned Vtmp = varEnd; 8986 if ((LoopSize & 0xFFFF0000) != 0) 8987 Vtmp = MRI.createVirtualRegister(TRC); 8988 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp) 8989 .addImm(LoopSize & 0xFFFF) 8990 .add(predOps(ARMCC::AL)); 8991 8992 if ((LoopSize & 0xFFFF0000) != 0) 8993 BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd) 8994 .addReg(Vtmp) 8995 .addImm(LoopSize >> 16) 8996 .add(predOps(ARMCC::AL)); 8997 } else { 8998 MachineConstantPool *ConstantPool = MF->getConstantPool(); 8999 Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext()); 9000 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 9001 9002 // MachineConstantPool wants an explicit alignment. 9003 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty); 9004 if (Align == 0) 9005 Align = MF->getDataLayout().getTypeAllocSize(C->getType()); 9006 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 9007 9008 if (IsThumb) 9009 BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)) 9010 .addReg(varEnd, RegState::Define) 9011 .addConstantPoolIndex(Idx) 9012 .add(predOps(ARMCC::AL)); 9013 else 9014 BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)) 9015 .addReg(varEnd, RegState::Define) 9016 .addConstantPoolIndex(Idx) 9017 .addImm(0) 9018 .add(predOps(ARMCC::AL)); 9019 } 9020 BB->addSuccessor(loopMBB); 9021 9022 // Generate the loop body: 9023 // varPhi = PHI(varLoop, varEnd) 9024 // srcPhi = PHI(srcLoop, src) 9025 // destPhi = PHI(destLoop, dst) 9026 MachineBasicBlock *entryBB = BB; 9027 BB = loopMBB; 9028 unsigned varLoop = MRI.createVirtualRegister(TRC); 9029 unsigned varPhi = MRI.createVirtualRegister(TRC); 9030 unsigned srcLoop = MRI.createVirtualRegister(TRC); 9031 unsigned srcPhi = MRI.createVirtualRegister(TRC); 9032 unsigned destLoop = MRI.createVirtualRegister(TRC); 9033 unsigned destPhi = MRI.createVirtualRegister(TRC); 9034 9035 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 9036 .addReg(varLoop).addMBB(loopMBB) 9037 .addReg(varEnd).addMBB(entryBB); 9038 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 9039 .addReg(srcLoop).addMBB(loopMBB) 9040 .addReg(src).addMBB(entryBB); 9041 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 9042 .addReg(destLoop).addMBB(loopMBB) 9043 .addReg(dest).addMBB(entryBB); 9044 9045 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 9046 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 9047 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 9048 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 9049 IsThumb1, IsThumb2); 9050 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 9051 IsThumb1, IsThumb2); 9052 9053 // Decrement loop variable by UnitSize. 9054 if (IsThumb1) { 9055 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop) 9056 .add(t1CondCodeOp()) 9057 .addReg(varPhi) 9058 .addImm(UnitSize) 9059 .add(predOps(ARMCC::AL)); 9060 } else { 9061 MachineInstrBuilder MIB = 9062 BuildMI(*BB, BB->end(), dl, 9063 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 9064 MIB.addReg(varPhi) 9065 .addImm(UnitSize) 9066 .add(predOps(ARMCC::AL)) 9067 .add(condCodeOp()); 9068 MIB->getOperand(5).setReg(ARM::CPSR); 9069 MIB->getOperand(5).setIsDef(true); 9070 } 9071 BuildMI(*BB, BB->end(), dl, 9072 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9073 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 9074 9075 // loopMBB can loop back to loopMBB or fall through to exitMBB. 9076 BB->addSuccessor(loopMBB); 9077 BB->addSuccessor(exitMBB); 9078 9079 // Add epilogue to handle BytesLeft. 9080 BB = exitMBB; 9081 auto StartOfExit = exitMBB->begin(); 9082 9083 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 9084 // [destOut] = STRB_POST(scratch, destLoop, 1) 9085 unsigned srcIn = srcLoop; 9086 unsigned destIn = destLoop; 9087 for (unsigned i = 0; i < BytesLeft; i++) { 9088 unsigned srcOut = MRI.createVirtualRegister(TRC); 9089 unsigned destOut = MRI.createVirtualRegister(TRC); 9090 unsigned scratch = MRI.createVirtualRegister(TRC); 9091 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 9092 IsThumb1, IsThumb2); 9093 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 9094 IsThumb1, IsThumb2); 9095 srcIn = srcOut; 9096 destIn = destOut; 9097 } 9098 9099 MI.eraseFromParent(); // The instruction is gone now. 9100 return BB; 9101 } 9102 9103 MachineBasicBlock * 9104 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI, 9105 MachineBasicBlock *MBB) const { 9106 const TargetMachine &TM = getTargetMachine(); 9107 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 9108 DebugLoc DL = MI.getDebugLoc(); 9109 9110 assert(Subtarget->isTargetWindows() && 9111 "__chkstk is only supported on Windows"); 9112 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode"); 9113 9114 // __chkstk takes the number of words to allocate on the stack in R4, and 9115 // returns the stack adjustment in number of bytes in R4. This will not 9116 // clober any other registers (other than the obvious lr). 9117 // 9118 // Although, technically, IP should be considered a register which may be 9119 // clobbered, the call itself will not touch it. Windows on ARM is a pure 9120 // thumb-2 environment, so there is no interworking required. As a result, we 9121 // do not expect a veneer to be emitted by the linker, clobbering IP. 9122 // 9123 // Each module receives its own copy of __chkstk, so no import thunk is 9124 // required, again, ensuring that IP is not clobbered. 9125 // 9126 // Finally, although some linkers may theoretically provide a trampoline for 9127 // out of range calls (which is quite common due to a 32M range limitation of 9128 // branches for Thumb), we can generate the long-call version via 9129 // -mcmodel=large, alleviating the need for the trampoline which may clobber 9130 // IP. 9131 9132 switch (TM.getCodeModel()) { 9133 case CodeModel::Small: 9134 case CodeModel::Medium: 9135 case CodeModel::Kernel: 9136 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL)) 9137 .add(predOps(ARMCC::AL)) 9138 .addExternalSymbol("__chkstk") 9139 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9140 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9141 .addReg(ARM::R12, 9142 RegState::Implicit | RegState::Define | RegState::Dead) 9143 .addReg(ARM::CPSR, 9144 RegState::Implicit | RegState::Define | RegState::Dead); 9145 break; 9146 case CodeModel::Large: { 9147 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 9148 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass); 9149 9150 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg) 9151 .addExternalSymbol("__chkstk"); 9152 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr)) 9153 .add(predOps(ARMCC::AL)) 9154 .addReg(Reg, RegState::Kill) 9155 .addReg(ARM::R4, RegState::Implicit | RegState::Kill) 9156 .addReg(ARM::R4, RegState::Implicit | RegState::Define) 9157 .addReg(ARM::R12, 9158 RegState::Implicit | RegState::Define | RegState::Dead) 9159 .addReg(ARM::CPSR, 9160 RegState::Implicit | RegState::Define | RegState::Dead); 9161 break; 9162 } 9163 } 9164 9165 BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP) 9166 .addReg(ARM::SP, RegState::Kill) 9167 .addReg(ARM::R4, RegState::Kill) 9168 .setMIFlags(MachineInstr::FrameSetup) 9169 .add(predOps(ARMCC::AL)) 9170 .add(condCodeOp()); 9171 9172 MI.eraseFromParent(); 9173 return MBB; 9174 } 9175 9176 MachineBasicBlock * 9177 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI, 9178 MachineBasicBlock *MBB) const { 9179 DebugLoc DL = MI.getDebugLoc(); 9180 MachineFunction *MF = MBB->getParent(); 9181 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9182 9183 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock(); 9184 MF->insert(++MBB->getIterator(), ContBB); 9185 ContBB->splice(ContBB->begin(), MBB, 9186 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9187 ContBB->transferSuccessorsAndUpdatePHIs(MBB); 9188 MBB->addSuccessor(ContBB); 9189 9190 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 9191 BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0)); 9192 MF->push_back(TrapBB); 9193 MBB->addSuccessor(TrapBB); 9194 9195 BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8)) 9196 .addReg(MI.getOperand(0).getReg()) 9197 .addImm(0) 9198 .add(predOps(ARMCC::AL)); 9199 BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc)) 9200 .addMBB(TrapBB) 9201 .addImm(ARMCC::EQ) 9202 .addReg(ARM::CPSR); 9203 9204 MI.eraseFromParent(); 9205 return ContBB; 9206 } 9207 9208 MachineBasicBlock * 9209 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9210 MachineBasicBlock *BB) const { 9211 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 9212 DebugLoc dl = MI.getDebugLoc(); 9213 bool isThumb2 = Subtarget->isThumb2(); 9214 switch (MI.getOpcode()) { 9215 default: { 9216 MI.print(errs()); 9217 llvm_unreachable("Unexpected instr type to insert"); 9218 } 9219 9220 // Thumb1 post-indexed loads are really just single-register LDMs. 9221 case ARM::tLDR_postidx: { 9222 MachineOperand Def(MI.getOperand(1)); 9223 if (TargetRegisterInfo::isPhysicalRegister(Def.getReg())) 9224 Def.setIsRenamable(false); 9225 BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD)) 9226 .add(Def) // Rn_wb 9227 .add(MI.getOperand(2)) // Rn 9228 .add(MI.getOperand(3)) // PredImm 9229 .add(MI.getOperand(4)) // PredReg 9230 .add(MI.getOperand(0)); // Rt 9231 MI.eraseFromParent(); 9232 return BB; 9233 } 9234 9235 // The Thumb2 pre-indexed stores have the same MI operands, they just 9236 // define them differently in the .td files from the isel patterns, so 9237 // they need pseudos. 9238 case ARM::t2STR_preidx: 9239 MI.setDesc(TII->get(ARM::t2STR_PRE)); 9240 return BB; 9241 case ARM::t2STRB_preidx: 9242 MI.setDesc(TII->get(ARM::t2STRB_PRE)); 9243 return BB; 9244 case ARM::t2STRH_preidx: 9245 MI.setDesc(TII->get(ARM::t2STRH_PRE)); 9246 return BB; 9247 9248 case ARM::STRi_preidx: 9249 case ARM::STRBi_preidx: { 9250 unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM 9251 : ARM::STRB_PRE_IMM; 9252 // Decode the offset. 9253 unsigned Offset = MI.getOperand(4).getImm(); 9254 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 9255 Offset = ARM_AM::getAM2Offset(Offset); 9256 if (isSub) 9257 Offset = -Offset; 9258 9259 MachineMemOperand *MMO = *MI.memoperands_begin(); 9260 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 9261 .add(MI.getOperand(0)) // Rn_wb 9262 .add(MI.getOperand(1)) // Rt 9263 .add(MI.getOperand(2)) // Rn 9264 .addImm(Offset) // offset (skip GPR==zero_reg) 9265 .add(MI.getOperand(5)) // pred 9266 .add(MI.getOperand(6)) 9267 .addMemOperand(MMO); 9268 MI.eraseFromParent(); 9269 return BB; 9270 } 9271 case ARM::STRr_preidx: 9272 case ARM::STRBr_preidx: 9273 case ARM::STRH_preidx: { 9274 unsigned NewOpc; 9275 switch (MI.getOpcode()) { 9276 default: llvm_unreachable("unexpected opcode!"); 9277 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 9278 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 9279 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 9280 } 9281 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 9282 for (unsigned i = 0; i < MI.getNumOperands(); ++i) 9283 MIB.add(MI.getOperand(i)); 9284 MI.eraseFromParent(); 9285 return BB; 9286 } 9287 9288 case ARM::tMOVCCr_pseudo: { 9289 // To "insert" a SELECT_CC instruction, we actually have to insert the 9290 // diamond control-flow pattern. The incoming instruction knows the 9291 // destination vreg to set, the condition code register to branch on, the 9292 // true/false values to select between, and a branch opcode to use. 9293 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9294 MachineFunction::iterator It = ++BB->getIterator(); 9295 9296 // thisMBB: 9297 // ... 9298 // TrueVal = ... 9299 // cmpTY ccX, r1, r2 9300 // bCC copy1MBB 9301 // fallthrough --> copy0MBB 9302 MachineBasicBlock *thisMBB = BB; 9303 MachineFunction *F = BB->getParent(); 9304 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 9305 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9306 F->insert(It, copy0MBB); 9307 F->insert(It, sinkMBB); 9308 9309 // Transfer the remainder of BB and its successor edges to sinkMBB. 9310 sinkMBB->splice(sinkMBB->begin(), BB, 9311 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9312 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 9313 9314 BB->addSuccessor(copy0MBB); 9315 BB->addSuccessor(sinkMBB); 9316 9317 BuildMI(BB, dl, TII->get(ARM::tBcc)) 9318 .addMBB(sinkMBB) 9319 .addImm(MI.getOperand(3).getImm()) 9320 .addReg(MI.getOperand(4).getReg()); 9321 9322 // copy0MBB: 9323 // %FalseValue = ... 9324 // # fallthrough to sinkMBB 9325 BB = copy0MBB; 9326 9327 // Update machine-CFG edges 9328 BB->addSuccessor(sinkMBB); 9329 9330 // sinkMBB: 9331 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 9332 // ... 9333 BB = sinkMBB; 9334 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg()) 9335 .addReg(MI.getOperand(1).getReg()) 9336 .addMBB(copy0MBB) 9337 .addReg(MI.getOperand(2).getReg()) 9338 .addMBB(thisMBB); 9339 9340 MI.eraseFromParent(); // The pseudo instruction is gone now. 9341 return BB; 9342 } 9343 9344 case ARM::BCCi64: 9345 case ARM::BCCZi64: { 9346 // If there is an unconditional branch to the other successor, remove it. 9347 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9348 9349 // Compare both parts that make up the double comparison separately for 9350 // equality. 9351 bool RHSisZero = MI.getOpcode() == ARM::BCCZi64; 9352 9353 unsigned LHS1 = MI.getOperand(1).getReg(); 9354 unsigned LHS2 = MI.getOperand(2).getReg(); 9355 if (RHSisZero) { 9356 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9357 .addReg(LHS1) 9358 .addImm(0) 9359 .add(predOps(ARMCC::AL)); 9360 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9361 .addReg(LHS2).addImm(0) 9362 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9363 } else { 9364 unsigned RHS1 = MI.getOperand(3).getReg(); 9365 unsigned RHS2 = MI.getOperand(4).getReg(); 9366 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9367 .addReg(LHS1) 9368 .addReg(RHS1) 9369 .add(predOps(ARMCC::AL)); 9370 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 9371 .addReg(LHS2).addReg(RHS2) 9372 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 9373 } 9374 9375 MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB(); 9376 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 9377 if (MI.getOperand(0).getImm() == ARMCC::NE) 9378 std::swap(destMBB, exitMBB); 9379 9380 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 9381 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 9382 if (isThumb2) 9383 BuildMI(BB, dl, TII->get(ARM::t2B)) 9384 .addMBB(exitMBB) 9385 .add(predOps(ARMCC::AL)); 9386 else 9387 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 9388 9389 MI.eraseFromParent(); // The pseudo instruction is gone now. 9390 return BB; 9391 } 9392 9393 case ARM::Int_eh_sjlj_setjmp: 9394 case ARM::Int_eh_sjlj_setjmp_nofp: 9395 case ARM::tInt_eh_sjlj_setjmp: 9396 case ARM::t2Int_eh_sjlj_setjmp: 9397 case ARM::t2Int_eh_sjlj_setjmp_nofp: 9398 return BB; 9399 9400 case ARM::Int_eh_sjlj_setup_dispatch: 9401 EmitSjLjDispatchBlock(MI, BB); 9402 return BB; 9403 9404 case ARM::ABS: 9405 case ARM::t2ABS: { 9406 // To insert an ABS instruction, we have to insert the 9407 // diamond control-flow pattern. The incoming instruction knows the 9408 // source vreg to test against 0, the destination vreg to set, 9409 // the condition code register to branch on, the 9410 // true/false values to select between, and a branch opcode to use. 9411 // It transforms 9412 // V1 = ABS V0 9413 // into 9414 // V2 = MOVS V0 9415 // BCC (branch to SinkBB if V0 >= 0) 9416 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 9417 // SinkBB: V1 = PHI(V2, V3) 9418 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9419 MachineFunction::iterator BBI = ++BB->getIterator(); 9420 MachineFunction *Fn = BB->getParent(); 9421 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9422 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 9423 Fn->insert(BBI, RSBBB); 9424 Fn->insert(BBI, SinkBB); 9425 9426 unsigned int ABSSrcReg = MI.getOperand(1).getReg(); 9427 unsigned int ABSDstReg = MI.getOperand(0).getReg(); 9428 bool ABSSrcKIll = MI.getOperand(1).isKill(); 9429 bool isThumb2 = Subtarget->isThumb2(); 9430 MachineRegisterInfo &MRI = Fn->getRegInfo(); 9431 // In Thumb mode S must not be specified if source register is the SP or 9432 // PC and if destination register is the SP, so restrict register class 9433 unsigned NewRsbDstReg = 9434 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass); 9435 9436 // Transfer the remainder of BB and its successor edges to sinkMBB. 9437 SinkBB->splice(SinkBB->begin(), BB, 9438 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9439 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 9440 9441 BB->addSuccessor(RSBBB); 9442 BB->addSuccessor(SinkBB); 9443 9444 // fall through to SinkMBB 9445 RSBBB->addSuccessor(SinkBB); 9446 9447 // insert a cmp at the end of BB 9448 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 9449 .addReg(ABSSrcReg) 9450 .addImm(0) 9451 .add(predOps(ARMCC::AL)); 9452 9453 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 9454 BuildMI(BB, dl, 9455 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 9456 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 9457 9458 // insert rsbri in RSBBB 9459 // Note: BCC and rsbri will be converted into predicated rsbmi 9460 // by if-conversion pass 9461 BuildMI(*RSBBB, RSBBB->begin(), dl, 9462 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 9463 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0) 9464 .addImm(0) 9465 .add(predOps(ARMCC::AL)) 9466 .add(condCodeOp()); 9467 9468 // insert PHI in SinkBB, 9469 // reuse ABSDstReg to not change uses of ABS instruction 9470 BuildMI(*SinkBB, SinkBB->begin(), dl, 9471 TII->get(ARM::PHI), ABSDstReg) 9472 .addReg(NewRsbDstReg).addMBB(RSBBB) 9473 .addReg(ABSSrcReg).addMBB(BB); 9474 9475 // remove ABS instruction 9476 MI.eraseFromParent(); 9477 9478 // return last added BB 9479 return SinkBB; 9480 } 9481 case ARM::COPY_STRUCT_BYVAL_I32: 9482 ++NumLoopByVals; 9483 return EmitStructByval(MI, BB); 9484 case ARM::WIN__CHKSTK: 9485 return EmitLowered__chkstk(MI, BB); 9486 case ARM::WIN__DBZCHK: 9487 return EmitLowered__dbzchk(MI, BB); 9488 } 9489 } 9490 9491 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers 9492 /// when it is expanded into LDM/STM. This is done as a post-isel lowering 9493 /// instead of as a custom inserter because we need the use list from the SDNode. 9494 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget, 9495 MachineInstr &MI, const SDNode *Node) { 9496 bool isThumb1 = Subtarget->isThumb1Only(); 9497 9498 DebugLoc DL = MI.getDebugLoc(); 9499 MachineFunction *MF = MI.getParent()->getParent(); 9500 MachineRegisterInfo &MRI = MF->getRegInfo(); 9501 MachineInstrBuilder MIB(*MF, MI); 9502 9503 // If the new dst/src is unused mark it as dead. 9504 if (!Node->hasAnyUseOfValue(0)) { 9505 MI.getOperand(0).setIsDead(true); 9506 } 9507 if (!Node->hasAnyUseOfValue(1)) { 9508 MI.getOperand(1).setIsDead(true); 9509 } 9510 9511 // The MEMCPY both defines and kills the scratch registers. 9512 for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) { 9513 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass 9514 : &ARM::GPRRegClass); 9515 MIB.addReg(TmpReg, RegState::Define|RegState::Dead); 9516 } 9517 } 9518 9519 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9520 SDNode *Node) const { 9521 if (MI.getOpcode() == ARM::MEMCPY) { 9522 attachMEMCPYScratchRegs(Subtarget, MI, Node); 9523 return; 9524 } 9525 9526 const MCInstrDesc *MCID = &MI.getDesc(); 9527 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 9528 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 9529 // operand is still set to noreg. If needed, set the optional operand's 9530 // register to CPSR, and remove the redundant implicit def. 9531 // 9532 // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR). 9533 9534 // Rename pseudo opcodes. 9535 unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode()); 9536 unsigned ccOutIdx; 9537 if (NewOpc) { 9538 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo(); 9539 MCID = &TII->get(NewOpc); 9540 9541 assert(MCID->getNumOperands() == 9542 MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize() 9543 && "converted opcode should be the same except for cc_out" 9544 " (and, on Thumb1, pred)"); 9545 9546 MI.setDesc(*MCID); 9547 9548 // Add the optional cc_out operand 9549 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 9550 9551 // On Thumb1, move all input operands to the end, then add the predicate 9552 if (Subtarget->isThumb1Only()) { 9553 for (unsigned c = MCID->getNumOperands() - 4; c--;) { 9554 MI.addOperand(MI.getOperand(1)); 9555 MI.RemoveOperand(1); 9556 } 9557 9558 // Restore the ties 9559 for (unsigned i = MI.getNumOperands(); i--;) { 9560 const MachineOperand& op = MI.getOperand(i); 9561 if (op.isReg() && op.isUse()) { 9562 int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO); 9563 if (DefIdx != -1) 9564 MI.tieOperands(DefIdx, i); 9565 } 9566 } 9567 9568 MI.addOperand(MachineOperand::CreateImm(ARMCC::AL)); 9569 MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false)); 9570 ccOutIdx = 1; 9571 } else 9572 ccOutIdx = MCID->getNumOperands() - 1; 9573 } else 9574 ccOutIdx = MCID->getNumOperands() - 1; 9575 9576 // Any ARM instruction that sets the 's' bit should specify an optional 9577 // "cc_out" operand in the last operand position. 9578 if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 9579 assert(!NewOpc && "Optional cc_out operand required"); 9580 return; 9581 } 9582 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 9583 // since we already have an optional CPSR def. 9584 bool definesCPSR = false; 9585 bool deadCPSR = false; 9586 for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e; 9587 ++i) { 9588 const MachineOperand &MO = MI.getOperand(i); 9589 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 9590 definesCPSR = true; 9591 if (MO.isDead()) 9592 deadCPSR = true; 9593 MI.RemoveOperand(i); 9594 break; 9595 } 9596 } 9597 if (!definesCPSR) { 9598 assert(!NewOpc && "Optional cc_out operand required"); 9599 return; 9600 } 9601 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 9602 if (deadCPSR) { 9603 assert(!MI.getOperand(ccOutIdx).getReg() && 9604 "expect uninitialized optional cc_out operand"); 9605 // Thumb1 instructions must have the S bit even if the CPSR is dead. 9606 if (!Subtarget->isThumb1Only()) 9607 return; 9608 } 9609 9610 // If this instruction was defined with an optional CPSR def and its dag node 9611 // had a live implicit CPSR def, then activate the optional CPSR def. 9612 MachineOperand &MO = MI.getOperand(ccOutIdx); 9613 MO.setReg(ARM::CPSR); 9614 MO.setIsDef(true); 9615 } 9616 9617 //===----------------------------------------------------------------------===// 9618 // ARM Optimization Hooks 9619 //===----------------------------------------------------------------------===// 9620 9621 // Helper function that checks if N is a null or all ones constant. 9622 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 9623 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 9624 } 9625 9626 // Return true if N is conditionally 0 or all ones. 9627 // Detects these expressions where cc is an i1 value: 9628 // 9629 // (select cc 0, y) [AllOnes=0] 9630 // (select cc y, 0) [AllOnes=0] 9631 // (zext cc) [AllOnes=0] 9632 // (sext cc) [AllOnes=0/1] 9633 // (select cc -1, y) [AllOnes=1] 9634 // (select cc y, -1) [AllOnes=1] 9635 // 9636 // Invert is set when N is the null/all ones constant when CC is false. 9637 // OtherOp is set to the alternative value of N. 9638 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 9639 SDValue &CC, bool &Invert, 9640 SDValue &OtherOp, 9641 SelectionDAG &DAG) { 9642 switch (N->getOpcode()) { 9643 default: return false; 9644 case ISD::SELECT: { 9645 CC = N->getOperand(0); 9646 SDValue N1 = N->getOperand(1); 9647 SDValue N2 = N->getOperand(2); 9648 if (isZeroOrAllOnes(N1, AllOnes)) { 9649 Invert = false; 9650 OtherOp = N2; 9651 return true; 9652 } 9653 if (isZeroOrAllOnes(N2, AllOnes)) { 9654 Invert = true; 9655 OtherOp = N1; 9656 return true; 9657 } 9658 return false; 9659 } 9660 case ISD::ZERO_EXTEND: 9661 // (zext cc) can never be the all ones value. 9662 if (AllOnes) 9663 return false; 9664 LLVM_FALLTHROUGH; 9665 case ISD::SIGN_EXTEND: { 9666 SDLoc dl(N); 9667 EVT VT = N->getValueType(0); 9668 CC = N->getOperand(0); 9669 if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC) 9670 return false; 9671 Invert = !AllOnes; 9672 if (AllOnes) 9673 // When looking for an AllOnes constant, N is an sext, and the 'other' 9674 // value is 0. 9675 OtherOp = DAG.getConstant(0, dl, VT); 9676 else if (N->getOpcode() == ISD::ZERO_EXTEND) 9677 // When looking for a 0 constant, N can be zext or sext. 9678 OtherOp = DAG.getConstant(1, dl, VT); 9679 else 9680 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 9681 VT); 9682 return true; 9683 } 9684 } 9685 } 9686 9687 // Combine a constant select operand into its use: 9688 // 9689 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 9690 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 9691 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 9692 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 9693 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 9694 // 9695 // The transform is rejected if the select doesn't have a constant operand that 9696 // is null, or all ones when AllOnes is set. 9697 // 9698 // Also recognize sext/zext from i1: 9699 // 9700 // (add (zext cc), x) -> (select cc (add x, 1), x) 9701 // (add (sext cc), x) -> (select cc (add x, -1), x) 9702 // 9703 // These transformations eventually create predicated instructions. 9704 // 9705 // @param N The node to transform. 9706 // @param Slct The N operand that is a select. 9707 // @param OtherOp The other N operand (x above). 9708 // @param DCI Context. 9709 // @param AllOnes Require the select constant to be all ones instead of null. 9710 // @returns The new node, or SDValue() on failure. 9711 static 9712 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 9713 TargetLowering::DAGCombinerInfo &DCI, 9714 bool AllOnes = false) { 9715 SelectionDAG &DAG = DCI.DAG; 9716 EVT VT = N->getValueType(0); 9717 SDValue NonConstantVal; 9718 SDValue CCOp; 9719 bool SwapSelectOps; 9720 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 9721 NonConstantVal, DAG)) 9722 return SDValue(); 9723 9724 // Slct is now know to be the desired identity constant when CC is true. 9725 SDValue TrueVal = OtherOp; 9726 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 9727 OtherOp, NonConstantVal); 9728 // Unless SwapSelectOps says CC should be false. 9729 if (SwapSelectOps) 9730 std::swap(TrueVal, FalseVal); 9731 9732 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 9733 CCOp, TrueVal, FalseVal); 9734 } 9735 9736 // Attempt combineSelectAndUse on each operand of a commutative operator N. 9737 static 9738 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 9739 TargetLowering::DAGCombinerInfo &DCI) { 9740 SDValue N0 = N->getOperand(0); 9741 SDValue N1 = N->getOperand(1); 9742 if (N0.getNode()->hasOneUse()) 9743 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes)) 9744 return Result; 9745 if (N1.getNode()->hasOneUse()) 9746 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes)) 9747 return Result; 9748 return SDValue(); 9749 } 9750 9751 static bool IsVUZPShuffleNode(SDNode *N) { 9752 // VUZP shuffle node. 9753 if (N->getOpcode() == ARMISD::VUZP) 9754 return true; 9755 9756 // "VUZP" on i32 is an alias for VTRN. 9757 if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32) 9758 return true; 9759 9760 return false; 9761 } 9762 9763 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1, 9764 TargetLowering::DAGCombinerInfo &DCI, 9765 const ARMSubtarget *Subtarget) { 9766 // Look for ADD(VUZP.0, VUZP.1). 9767 if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() || 9768 N0 == N1) 9769 return SDValue(); 9770 9771 // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD. 9772 if (!N->getValueType(0).is64BitVector()) 9773 return SDValue(); 9774 9775 // Generate vpadd. 9776 SelectionDAG &DAG = DCI.DAG; 9777 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9778 SDLoc dl(N); 9779 SDNode *Unzip = N0.getNode(); 9780 EVT VT = N->getValueType(0); 9781 9782 SmallVector<SDValue, 8> Ops; 9783 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl, 9784 TLI.getPointerTy(DAG.getDataLayout()))); 9785 Ops.push_back(Unzip->getOperand(0)); 9786 Ops.push_back(Unzip->getOperand(1)); 9787 9788 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9789 } 9790 9791 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9792 TargetLowering::DAGCombinerInfo &DCI, 9793 const ARMSubtarget *Subtarget) { 9794 // Check for two extended operands. 9795 if (!(N0.getOpcode() == ISD::SIGN_EXTEND && 9796 N1.getOpcode() == ISD::SIGN_EXTEND) && 9797 !(N0.getOpcode() == ISD::ZERO_EXTEND && 9798 N1.getOpcode() == ISD::ZERO_EXTEND)) 9799 return SDValue(); 9800 9801 SDValue N00 = N0.getOperand(0); 9802 SDValue N10 = N1.getOperand(0); 9803 9804 // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1)) 9805 if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() || 9806 N00 == N10) 9807 return SDValue(); 9808 9809 // We only recognize Q register paddl here; this can't be reached until 9810 // after type legalization. 9811 if (!N00.getValueType().is64BitVector() || 9812 !N0.getValueType().is128BitVector()) 9813 return SDValue(); 9814 9815 // Generate vpaddl. 9816 SelectionDAG &DAG = DCI.DAG; 9817 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9818 SDLoc dl(N); 9819 EVT VT = N->getValueType(0); 9820 9821 SmallVector<SDValue, 8> Ops; 9822 // Form vpaddl.sN or vpaddl.uN depending on the kind of extension. 9823 unsigned Opcode; 9824 if (N0.getOpcode() == ISD::SIGN_EXTEND) 9825 Opcode = Intrinsic::arm_neon_vpaddls; 9826 else 9827 Opcode = Intrinsic::arm_neon_vpaddlu; 9828 Ops.push_back(DAG.getConstant(Opcode, dl, 9829 TLI.getPointerTy(DAG.getDataLayout()))); 9830 EVT ElemTy = N00.getValueType().getVectorElementType(); 9831 unsigned NumElts = VT.getVectorNumElements(); 9832 EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2); 9833 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT, 9834 N00.getOperand(0), N00.getOperand(1)); 9835 Ops.push_back(Concat); 9836 9837 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops); 9838 } 9839 9840 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in 9841 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is 9842 // much easier to match. 9843 static SDValue 9844 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1, 9845 TargetLowering::DAGCombinerInfo &DCI, 9846 const ARMSubtarget *Subtarget) { 9847 // Only perform optimization if after legalize, and if NEON is available. We 9848 // also expected both operands to be BUILD_VECTORs. 9849 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 9850 || N0.getOpcode() != ISD::BUILD_VECTOR 9851 || N1.getOpcode() != ISD::BUILD_VECTOR) 9852 return SDValue(); 9853 9854 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 9855 EVT VT = N->getValueType(0); 9856 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 9857 return SDValue(); 9858 9859 // Check that the vector operands are of the right form. 9860 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 9861 // operands, where N is the size of the formed vector. 9862 // Each EXTRACT_VECTOR should have the same input vector and odd or even 9863 // index such that we have a pair wise add pattern. 9864 9865 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 9866 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9867 return SDValue(); 9868 SDValue Vec = N0->getOperand(0)->getOperand(0); 9869 SDNode *V = Vec.getNode(); 9870 unsigned nextIndex = 0; 9871 9872 // For each operands to the ADD which are BUILD_VECTORs, 9873 // check to see if each of their operands are an EXTRACT_VECTOR with 9874 // the same vector and appropriate index. 9875 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 9876 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 9877 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9878 9879 SDValue ExtVec0 = N0->getOperand(i); 9880 SDValue ExtVec1 = N1->getOperand(i); 9881 9882 // First operand is the vector, verify its the same. 9883 if (V != ExtVec0->getOperand(0).getNode() || 9884 V != ExtVec1->getOperand(0).getNode()) 9885 return SDValue(); 9886 9887 // Second is the constant, verify its correct. 9888 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 9889 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 9890 9891 // For the constant, we want to see all the even or all the odd. 9892 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 9893 || C1->getZExtValue() != nextIndex+1) 9894 return SDValue(); 9895 9896 // Increment index. 9897 nextIndex+=2; 9898 } else 9899 return SDValue(); 9900 } 9901 9902 // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure 9903 // we're using the entire input vector, otherwise there's a size/legality 9904 // mismatch somewhere. 9905 if (nextIndex != Vec.getValueType().getVectorNumElements() || 9906 Vec.getValueType().getVectorElementType() == VT.getVectorElementType()) 9907 return SDValue(); 9908 9909 // Create VPADDL node. 9910 SelectionDAG &DAG = DCI.DAG; 9911 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9912 9913 SDLoc dl(N); 9914 9915 // Build operand list. 9916 SmallVector<SDValue, 8> Ops; 9917 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl, 9918 TLI.getPointerTy(DAG.getDataLayout()))); 9919 9920 // Input is the vector. 9921 Ops.push_back(Vec); 9922 9923 // Get widened type and narrowed type. 9924 MVT widenType; 9925 unsigned numElem = VT.getVectorNumElements(); 9926 9927 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 9928 switch (inputLaneType.getSimpleVT().SimpleTy) { 9929 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 9930 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 9931 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 9932 default: 9933 llvm_unreachable("Invalid vector element type for padd optimization."); 9934 } 9935 9936 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops); 9937 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 9938 return DAG.getNode(ExtOp, dl, VT, tmp); 9939 } 9940 9941 static SDValue findMUL_LOHI(SDValue V) { 9942 if (V->getOpcode() == ISD::UMUL_LOHI || 9943 V->getOpcode() == ISD::SMUL_LOHI) 9944 return V; 9945 return SDValue(); 9946 } 9947 9948 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode, 9949 TargetLowering::DAGCombinerInfo &DCI, 9950 const ARMSubtarget *Subtarget) { 9951 if (Subtarget->isThumb()) { 9952 if (!Subtarget->hasDSP()) 9953 return SDValue(); 9954 } else if (!Subtarget->hasV5TEOps()) 9955 return SDValue(); 9956 9957 // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and 9958 // accumulates the product into a 64-bit value. The 16-bit values will 9959 // be sign extended somehow or SRA'd into 32-bit values 9960 // (addc (adde (mul 16bit, 16bit), lo), hi) 9961 SDValue Mul = AddcNode->getOperand(0); 9962 SDValue Lo = AddcNode->getOperand(1); 9963 if (Mul.getOpcode() != ISD::MUL) { 9964 Lo = AddcNode->getOperand(0); 9965 Mul = AddcNode->getOperand(1); 9966 if (Mul.getOpcode() != ISD::MUL) 9967 return SDValue(); 9968 } 9969 9970 SDValue SRA = AddeNode->getOperand(0); 9971 SDValue Hi = AddeNode->getOperand(1); 9972 if (SRA.getOpcode() != ISD::SRA) { 9973 SRA = AddeNode->getOperand(1); 9974 Hi = AddeNode->getOperand(0); 9975 if (SRA.getOpcode() != ISD::SRA) 9976 return SDValue(); 9977 } 9978 if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) { 9979 if (Const->getZExtValue() != 31) 9980 return SDValue(); 9981 } else 9982 return SDValue(); 9983 9984 if (SRA.getOperand(0) != Mul) 9985 return SDValue(); 9986 9987 SelectionDAG &DAG = DCI.DAG; 9988 SDLoc dl(AddcNode); 9989 unsigned Opcode = 0; 9990 SDValue Op0; 9991 SDValue Op1; 9992 9993 if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) { 9994 Opcode = ARMISD::SMLALBB; 9995 Op0 = Mul.getOperand(0); 9996 Op1 = Mul.getOperand(1); 9997 } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) { 9998 Opcode = ARMISD::SMLALBT; 9999 Op0 = Mul.getOperand(0); 10000 Op1 = Mul.getOperand(1).getOperand(0); 10001 } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) { 10002 Opcode = ARMISD::SMLALTB; 10003 Op0 = Mul.getOperand(0).getOperand(0); 10004 Op1 = Mul.getOperand(1); 10005 } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) { 10006 Opcode = ARMISD::SMLALTT; 10007 Op0 = Mul->getOperand(0).getOperand(0); 10008 Op1 = Mul->getOperand(1).getOperand(0); 10009 } 10010 10011 if (!Op0 || !Op1) 10012 return SDValue(); 10013 10014 SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 10015 Op0, Op1, Lo, Hi); 10016 // Replace the ADDs' nodes uses by the MLA node's values. 10017 SDValue HiMLALResult(SMLAL.getNode(), 1); 10018 SDValue LoMLALResult(SMLAL.getNode(), 0); 10019 10020 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 10021 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 10022 10023 // Return original node to notify the driver to stop replacing. 10024 SDValue resNode(AddcNode, 0); 10025 return resNode; 10026 } 10027 10028 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode, 10029 TargetLowering::DAGCombinerInfo &DCI, 10030 const ARMSubtarget *Subtarget) { 10031 // Look for multiply add opportunities. 10032 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 10033 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 10034 // a glue link from the first add to the second add. 10035 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 10036 // a S/UMLAL instruction. 10037 // UMUL_LOHI 10038 // / :lo \ :hi 10039 // V \ [no multiline comment] 10040 // loAdd -> ADDC | 10041 // \ :carry / 10042 // V V 10043 // ADDE <- hiAdd 10044 // 10045 // In the special case where only the higher part of a signed result is used 10046 // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts 10047 // a constant with the exact value of 0x80000000, we recognize we are dealing 10048 // with a "rounded multiply and add" (or subtract) and transform it into 10049 // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively. 10050 10051 assert((AddeSubeNode->getOpcode() == ARMISD::ADDE || 10052 AddeSubeNode->getOpcode() == ARMISD::SUBE) && 10053 "Expect an ADDE or SUBE"); 10054 10055 assert(AddeSubeNode->getNumOperands() == 3 && 10056 AddeSubeNode->getOperand(2).getValueType() == MVT::i32 && 10057 "ADDE node has the wrong inputs"); 10058 10059 // Check that we are chained to the right ADDC or SUBC node. 10060 SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode(); 10061 if ((AddeSubeNode->getOpcode() == ARMISD::ADDE && 10062 AddcSubcNode->getOpcode() != ARMISD::ADDC) || 10063 (AddeSubeNode->getOpcode() == ARMISD::SUBE && 10064 AddcSubcNode->getOpcode() != ARMISD::SUBC)) 10065 return SDValue(); 10066 10067 SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0); 10068 SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1); 10069 10070 // Check if the two operands are from the same mul_lohi node. 10071 if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode()) 10072 return SDValue(); 10073 10074 assert(AddcSubcNode->getNumValues() == 2 && 10075 AddcSubcNode->getValueType(0) == MVT::i32 && 10076 "Expect ADDC with two result values. First: i32"); 10077 10078 // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it 10079 // maybe a SMLAL which multiplies two 16-bit values. 10080 if (AddeSubeNode->getOpcode() == ARMISD::ADDE && 10081 AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI && 10082 AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI && 10083 AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI && 10084 AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI) 10085 return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget); 10086 10087 // Check for the triangle shape. 10088 SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0); 10089 SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1); 10090 10091 // Make sure that the ADDE/SUBE operands are not coming from the same node. 10092 if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode()) 10093 return SDValue(); 10094 10095 // Find the MUL_LOHI node walking up ADDE/SUBE's operands. 10096 bool IsLeftOperandMUL = false; 10097 SDValue MULOp = findMUL_LOHI(AddeSubeOp0); 10098 if (MULOp == SDValue()) 10099 MULOp = findMUL_LOHI(AddeSubeOp1); 10100 else 10101 IsLeftOperandMUL = true; 10102 if (MULOp == SDValue()) 10103 return SDValue(); 10104 10105 // Figure out the right opcode. 10106 unsigned Opc = MULOp->getOpcode(); 10107 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 10108 10109 // Figure out the high and low input values to the MLAL node. 10110 SDValue *HiAddSub = nullptr; 10111 SDValue *LoMul = nullptr; 10112 SDValue *LowAddSub = nullptr; 10113 10114 // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI. 10115 if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1))) 10116 return SDValue(); 10117 10118 if (IsLeftOperandMUL) 10119 HiAddSub = &AddeSubeOp1; 10120 else 10121 HiAddSub = &AddeSubeOp0; 10122 10123 // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node 10124 // whose low result is fed to the ADDC/SUBC we are checking. 10125 10126 if (AddcSubcOp0 == MULOp.getValue(0)) { 10127 LoMul = &AddcSubcOp0; 10128 LowAddSub = &AddcSubcOp1; 10129 } 10130 if (AddcSubcOp1 == MULOp.getValue(0)) { 10131 LoMul = &AddcSubcOp1; 10132 LowAddSub = &AddcSubcOp0; 10133 } 10134 10135 if (!LoMul) 10136 return SDValue(); 10137 10138 // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC 10139 // the replacement below will create a cycle. 10140 if (AddcSubcNode == HiAddSub->getNode() || 10141 AddcSubcNode->isPredecessorOf(HiAddSub->getNode())) 10142 return SDValue(); 10143 10144 // Create the merged node. 10145 SelectionDAG &DAG = DCI.DAG; 10146 10147 // Start building operand list. 10148 SmallVector<SDValue, 8> Ops; 10149 Ops.push_back(LoMul->getOperand(0)); 10150 Ops.push_back(LoMul->getOperand(1)); 10151 10152 // Check whether we can use SMMLAR, SMMLSR or SMMULR instead. For this to be 10153 // the case, we must be doing signed multiplication and only use the higher 10154 // part of the result of the MLAL, furthermore the LowAddSub must be a constant 10155 // addition or subtraction with the value of 0x800000. 10156 if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() && 10157 FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) && 10158 LowAddSub->getNode()->getOpcode() == ISD::Constant && 10159 static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() == 10160 0x80000000) { 10161 Ops.push_back(*HiAddSub); 10162 if (AddcSubcNode->getOpcode() == ARMISD::SUBC) { 10163 FinalOpc = ARMISD::SMMLSR; 10164 } else { 10165 FinalOpc = ARMISD::SMMLAR; 10166 } 10167 SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops); 10168 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode); 10169 10170 return SDValue(AddeSubeNode, 0); 10171 } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC) 10172 // SMMLS is generated during instruction selection and the rest of this 10173 // function can not handle the case where AddcSubcNode is a SUBC. 10174 return SDValue(); 10175 10176 // Finish building the operand list for {U/S}MLAL 10177 Ops.push_back(*LowAddSub); 10178 Ops.push_back(*HiAddSub); 10179 10180 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), 10181 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10182 10183 // Replace the ADDs' nodes uses by the MLA node's values. 10184 SDValue HiMLALResult(MLALNode.getNode(), 1); 10185 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult); 10186 10187 SDValue LoMLALResult(MLALNode.getNode(), 0); 10188 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult); 10189 10190 // Return original node to notify the driver to stop replacing. 10191 return SDValue(AddeSubeNode, 0); 10192 } 10193 10194 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode, 10195 TargetLowering::DAGCombinerInfo &DCI, 10196 const ARMSubtarget *Subtarget) { 10197 // UMAAL is similar to UMLAL except that it adds two unsigned values. 10198 // While trying to combine for the other MLAL nodes, first search for the 10199 // chance to use UMAAL. Check if Addc uses a node which has already 10200 // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde 10201 // as the addend, and it's handled in PerformUMLALCombine. 10202 10203 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10204 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10205 10206 // Check that we have a glued ADDC node. 10207 SDNode* AddcNode = AddeNode->getOperand(2).getNode(); 10208 if (AddcNode->getOpcode() != ARMISD::ADDC) 10209 return SDValue(); 10210 10211 // Find the converted UMAAL or quit if it doesn't exist. 10212 SDNode *UmlalNode = nullptr; 10213 SDValue AddHi; 10214 if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) { 10215 UmlalNode = AddcNode->getOperand(0).getNode(); 10216 AddHi = AddcNode->getOperand(1); 10217 } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) { 10218 UmlalNode = AddcNode->getOperand(1).getNode(); 10219 AddHi = AddcNode->getOperand(0); 10220 } else { 10221 return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget); 10222 } 10223 10224 // The ADDC should be glued to an ADDE node, which uses the same UMLAL as 10225 // the ADDC as well as Zero. 10226 if (!isNullConstant(UmlalNode->getOperand(3))) 10227 return SDValue(); 10228 10229 if ((isNullConstant(AddeNode->getOperand(0)) && 10230 AddeNode->getOperand(1).getNode() == UmlalNode) || 10231 (AddeNode->getOperand(0).getNode() == UmlalNode && 10232 isNullConstant(AddeNode->getOperand(1)))) { 10233 SelectionDAG &DAG = DCI.DAG; 10234 SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1), 10235 UmlalNode->getOperand(2), AddHi }; 10236 SDValue UMAAL = DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode), 10237 DAG.getVTList(MVT::i32, MVT::i32), Ops); 10238 10239 // Replace the ADDs' nodes uses by the UMAAL node's values. 10240 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1)); 10241 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0)); 10242 10243 // Return original node to notify the driver to stop replacing. 10244 return SDValue(AddeNode, 0); 10245 } 10246 return SDValue(); 10247 } 10248 10249 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG, 10250 const ARMSubtarget *Subtarget) { 10251 if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP()) 10252 return SDValue(); 10253 10254 // Check that we have a pair of ADDC and ADDE as operands. 10255 // Both addends of the ADDE must be zero. 10256 SDNode* AddcNode = N->getOperand(2).getNode(); 10257 SDNode* AddeNode = N->getOperand(3).getNode(); 10258 if ((AddcNode->getOpcode() == ARMISD::ADDC) && 10259 (AddeNode->getOpcode() == ARMISD::ADDE) && 10260 isNullConstant(AddeNode->getOperand(0)) && 10261 isNullConstant(AddeNode->getOperand(1)) && 10262 (AddeNode->getOperand(2).getNode() == AddcNode)) 10263 return DAG.getNode(ARMISD::UMAAL, SDLoc(N), 10264 DAG.getVTList(MVT::i32, MVT::i32), 10265 {N->getOperand(0), N->getOperand(1), 10266 AddcNode->getOperand(0), AddcNode->getOperand(1)}); 10267 else 10268 return SDValue(); 10269 } 10270 10271 static SDValue PerformAddcSubcCombine(SDNode *N, 10272 TargetLowering::DAGCombinerInfo &DCI, 10273 const ARMSubtarget *Subtarget) { 10274 SelectionDAG &DAG(DCI.DAG); 10275 10276 if (N->getOpcode() == ARMISD::ADDC) { 10277 // (ADDC (ADDE 0, 0, C), -1) -> C 10278 SDValue LHS = N->getOperand(0); 10279 SDValue RHS = N->getOperand(1); 10280 if (LHS->getOpcode() == ARMISD::ADDE && 10281 isNullConstant(LHS->getOperand(0)) && 10282 isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) { 10283 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2)); 10284 } 10285 } 10286 10287 if (Subtarget->isThumb1Only()) { 10288 SDValue RHS = N->getOperand(1); 10289 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10290 int32_t imm = C->getSExtValue(); 10291 if (imm < 0 && imm > std::numeric_limits<int>::min()) { 10292 SDLoc DL(N); 10293 RHS = DAG.getConstant(-imm, DL, MVT::i32); 10294 unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC 10295 : ARMISD::ADDC; 10296 return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS); 10297 } 10298 } 10299 } 10300 return SDValue(); 10301 } 10302 10303 static SDValue PerformAddeSubeCombine(SDNode *N, 10304 TargetLowering::DAGCombinerInfo &DCI, 10305 const ARMSubtarget *Subtarget) { 10306 if (Subtarget->isThumb1Only()) { 10307 SelectionDAG &DAG = DCI.DAG; 10308 SDValue RHS = N->getOperand(1); 10309 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 10310 int64_t imm = C->getSExtValue(); 10311 if (imm < 0) { 10312 SDLoc DL(N); 10313 10314 // The with-carry-in form matches bitwise not instead of the negation. 10315 // Effectively, the inverse interpretation of the carry flag already 10316 // accounts for part of the negation. 10317 RHS = DAG.getConstant(~imm, DL, MVT::i32); 10318 10319 unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE 10320 : ARMISD::ADDE; 10321 return DAG.getNode(Opcode, DL, N->getVTList(), 10322 N->getOperand(0), RHS, N->getOperand(2)); 10323 } 10324 } 10325 } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) { 10326 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 10327 } 10328 return SDValue(); 10329 } 10330 10331 /// PerformADDECombine - Target-specific dag combine transform from 10332 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or 10333 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL 10334 static SDValue PerformADDECombine(SDNode *N, 10335 TargetLowering::DAGCombinerInfo &DCI, 10336 const ARMSubtarget *Subtarget) { 10337 // Only ARM and Thumb2 support UMLAL/SMLAL. 10338 if (Subtarget->isThumb1Only()) 10339 return PerformAddeSubeCombine(N, DCI, Subtarget); 10340 10341 // Only perform the checks after legalize when the pattern is available. 10342 if (DCI.isBeforeLegalize()) return SDValue(); 10343 10344 return AddCombineTo64bitUMAAL(N, DCI, Subtarget); 10345 } 10346 10347 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 10348 /// operands N0 and N1. This is a helper for PerformADDCombine that is 10349 /// called with the default operands, and if that fails, with commuted 10350 /// operands. 10351 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 10352 TargetLowering::DAGCombinerInfo &DCI, 10353 const ARMSubtarget *Subtarget){ 10354 // Attempt to create vpadd for this add. 10355 if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget)) 10356 return Result; 10357 10358 // Attempt to create vpaddl for this add. 10359 if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget)) 10360 return Result; 10361 if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI, 10362 Subtarget)) 10363 return Result; 10364 10365 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 10366 if (N0.getNode()->hasOneUse()) 10367 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI)) 10368 return Result; 10369 return SDValue(); 10370 } 10371 10372 static SDValue PerformSHLSimplify(SDNode *N, 10373 TargetLowering::DAGCombinerInfo &DCI, 10374 const ARMSubtarget *ST) { 10375 // Allow the generic combiner to identify potential bswaps. 10376 if (DCI.isBeforeLegalize()) 10377 return SDValue(); 10378 10379 // DAG combiner will fold: 10380 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 10381 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2 10382 // Other code patterns that can be also be modified have the following form: 10383 // b + ((a << 1) | 510) 10384 // b + ((a << 1) & 510) 10385 // b + ((a << 1) ^ 510) 10386 // b + ((a << 1) + 510) 10387 10388 // Many instructions can perform the shift for free, but it requires both 10389 // the operands to be registers. If c1 << c2 is too large, a mov immediate 10390 // instruction will needed. So, unfold back to the original pattern if: 10391 // - if c1 and c2 are small enough that they don't require mov imms. 10392 // - the user(s) of the node can perform an shl 10393 10394 // No shifted operands for 16-bit instructions. 10395 if (ST->isThumb() && ST->isThumb1Only()) 10396 return SDValue(); 10397 10398 // Check that all the users could perform the shl themselves. 10399 for (auto U : N->uses()) { 10400 switch(U->getOpcode()) { 10401 default: 10402 return SDValue(); 10403 case ISD::SUB: 10404 case ISD::ADD: 10405 case ISD::AND: 10406 case ISD::OR: 10407 case ISD::XOR: 10408 case ISD::SETCC: 10409 case ARMISD::CMP: 10410 // Check that its not already using a shl. 10411 if (U->getOperand(0).getOpcode() == ISD::SHL || 10412 U->getOperand(1).getOpcode() == ISD::SHL) 10413 return SDValue(); 10414 break; 10415 } 10416 } 10417 10418 if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR && 10419 N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND) 10420 return SDValue(); 10421 10422 if (N->getOperand(0).getOpcode() != ISD::SHL) 10423 return SDValue(); 10424 10425 SDValue SHL = N->getOperand(0); 10426 10427 auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10428 auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1)); 10429 if (!C1ShlC2 || !C2) 10430 return SDValue(); 10431 10432 DEBUG(dbgs() << "Trying to simplify shl: "; N->dump()); 10433 10434 APInt C2Int = C2->getAPIntValue(); 10435 APInt C1Int = C1ShlC2->getAPIntValue(); 10436 10437 // Check that performing a lshr will not lose any information. 10438 APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(), 10439 C2Int.getBitWidth() - C2->getZExtValue()); 10440 if ((C1Int & Mask) != C1Int) 10441 return SDValue(); 10442 10443 // Shift the first constant. 10444 C1Int.lshrInPlace(C2Int); 10445 10446 // The immediates are encoded as an 8-bit value that can be rotated. 10447 unsigned Zeros = C1Int.countLeadingZeros() + C1Int.countTrailingZeros(); 10448 if (C1Int.getBitWidth() - Zeros > 8) 10449 return SDValue(); 10450 10451 Zeros = C2Int.countLeadingZeros() + C2Int.countTrailingZeros(); 10452 if (C2Int.getBitWidth() - Zeros > 8) 10453 return SDValue(); 10454 10455 SelectionDAG &DAG = DCI.DAG; 10456 SDLoc dl(N); 10457 SDValue X = SHL.getOperand(0); 10458 SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X, 10459 DAG.getConstant(C1Int, dl, MVT::i32)); 10460 // Shift left to compensate for the lshr of C1Int. 10461 SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1)); 10462 10463 DAG.ReplaceAllUsesWith(SDValue(N, 0), Res); 10464 return SDValue(N, 0); 10465 } 10466 10467 10468 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 10469 /// 10470 static SDValue PerformADDCombine(SDNode *N, 10471 TargetLowering::DAGCombinerInfo &DCI, 10472 const ARMSubtarget *Subtarget) { 10473 SDValue N0 = N->getOperand(0); 10474 SDValue N1 = N->getOperand(1); 10475 10476 // Only works one way, because it needs an immediate operand. 10477 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10478 return Result; 10479 10480 // First try with the default operand order. 10481 if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget)) 10482 return Result; 10483 10484 // If that didn't work, try again with the operands commuted. 10485 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 10486 } 10487 10488 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 10489 /// 10490 static SDValue PerformSUBCombine(SDNode *N, 10491 TargetLowering::DAGCombinerInfo &DCI) { 10492 SDValue N0 = N->getOperand(0); 10493 SDValue N1 = N->getOperand(1); 10494 10495 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 10496 if (N1.getNode()->hasOneUse()) 10497 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI)) 10498 return Result; 10499 10500 return SDValue(); 10501 } 10502 10503 /// PerformVMULCombine 10504 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 10505 /// special multiplier accumulator forwarding. 10506 /// vmul d3, d0, d2 10507 /// vmla d3, d1, d2 10508 /// is faster than 10509 /// vadd d3, d0, d1 10510 /// vmul d3, d3, d2 10511 // However, for (A + B) * (A + B), 10512 // vadd d2, d0, d1 10513 // vmul d3, d0, d2 10514 // vmla d3, d1, d2 10515 // is slower than 10516 // vadd d2, d0, d1 10517 // vmul d3, d2, d2 10518 static SDValue PerformVMULCombine(SDNode *N, 10519 TargetLowering::DAGCombinerInfo &DCI, 10520 const ARMSubtarget *Subtarget) { 10521 if (!Subtarget->hasVMLxForwarding()) 10522 return SDValue(); 10523 10524 SelectionDAG &DAG = DCI.DAG; 10525 SDValue N0 = N->getOperand(0); 10526 SDValue N1 = N->getOperand(1); 10527 unsigned Opcode = N0.getOpcode(); 10528 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10529 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 10530 Opcode = N1.getOpcode(); 10531 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 10532 Opcode != ISD::FADD && Opcode != ISD::FSUB) 10533 return SDValue(); 10534 std::swap(N0, N1); 10535 } 10536 10537 if (N0 == N1) 10538 return SDValue(); 10539 10540 EVT VT = N->getValueType(0); 10541 SDLoc DL(N); 10542 SDValue N00 = N0->getOperand(0); 10543 SDValue N01 = N0->getOperand(1); 10544 return DAG.getNode(Opcode, DL, VT, 10545 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 10546 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 10547 } 10548 10549 static SDValue PerformMULCombine(SDNode *N, 10550 TargetLowering::DAGCombinerInfo &DCI, 10551 const ARMSubtarget *Subtarget) { 10552 SelectionDAG &DAG = DCI.DAG; 10553 10554 if (Subtarget->isThumb1Only()) 10555 return SDValue(); 10556 10557 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10558 return SDValue(); 10559 10560 EVT VT = N->getValueType(0); 10561 if (VT.is64BitVector() || VT.is128BitVector()) 10562 return PerformVMULCombine(N, DCI, Subtarget); 10563 if (VT != MVT::i32) 10564 return SDValue(); 10565 10566 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10567 if (!C) 10568 return SDValue(); 10569 10570 int64_t MulAmt = C->getSExtValue(); 10571 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 10572 10573 ShiftAmt = ShiftAmt & (32 - 1); 10574 SDValue V = N->getOperand(0); 10575 SDLoc DL(N); 10576 10577 SDValue Res; 10578 MulAmt >>= ShiftAmt; 10579 10580 if (MulAmt >= 0) { 10581 if (isPowerOf2_32(MulAmt - 1)) { 10582 // (mul x, 2^N + 1) => (add (shl x, N), x) 10583 Res = DAG.getNode(ISD::ADD, DL, VT, 10584 V, 10585 DAG.getNode(ISD::SHL, DL, VT, 10586 V, 10587 DAG.getConstant(Log2_32(MulAmt - 1), DL, 10588 MVT::i32))); 10589 } else if (isPowerOf2_32(MulAmt + 1)) { 10590 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10591 Res = DAG.getNode(ISD::SUB, DL, VT, 10592 DAG.getNode(ISD::SHL, DL, VT, 10593 V, 10594 DAG.getConstant(Log2_32(MulAmt + 1), DL, 10595 MVT::i32)), 10596 V); 10597 } else 10598 return SDValue(); 10599 } else { 10600 uint64_t MulAmtAbs = -MulAmt; 10601 if (isPowerOf2_32(MulAmtAbs + 1)) { 10602 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10603 Res = DAG.getNode(ISD::SUB, DL, VT, 10604 V, 10605 DAG.getNode(ISD::SHL, DL, VT, 10606 V, 10607 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL, 10608 MVT::i32))); 10609 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 10610 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10611 Res = DAG.getNode(ISD::ADD, DL, VT, 10612 V, 10613 DAG.getNode(ISD::SHL, DL, VT, 10614 V, 10615 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL, 10616 MVT::i32))); 10617 Res = DAG.getNode(ISD::SUB, DL, VT, 10618 DAG.getConstant(0, DL, MVT::i32), Res); 10619 } else 10620 return SDValue(); 10621 } 10622 10623 if (ShiftAmt != 0) 10624 Res = DAG.getNode(ISD::SHL, DL, VT, 10625 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32)); 10626 10627 // Do not add new nodes to DAG combiner worklist. 10628 DCI.CombineTo(N, Res, false); 10629 return SDValue(); 10630 } 10631 10632 static SDValue PerformANDCombine(SDNode *N, 10633 TargetLowering::DAGCombinerInfo &DCI, 10634 const ARMSubtarget *Subtarget) { 10635 // Attempt to use immediate-form VBIC 10636 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10637 SDLoc dl(N); 10638 EVT VT = N->getValueType(0); 10639 SelectionDAG &DAG = DCI.DAG; 10640 10641 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10642 return SDValue(); 10643 10644 APInt SplatBits, SplatUndef; 10645 unsigned SplatBitSize; 10646 bool HasAnyUndefs; 10647 if (BVN && 10648 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10649 if (SplatBitSize <= 64) { 10650 EVT VbicVT; 10651 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 10652 SplatUndef.getZExtValue(), SplatBitSize, 10653 DAG, dl, VbicVT, VT.is128BitVector(), 10654 OtherModImm); 10655 if (Val.getNode()) { 10656 SDValue Input = 10657 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 10658 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 10659 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 10660 } 10661 } 10662 } 10663 10664 if (!Subtarget->isThumb1Only()) { 10665 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 10666 if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI)) 10667 return Result; 10668 10669 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10670 return Result; 10671 } 10672 10673 return SDValue(); 10674 } 10675 10676 // Try combining OR nodes to SMULWB, SMULWT. 10677 static SDValue PerformORCombineToSMULWBT(SDNode *OR, 10678 TargetLowering::DAGCombinerInfo &DCI, 10679 const ARMSubtarget *Subtarget) { 10680 if (!Subtarget->hasV6Ops() || 10681 (Subtarget->isThumb() && 10682 (!Subtarget->hasThumb2() || !Subtarget->hasDSP()))) 10683 return SDValue(); 10684 10685 SDValue SRL = OR->getOperand(0); 10686 SDValue SHL = OR->getOperand(1); 10687 10688 if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) { 10689 SRL = OR->getOperand(1); 10690 SHL = OR->getOperand(0); 10691 } 10692 if (!isSRL16(SRL) || !isSHL16(SHL)) 10693 return SDValue(); 10694 10695 // The first operands to the shifts need to be the two results from the 10696 // same smul_lohi node. 10697 if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) || 10698 SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI) 10699 return SDValue(); 10700 10701 SDNode *SMULLOHI = SRL.getOperand(0).getNode(); 10702 if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) || 10703 SHL.getOperand(0) != SDValue(SMULLOHI, 1)) 10704 return SDValue(); 10705 10706 // Now we have: 10707 // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16))) 10708 // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments. 10709 // For SMUWB the 16-bit value will signed extended somehow. 10710 // For SMULWT only the SRA is required. 10711 // Check both sides of SMUL_LOHI 10712 SDValue OpS16 = SMULLOHI->getOperand(0); 10713 SDValue OpS32 = SMULLOHI->getOperand(1); 10714 10715 SelectionDAG &DAG = DCI.DAG; 10716 if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) { 10717 OpS16 = OpS32; 10718 OpS32 = SMULLOHI->getOperand(0); 10719 } 10720 10721 SDLoc dl(OR); 10722 unsigned Opcode = 0; 10723 if (isS16(OpS16, DAG)) 10724 Opcode = ARMISD::SMULWB; 10725 else if (isSRA16(OpS16)) { 10726 Opcode = ARMISD::SMULWT; 10727 OpS16 = OpS16->getOperand(0); 10728 } 10729 else 10730 return SDValue(); 10731 10732 SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16); 10733 DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res); 10734 return SDValue(OR, 0); 10735 } 10736 10737 static SDValue PerformORCombineToBFI(SDNode *N, 10738 TargetLowering::DAGCombinerInfo &DCI, 10739 const ARMSubtarget *Subtarget) { 10740 // BFI is only available on V6T2+ 10741 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 10742 return SDValue(); 10743 10744 EVT VT = N->getValueType(0); 10745 SDValue N0 = N->getOperand(0); 10746 SDValue N1 = N->getOperand(1); 10747 SelectionDAG &DAG = DCI.DAG; 10748 SDLoc DL(N); 10749 // 1) or (and A, mask), val => ARMbfi A, val, mask 10750 // iff (val & mask) == val 10751 // 10752 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10753 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 10754 // && mask == ~mask2 10755 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 10756 // && ~mask == mask2 10757 // (i.e., copy a bitfield value into another bitfield of the same width) 10758 10759 if (VT != MVT::i32) 10760 return SDValue(); 10761 10762 SDValue N00 = N0.getOperand(0); 10763 10764 // The value and the mask need to be constants so we can verify this is 10765 // actually a bitfield set. If the mask is 0xffff, we can do better 10766 // via a movt instruction, so don't use BFI in that case. 10767 SDValue MaskOp = N0.getOperand(1); 10768 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 10769 if (!MaskC) 10770 return SDValue(); 10771 unsigned Mask = MaskC->getZExtValue(); 10772 if (Mask == 0xffff) 10773 return SDValue(); 10774 SDValue Res; 10775 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 10776 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10777 if (N1C) { 10778 unsigned Val = N1C->getZExtValue(); 10779 if ((Val & ~Mask) != Val) 10780 return SDValue(); 10781 10782 if (ARM::isBitFieldInvertedMask(Mask)) { 10783 Val >>= countTrailingZeros(~Mask); 10784 10785 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 10786 DAG.getConstant(Val, DL, MVT::i32), 10787 DAG.getConstant(Mask, DL, MVT::i32)); 10788 10789 DCI.CombineTo(N, Res, false); 10790 // Return value from the original node to inform the combiner than N is 10791 // now dead. 10792 return SDValue(N, 0); 10793 } 10794 } else if (N1.getOpcode() == ISD::AND) { 10795 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 10796 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 10797 if (!N11C) 10798 return SDValue(); 10799 unsigned Mask2 = N11C->getZExtValue(); 10800 10801 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 10802 // as is to match. 10803 if (ARM::isBitFieldInvertedMask(Mask) && 10804 (Mask == ~Mask2)) { 10805 // The pack halfword instruction works better for masks that fit it, 10806 // so use that when it's available. 10807 if (Subtarget->hasDSP() && 10808 (Mask == 0xffff || Mask == 0xffff0000)) 10809 return SDValue(); 10810 // 2a 10811 unsigned amt = countTrailingZeros(Mask2); 10812 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 10813 DAG.getConstant(amt, DL, MVT::i32)); 10814 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 10815 DAG.getConstant(Mask, DL, MVT::i32)); 10816 DCI.CombineTo(N, Res, false); 10817 // Return value from the original node to inform the combiner than N is 10818 // now dead. 10819 return SDValue(N, 0); 10820 } else if (ARM::isBitFieldInvertedMask(~Mask) && 10821 (~Mask == Mask2)) { 10822 // The pack halfword instruction works better for masks that fit it, 10823 // so use that when it's available. 10824 if (Subtarget->hasDSP() && 10825 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 10826 return SDValue(); 10827 // 2b 10828 unsigned lsb = countTrailingZeros(Mask); 10829 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 10830 DAG.getConstant(lsb, DL, MVT::i32)); 10831 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 10832 DAG.getConstant(Mask2, DL, MVT::i32)); 10833 DCI.CombineTo(N, Res, false); 10834 // Return value from the original node to inform the combiner than N is 10835 // now dead. 10836 return SDValue(N, 0); 10837 } 10838 } 10839 10840 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 10841 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 10842 ARM::isBitFieldInvertedMask(~Mask)) { 10843 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 10844 // where lsb(mask) == #shamt and masked bits of B are known zero. 10845 SDValue ShAmt = N00.getOperand(1); 10846 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10847 unsigned LSB = countTrailingZeros(Mask); 10848 if (ShAmtC != LSB) 10849 return SDValue(); 10850 10851 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 10852 DAG.getConstant(~Mask, DL, MVT::i32)); 10853 10854 DCI.CombineTo(N, Res, false); 10855 // Return value from the original node to inform the combiner than N is 10856 // now dead. 10857 return SDValue(N, 0); 10858 } 10859 10860 return SDValue(); 10861 } 10862 10863 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 10864 static SDValue PerformORCombine(SDNode *N, 10865 TargetLowering::DAGCombinerInfo &DCI, 10866 const ARMSubtarget *Subtarget) { 10867 // Attempt to use immediate-form VORR 10868 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 10869 SDLoc dl(N); 10870 EVT VT = N->getValueType(0); 10871 SelectionDAG &DAG = DCI.DAG; 10872 10873 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10874 return SDValue(); 10875 10876 APInt SplatBits, SplatUndef; 10877 unsigned SplatBitSize; 10878 bool HasAnyUndefs; 10879 if (BVN && Subtarget->hasNEON() && 10880 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 10881 if (SplatBitSize <= 64) { 10882 EVT VorrVT; 10883 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 10884 SplatUndef.getZExtValue(), SplatBitSize, 10885 DAG, dl, VorrVT, VT.is128BitVector(), 10886 OtherModImm); 10887 if (Val.getNode()) { 10888 SDValue Input = 10889 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 10890 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 10891 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 10892 } 10893 } 10894 } 10895 10896 if (!Subtarget->isThumb1Only()) { 10897 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 10898 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10899 return Result; 10900 if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget)) 10901 return Result; 10902 } 10903 10904 SDValue N0 = N->getOperand(0); 10905 SDValue N1 = N->getOperand(1); 10906 10907 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 10908 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 10909 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10910 10911 // The code below optimizes (or (and X, Y), Z). 10912 // The AND operand needs to have a single user to make these optimizations 10913 // profitable. 10914 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 10915 return SDValue(); 10916 10917 APInt SplatUndef; 10918 unsigned SplatBitSize; 10919 bool HasAnyUndefs; 10920 10921 APInt SplatBits0, SplatBits1; 10922 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 10923 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 10924 // Ensure that the second operand of both ands are constants 10925 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 10926 HasAnyUndefs) && !HasAnyUndefs) { 10927 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 10928 HasAnyUndefs) && !HasAnyUndefs) { 10929 // Ensure that the bit width of the constants are the same and that 10930 // the splat arguments are logical inverses as per the pattern we 10931 // are trying to simplify. 10932 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 10933 SplatBits0 == ~SplatBits1) { 10934 // Canonicalize the vector type to make instruction selection 10935 // simpler. 10936 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 10937 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 10938 N0->getOperand(1), 10939 N0->getOperand(0), 10940 N1->getOperand(0)); 10941 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 10942 } 10943 } 10944 } 10945 } 10946 10947 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 10948 // reasonable. 10949 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 10950 if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget)) 10951 return Res; 10952 } 10953 10954 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10955 return Result; 10956 10957 return SDValue(); 10958 } 10959 10960 static SDValue PerformXORCombine(SDNode *N, 10961 TargetLowering::DAGCombinerInfo &DCI, 10962 const ARMSubtarget *Subtarget) { 10963 EVT VT = N->getValueType(0); 10964 SelectionDAG &DAG = DCI.DAG; 10965 10966 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10967 return SDValue(); 10968 10969 if (!Subtarget->isThumb1Only()) { 10970 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 10971 if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI)) 10972 return Result; 10973 10974 if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget)) 10975 return Result; 10976 } 10977 10978 return SDValue(); 10979 } 10980 10981 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it, 10982 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and 10983 // their position in "to" (Rd). 10984 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) { 10985 assert(N->getOpcode() == ARMISD::BFI); 10986 10987 SDValue From = N->getOperand(1); 10988 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue(); 10989 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation()); 10990 10991 // If the Base came from a SHR #C, we can deduce that it is really testing bit 10992 // #C in the base of the SHR. 10993 if (From->getOpcode() == ISD::SRL && 10994 isa<ConstantSDNode>(From->getOperand(1))) { 10995 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue(); 10996 assert(Shift.getLimitedValue() < 32 && "Shift too large!"); 10997 FromMask <<= Shift.getLimitedValue(31); 10998 From = From->getOperand(0); 10999 } 11000 11001 return From; 11002 } 11003 11004 // If A and B contain one contiguous set of bits, does A | B == A . B? 11005 // 11006 // Neither A nor B must be zero. 11007 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) { 11008 unsigned LastActiveBitInA = A.countTrailingZeros(); 11009 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1; 11010 return LastActiveBitInA - 1 == FirstActiveBitInB; 11011 } 11012 11013 static SDValue FindBFIToCombineWith(SDNode *N) { 11014 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with, 11015 // if one exists. 11016 APInt ToMask, FromMask; 11017 SDValue From = ParseBFI(N, ToMask, FromMask); 11018 SDValue To = N->getOperand(0); 11019 11020 // Now check for a compatible BFI to merge with. We can pass through BFIs that 11021 // aren't compatible, but not if they set the same bit in their destination as 11022 // we do (or that of any BFI we're going to combine with). 11023 SDValue V = To; 11024 APInt CombinedToMask = ToMask; 11025 while (V.getOpcode() == ARMISD::BFI) { 11026 APInt NewToMask, NewFromMask; 11027 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask); 11028 if (NewFrom != From) { 11029 // This BFI has a different base. Keep going. 11030 CombinedToMask |= NewToMask; 11031 V = V.getOperand(0); 11032 continue; 11033 } 11034 11035 // Do the written bits conflict with any we've seen so far? 11036 if ((NewToMask & CombinedToMask).getBoolValue()) 11037 // Conflicting bits - bail out because going further is unsafe. 11038 return SDValue(); 11039 11040 // Are the new bits contiguous when combined with the old bits? 11041 if (BitsProperlyConcatenate(ToMask, NewToMask) && 11042 BitsProperlyConcatenate(FromMask, NewFromMask)) 11043 return V; 11044 if (BitsProperlyConcatenate(NewToMask, ToMask) && 11045 BitsProperlyConcatenate(NewFromMask, FromMask)) 11046 return V; 11047 11048 // We've seen a write to some bits, so track it. 11049 CombinedToMask |= NewToMask; 11050 // Keep going... 11051 V = V.getOperand(0); 11052 } 11053 11054 return SDValue(); 11055 } 11056 11057 static SDValue PerformBFICombine(SDNode *N, 11058 TargetLowering::DAGCombinerInfo &DCI) { 11059 SDValue N1 = N->getOperand(1); 11060 if (N1.getOpcode() == ISD::AND) { 11061 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 11062 // the bits being cleared by the AND are not demanded by the BFI. 11063 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 11064 if (!N11C) 11065 return SDValue(); 11066 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 11067 unsigned LSB = countTrailingZeros(~InvMask); 11068 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 11069 assert(Width < 11070 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 11071 "undefined behavior"); 11072 unsigned Mask = (1u << Width) - 1; 11073 unsigned Mask2 = N11C->getZExtValue(); 11074 if ((Mask & (~Mask2)) == 0) 11075 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 11076 N->getOperand(0), N1.getOperand(0), 11077 N->getOperand(2)); 11078 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) { 11079 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes. 11080 // Keep track of any consecutive bits set that all come from the same base 11081 // value. We can combine these together into a single BFI. 11082 SDValue CombineBFI = FindBFIToCombineWith(N); 11083 if (CombineBFI == SDValue()) 11084 return SDValue(); 11085 11086 // We've found a BFI. 11087 APInt ToMask1, FromMask1; 11088 SDValue From1 = ParseBFI(N, ToMask1, FromMask1); 11089 11090 APInt ToMask2, FromMask2; 11091 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2); 11092 assert(From1 == From2); 11093 (void)From2; 11094 11095 // First, unlink CombineBFI. 11096 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0)); 11097 // Then create a new BFI, combining the two together. 11098 APInt NewFromMask = FromMask1 | FromMask2; 11099 APInt NewToMask = ToMask1 | ToMask2; 11100 11101 EVT VT = N->getValueType(0); 11102 SDLoc dl(N); 11103 11104 if (NewFromMask[0] == 0) 11105 From1 = DCI.DAG.getNode( 11106 ISD::SRL, dl, VT, From1, 11107 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT)); 11108 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1, 11109 DCI.DAG.getConstant(~NewToMask, dl, VT)); 11110 } 11111 return SDValue(); 11112 } 11113 11114 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 11115 /// ARMISD::VMOVRRD. 11116 static SDValue PerformVMOVRRDCombine(SDNode *N, 11117 TargetLowering::DAGCombinerInfo &DCI, 11118 const ARMSubtarget *Subtarget) { 11119 // vmovrrd(vmovdrr x, y) -> x,y 11120 SDValue InDouble = N->getOperand(0); 11121 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP()) 11122 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 11123 11124 // vmovrrd(load f64) -> (load i32), (load i32) 11125 SDNode *InNode = InDouble.getNode(); 11126 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 11127 InNode->getValueType(0) == MVT::f64 && 11128 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 11129 !cast<LoadSDNode>(InNode)->isVolatile()) { 11130 // TODO: Should this be done for non-FrameIndex operands? 11131 LoadSDNode *LD = cast<LoadSDNode>(InNode); 11132 11133 SelectionDAG &DAG = DCI.DAG; 11134 SDLoc DL(LD); 11135 SDValue BasePtr = LD->getBasePtr(); 11136 SDValue NewLD1 = 11137 DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(), 11138 LD->getAlignment(), LD->getMemOperand()->getFlags()); 11139 11140 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11141 DAG.getConstant(4, DL, MVT::i32)); 11142 SDValue NewLD2 = DAG.getLoad( 11143 MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(), 11144 std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags()); 11145 11146 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 11147 if (DCI.DAG.getDataLayout().isBigEndian()) 11148 std::swap (NewLD1, NewLD2); 11149 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 11150 return Result; 11151 } 11152 11153 return SDValue(); 11154 } 11155 11156 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 11157 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 11158 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 11159 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 11160 SDValue Op0 = N->getOperand(0); 11161 SDValue Op1 = N->getOperand(1); 11162 if (Op0.getOpcode() == ISD::BITCAST) 11163 Op0 = Op0.getOperand(0); 11164 if (Op1.getOpcode() == ISD::BITCAST) 11165 Op1 = Op1.getOperand(0); 11166 if (Op0.getOpcode() == ARMISD::VMOVRRD && 11167 Op0.getNode() == Op1.getNode() && 11168 Op0.getResNo() == 0 && Op1.getResNo() == 1) 11169 return DAG.getNode(ISD::BITCAST, SDLoc(N), 11170 N->getValueType(0), Op0.getOperand(0)); 11171 return SDValue(); 11172 } 11173 11174 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 11175 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 11176 /// i64 vector to have f64 elements, since the value can then be loaded 11177 /// directly into a VFP register. 11178 static bool hasNormalLoadOperand(SDNode *N) { 11179 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 11180 for (unsigned i = 0; i < NumElts; ++i) { 11181 SDNode *Elt = N->getOperand(i).getNode(); 11182 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 11183 return true; 11184 } 11185 return false; 11186 } 11187 11188 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 11189 /// ISD::BUILD_VECTOR. 11190 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 11191 TargetLowering::DAGCombinerInfo &DCI, 11192 const ARMSubtarget *Subtarget) { 11193 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 11194 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 11195 // into a pair of GPRs, which is fine when the value is used as a scalar, 11196 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 11197 SelectionDAG &DAG = DCI.DAG; 11198 if (N->getNumOperands() == 2) 11199 if (SDValue RV = PerformVMOVDRRCombine(N, DAG)) 11200 return RV; 11201 11202 // Load i64 elements as f64 values so that type legalization does not split 11203 // them up into i32 values. 11204 EVT VT = N->getValueType(0); 11205 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 11206 return SDValue(); 11207 SDLoc dl(N); 11208 SmallVector<SDValue, 8> Ops; 11209 unsigned NumElts = VT.getVectorNumElements(); 11210 for (unsigned i = 0; i < NumElts; ++i) { 11211 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 11212 Ops.push_back(V); 11213 // Make the DAGCombiner fold the bitcast. 11214 DCI.AddToWorklist(V.getNode()); 11215 } 11216 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 11217 SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops); 11218 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11219 } 11220 11221 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 11222 static SDValue 11223 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11224 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 11225 // At that time, we may have inserted bitcasts from integer to float. 11226 // If these bitcasts have survived DAGCombine, change the lowering of this 11227 // BUILD_VECTOR in something more vector friendly, i.e., that does not 11228 // force to use floating point types. 11229 11230 // Make sure we can change the type of the vector. 11231 // This is possible iff: 11232 // 1. The vector is only used in a bitcast to a integer type. I.e., 11233 // 1.1. Vector is used only once. 11234 // 1.2. Use is a bit convert to an integer type. 11235 // 2. The size of its operands are 32-bits (64-bits are not legal). 11236 EVT VT = N->getValueType(0); 11237 EVT EltVT = VT.getVectorElementType(); 11238 11239 // Check 1.1. and 2. 11240 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 11241 return SDValue(); 11242 11243 // By construction, the input type must be float. 11244 assert(EltVT == MVT::f32 && "Unexpected type!"); 11245 11246 // Check 1.2. 11247 SDNode *Use = *N->use_begin(); 11248 if (Use->getOpcode() != ISD::BITCAST || 11249 Use->getValueType(0).isFloatingPoint()) 11250 return SDValue(); 11251 11252 // Check profitability. 11253 // Model is, if more than half of the relevant operands are bitcast from 11254 // i32, turn the build_vector into a sequence of insert_vector_elt. 11255 // Relevant operands are everything that is not statically 11256 // (i.e., at compile time) bitcasted. 11257 unsigned NumOfBitCastedElts = 0; 11258 unsigned NumElts = VT.getVectorNumElements(); 11259 unsigned NumOfRelevantElts = NumElts; 11260 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 11261 SDValue Elt = N->getOperand(Idx); 11262 if (Elt->getOpcode() == ISD::BITCAST) { 11263 // Assume only bit cast to i32 will go away. 11264 if (Elt->getOperand(0).getValueType() == MVT::i32) 11265 ++NumOfBitCastedElts; 11266 } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt)) 11267 // Constants are statically casted, thus do not count them as 11268 // relevant operands. 11269 --NumOfRelevantElts; 11270 } 11271 11272 // Check if more than half of the elements require a non-free bitcast. 11273 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 11274 return SDValue(); 11275 11276 SelectionDAG &DAG = DCI.DAG; 11277 // Create the new vector type. 11278 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 11279 // Check if the type is legal. 11280 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11281 if (!TLI.isTypeLegal(VecVT)) 11282 return SDValue(); 11283 11284 // Combine: 11285 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 11286 // => BITCAST INSERT_VECTOR_ELT 11287 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 11288 // (BITCAST EN), N. 11289 SDValue Vec = DAG.getUNDEF(VecVT); 11290 SDLoc dl(N); 11291 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 11292 SDValue V = N->getOperand(Idx); 11293 if (V.isUndef()) 11294 continue; 11295 if (V.getOpcode() == ISD::BITCAST && 11296 V->getOperand(0).getValueType() == MVT::i32) 11297 // Fold obvious case. 11298 V = V.getOperand(0); 11299 else { 11300 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 11301 // Make the DAGCombiner fold the bitcasts. 11302 DCI.AddToWorklist(V.getNode()); 11303 } 11304 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32); 11305 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 11306 } 11307 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 11308 // Make the DAGCombiner fold the bitcasts. 11309 DCI.AddToWorklist(Vec.getNode()); 11310 return Vec; 11311 } 11312 11313 /// PerformInsertEltCombine - Target-specific dag combine xforms for 11314 /// ISD::INSERT_VECTOR_ELT. 11315 static SDValue PerformInsertEltCombine(SDNode *N, 11316 TargetLowering::DAGCombinerInfo &DCI) { 11317 // Bitcast an i64 load inserted into a vector to f64. 11318 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11319 EVT VT = N->getValueType(0); 11320 SDNode *Elt = N->getOperand(1).getNode(); 11321 if (VT.getVectorElementType() != MVT::i64 || 11322 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 11323 return SDValue(); 11324 11325 SelectionDAG &DAG = DCI.DAG; 11326 SDLoc dl(N); 11327 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11328 VT.getVectorNumElements()); 11329 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 11330 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 11331 // Make the DAGCombiner fold the bitcasts. 11332 DCI.AddToWorklist(Vec.getNode()); 11333 DCI.AddToWorklist(V.getNode()); 11334 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 11335 Vec, V, N->getOperand(2)); 11336 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 11337 } 11338 11339 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 11340 /// ISD::VECTOR_SHUFFLE. 11341 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 11342 // The LLVM shufflevector instruction does not require the shuffle mask 11343 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 11344 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 11345 // operands do not match the mask length, they are extended by concatenating 11346 // them with undef vectors. That is probably the right thing for other 11347 // targets, but for NEON it is better to concatenate two double-register 11348 // size vector operands into a single quad-register size vector. Do that 11349 // transformation here: 11350 // shuffle(concat(v1, undef), concat(v2, undef)) -> 11351 // shuffle(concat(v1, v2), undef) 11352 SDValue Op0 = N->getOperand(0); 11353 SDValue Op1 = N->getOperand(1); 11354 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 11355 Op1.getOpcode() != ISD::CONCAT_VECTORS || 11356 Op0.getNumOperands() != 2 || 11357 Op1.getNumOperands() != 2) 11358 return SDValue(); 11359 SDValue Concat0Op1 = Op0.getOperand(1); 11360 SDValue Concat1Op1 = Op1.getOperand(1); 11361 if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef()) 11362 return SDValue(); 11363 // Skip the transformation if any of the types are illegal. 11364 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11365 EVT VT = N->getValueType(0); 11366 if (!TLI.isTypeLegal(VT) || 11367 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 11368 !TLI.isTypeLegal(Concat1Op1.getValueType())) 11369 return SDValue(); 11370 11371 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11372 Op0.getOperand(0), Op1.getOperand(0)); 11373 // Translate the shuffle mask. 11374 SmallVector<int, 16> NewMask; 11375 unsigned NumElts = VT.getVectorNumElements(); 11376 unsigned HalfElts = NumElts/2; 11377 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11378 for (unsigned n = 0; n < NumElts; ++n) { 11379 int MaskElt = SVN->getMaskElt(n); 11380 int NewElt = -1; 11381 if (MaskElt < (int)HalfElts) 11382 NewElt = MaskElt; 11383 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 11384 NewElt = HalfElts + MaskElt - NumElts; 11385 NewMask.push_back(NewElt); 11386 } 11387 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 11388 DAG.getUNDEF(VT), NewMask); 11389 } 11390 11391 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP, 11392 /// NEON load/store intrinsics, and generic vector load/stores, to merge 11393 /// base address updates. 11394 /// For generic load/stores, the memory type is assumed to be a vector. 11395 /// The caller is assumed to have checked legality. 11396 static SDValue CombineBaseUpdate(SDNode *N, 11397 TargetLowering::DAGCombinerInfo &DCI) { 11398 SelectionDAG &DAG = DCI.DAG; 11399 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 11400 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 11401 const bool isStore = N->getOpcode() == ISD::STORE; 11402 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1); 11403 SDValue Addr = N->getOperand(AddrOpIdx); 11404 MemSDNode *MemN = cast<MemSDNode>(N); 11405 SDLoc dl(N); 11406 11407 // Search for a use of the address operand that is an increment. 11408 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11409 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11410 SDNode *User = *UI; 11411 if (User->getOpcode() != ISD::ADD || 11412 UI.getUse().getResNo() != Addr.getResNo()) 11413 continue; 11414 11415 // Check that the add is independent of the load/store. Otherwise, folding 11416 // it would create a cycle. 11417 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 11418 continue; 11419 11420 // Find the new opcode for the updating load/store. 11421 bool isLoadOp = true; 11422 bool isLaneOp = false; 11423 unsigned NewOpc = 0; 11424 unsigned NumVecs = 0; 11425 if (isIntrinsic) { 11426 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11427 switch (IntNo) { 11428 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11429 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 11430 NumVecs = 1; break; 11431 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 11432 NumVecs = 2; break; 11433 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 11434 NumVecs = 3; break; 11435 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 11436 NumVecs = 4; break; 11437 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 11438 NumVecs = 2; isLaneOp = true; break; 11439 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 11440 NumVecs = 3; isLaneOp = true; break; 11441 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 11442 NumVecs = 4; isLaneOp = true; break; 11443 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 11444 NumVecs = 1; isLoadOp = false; break; 11445 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 11446 NumVecs = 2; isLoadOp = false; break; 11447 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 11448 NumVecs = 3; isLoadOp = false; break; 11449 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 11450 NumVecs = 4; isLoadOp = false; break; 11451 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 11452 NumVecs = 2; isLoadOp = false; isLaneOp = true; break; 11453 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 11454 NumVecs = 3; isLoadOp = false; isLaneOp = true; break; 11455 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 11456 NumVecs = 4; isLoadOp = false; isLaneOp = true; break; 11457 } 11458 } else { 11459 isLaneOp = true; 11460 switch (N->getOpcode()) { 11461 default: llvm_unreachable("unexpected opcode for Neon base update"); 11462 case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break; 11463 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 11464 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 11465 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 11466 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD; 11467 NumVecs = 1; isLaneOp = false; break; 11468 case ISD::STORE: NewOpc = ARMISD::VST1_UPD; 11469 NumVecs = 1; isLaneOp = false; isLoadOp = false; break; 11470 } 11471 } 11472 11473 // Find the size of memory referenced by the load/store. 11474 EVT VecTy; 11475 if (isLoadOp) { 11476 VecTy = N->getValueType(0); 11477 } else if (isIntrinsic) { 11478 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 11479 } else { 11480 assert(isStore && "Node has to be a load, a store, or an intrinsic!"); 11481 VecTy = N->getOperand(1).getValueType(); 11482 } 11483 11484 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 11485 if (isLaneOp) 11486 NumBytes /= VecTy.getVectorNumElements(); 11487 11488 // If the increment is a constant, it must match the memory ref size. 11489 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11490 ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode()); 11491 if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) { 11492 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 11493 // separate instructions that make it harder to use a non-constant update. 11494 continue; 11495 } 11496 11497 // OK, we found an ADD we can fold into the base update. 11498 // Now, create a _UPD node, taking care of not breaking alignment. 11499 11500 EVT AlignedVecTy = VecTy; 11501 unsigned Alignment = MemN->getAlignment(); 11502 11503 // If this is a less-than-standard-aligned load/store, change the type to 11504 // match the standard alignment. 11505 // The alignment is overlooked when selecting _UPD variants; and it's 11506 // easier to introduce bitcasts here than fix that. 11507 // There are 3 ways to get to this base-update combine: 11508 // - intrinsics: they are assumed to be properly aligned (to the standard 11509 // alignment of the memory type), so we don't need to do anything. 11510 // - ARMISD::VLDx nodes: they are only generated from the aforementioned 11511 // intrinsics, so, likewise, there's nothing to do. 11512 // - generic load/store instructions: the alignment is specified as an 11513 // explicit operand, rather than implicitly as the standard alignment 11514 // of the memory type (like the intrisics). We need to change the 11515 // memory type to match the explicit alignment. That way, we don't 11516 // generate non-standard-aligned ARMISD::VLDx nodes. 11517 if (isa<LSBaseSDNode>(N)) { 11518 if (Alignment == 0) 11519 Alignment = 1; 11520 if (Alignment < VecTy.getScalarSizeInBits() / 8) { 11521 MVT EltTy = MVT::getIntegerVT(Alignment * 8); 11522 assert(NumVecs == 1 && "Unexpected multi-element generic load/store."); 11523 assert(!isLaneOp && "Unexpected generic load/store lane."); 11524 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8); 11525 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts); 11526 } 11527 // Don't set an explicit alignment on regular load/stores that we want 11528 // to transform to VLD/VST 1_UPD nodes. 11529 // This matches the behavior of regular load/stores, which only get an 11530 // explicit alignment if the MMO alignment is larger than the standard 11531 // alignment of the memory type. 11532 // Intrinsics, however, always get an explicit alignment, set to the 11533 // alignment of the MMO. 11534 Alignment = 1; 11535 } 11536 11537 // Create the new updating load/store node. 11538 // First, create an SDVTList for the new updating node's results. 11539 EVT Tys[6]; 11540 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0); 11541 unsigned n; 11542 for (n = 0; n < NumResultVecs; ++n) 11543 Tys[n] = AlignedVecTy; 11544 Tys[n++] = MVT::i32; 11545 Tys[n] = MVT::Other; 11546 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2)); 11547 11548 // Then, gather the new node's operands. 11549 SmallVector<SDValue, 8> Ops; 11550 Ops.push_back(N->getOperand(0)); // incoming chain 11551 Ops.push_back(N->getOperand(AddrOpIdx)); 11552 Ops.push_back(Inc); 11553 11554 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) { 11555 // Try to match the intrinsic's signature 11556 Ops.push_back(StN->getValue()); 11557 } else { 11558 // Loads (and of course intrinsics) match the intrinsics' signature, 11559 // so just add all but the alignment operand. 11560 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i) 11561 Ops.push_back(N->getOperand(i)); 11562 } 11563 11564 // For all node types, the alignment operand is always the last one. 11565 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32)); 11566 11567 // If this is a non-standard-aligned STORE, the penultimate operand is the 11568 // stored value. Bitcast it to the aligned type. 11569 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) { 11570 SDValue &StVal = Ops[Ops.size()-2]; 11571 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal); 11572 } 11573 11574 EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy; 11575 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT, 11576 MemN->getMemOperand()); 11577 11578 // Update the uses. 11579 SmallVector<SDValue, 5> NewResults; 11580 for (unsigned i = 0; i < NumResultVecs; ++i) 11581 NewResults.push_back(SDValue(UpdN.getNode(), i)); 11582 11583 // If this is an non-standard-aligned LOAD, the first result is the loaded 11584 // value. Bitcast it to the expected result type. 11585 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) { 11586 SDValue &LdVal = NewResults[0]; 11587 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal); 11588 } 11589 11590 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 11591 DCI.CombineTo(N, NewResults); 11592 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 11593 11594 break; 11595 } 11596 return SDValue(); 11597 } 11598 11599 static SDValue PerformVLDCombine(SDNode *N, 11600 TargetLowering::DAGCombinerInfo &DCI) { 11601 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11602 return SDValue(); 11603 11604 return CombineBaseUpdate(N, DCI); 11605 } 11606 11607 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 11608 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 11609 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 11610 /// return true. 11611 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 11612 SelectionDAG &DAG = DCI.DAG; 11613 EVT VT = N->getValueType(0); 11614 // vldN-dup instructions only support 64-bit vectors for N > 1. 11615 if (!VT.is64BitVector()) 11616 return false; 11617 11618 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 11619 SDNode *VLD = N->getOperand(0).getNode(); 11620 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 11621 return false; 11622 unsigned NumVecs = 0; 11623 unsigned NewOpc = 0; 11624 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 11625 if (IntNo == Intrinsic::arm_neon_vld2lane) { 11626 NumVecs = 2; 11627 NewOpc = ARMISD::VLD2DUP; 11628 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 11629 NumVecs = 3; 11630 NewOpc = ARMISD::VLD3DUP; 11631 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 11632 NumVecs = 4; 11633 NewOpc = ARMISD::VLD4DUP; 11634 } else { 11635 return false; 11636 } 11637 11638 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 11639 // numbers match the load. 11640 unsigned VLDLaneNo = 11641 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 11642 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11643 UI != UE; ++UI) { 11644 // Ignore uses of the chain result. 11645 if (UI.getUse().getResNo() == NumVecs) 11646 continue; 11647 SDNode *User = *UI; 11648 if (User->getOpcode() != ARMISD::VDUPLANE || 11649 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 11650 return false; 11651 } 11652 11653 // Create the vldN-dup node. 11654 EVT Tys[5]; 11655 unsigned n; 11656 for (n = 0; n < NumVecs; ++n) 11657 Tys[n] = VT; 11658 Tys[n] = MVT::Other; 11659 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1)); 11660 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 11661 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 11662 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 11663 Ops, VLDMemInt->getMemoryVT(), 11664 VLDMemInt->getMemOperand()); 11665 11666 // Update the uses. 11667 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 11668 UI != UE; ++UI) { 11669 unsigned ResNo = UI.getUse().getResNo(); 11670 // Ignore uses of the chain result. 11671 if (ResNo == NumVecs) 11672 continue; 11673 SDNode *User = *UI; 11674 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 11675 } 11676 11677 // Now the vldN-lane intrinsic is dead except for its chain result. 11678 // Update uses of the chain. 11679 std::vector<SDValue> VLDDupResults; 11680 for (unsigned n = 0; n < NumVecs; ++n) 11681 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 11682 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 11683 DCI.CombineTo(VLD, VLDDupResults); 11684 11685 return true; 11686 } 11687 11688 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 11689 /// ARMISD::VDUPLANE. 11690 static SDValue PerformVDUPLANECombine(SDNode *N, 11691 TargetLowering::DAGCombinerInfo &DCI) { 11692 SDValue Op = N->getOperand(0); 11693 11694 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 11695 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 11696 if (CombineVLDDUP(N, DCI)) 11697 return SDValue(N, 0); 11698 11699 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 11700 // redundant. Ignore bit_converts for now; element sizes are checked below. 11701 while (Op.getOpcode() == ISD::BITCAST) 11702 Op = Op.getOperand(0); 11703 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 11704 return SDValue(); 11705 11706 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 11707 unsigned EltSize = Op.getScalarValueSizeInBits(); 11708 // The canonical VMOV for a zero vector uses a 32-bit element size. 11709 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11710 unsigned EltBits; 11711 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 11712 EltSize = 8; 11713 EVT VT = N->getValueType(0); 11714 if (EltSize > VT.getScalarSizeInBits()) 11715 return SDValue(); 11716 11717 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 11718 } 11719 11720 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP. 11721 static SDValue PerformVDUPCombine(SDNode *N, 11722 TargetLowering::DAGCombinerInfo &DCI) { 11723 SelectionDAG &DAG = DCI.DAG; 11724 SDValue Op = N->getOperand(0); 11725 11726 // Match VDUP(LOAD) -> VLD1DUP. 11727 // We match this pattern here rather than waiting for isel because the 11728 // transform is only legal for unindexed loads. 11729 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()); 11730 if (LD && Op.hasOneUse() && LD->isUnindexed() && 11731 LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) { 11732 SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1), 11733 DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) }; 11734 SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other); 11735 SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, 11736 Ops, LD->getMemoryVT(), 11737 LD->getMemOperand()); 11738 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1)); 11739 return VLDDup; 11740 } 11741 11742 return SDValue(); 11743 } 11744 11745 static SDValue PerformLOADCombine(SDNode *N, 11746 TargetLowering::DAGCombinerInfo &DCI) { 11747 EVT VT = N->getValueType(0); 11748 11749 // If this is a legal vector load, try to combine it into a VLD1_UPD. 11750 if (ISD::isNormalLoad(N) && VT.isVector() && 11751 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11752 return CombineBaseUpdate(N, DCI); 11753 11754 return SDValue(); 11755 } 11756 11757 /// PerformSTORECombine - Target-specific dag combine xforms for 11758 /// ISD::STORE. 11759 static SDValue PerformSTORECombine(SDNode *N, 11760 TargetLowering::DAGCombinerInfo &DCI) { 11761 StoreSDNode *St = cast<StoreSDNode>(N); 11762 if (St->isVolatile()) 11763 return SDValue(); 11764 11765 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 11766 // pack all of the elements in one place. Next, store to memory in fewer 11767 // chunks. 11768 SDValue StVal = St->getValue(); 11769 EVT VT = StVal.getValueType(); 11770 if (St->isTruncatingStore() && VT.isVector()) { 11771 SelectionDAG &DAG = DCI.DAG; 11772 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11773 EVT StVT = St->getMemoryVT(); 11774 unsigned NumElems = VT.getVectorNumElements(); 11775 assert(StVT != VT && "Cannot truncate to the same type"); 11776 unsigned FromEltSz = VT.getScalarSizeInBits(); 11777 unsigned ToEltSz = StVT.getScalarSizeInBits(); 11778 11779 // From, To sizes and ElemCount must be pow of two 11780 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 11781 11782 // We are going to use the original vector elt for storing. 11783 // Accumulated smaller vector elements must be a multiple of the store size. 11784 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 11785 11786 unsigned SizeRatio = FromEltSz / ToEltSz; 11787 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 11788 11789 // Create a type on which we perform the shuffle. 11790 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 11791 NumElems*SizeRatio); 11792 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 11793 11794 SDLoc DL(St); 11795 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 11796 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 11797 for (unsigned i = 0; i < NumElems; ++i) 11798 ShuffleVec[i] = DAG.getDataLayout().isBigEndian() 11799 ? (i + 1) * SizeRatio - 1 11800 : i * SizeRatio; 11801 11802 // Can't shuffle using an illegal type. 11803 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 11804 11805 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 11806 DAG.getUNDEF(WideVec.getValueType()), 11807 ShuffleVec); 11808 // At this point all of the data is stored at the bottom of the 11809 // register. We now need to save it to mem. 11810 11811 // Find the largest store unit 11812 MVT StoreType = MVT::i8; 11813 for (MVT Tp : MVT::integer_valuetypes()) { 11814 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 11815 StoreType = Tp; 11816 } 11817 // Didn't find a legal store type. 11818 if (!TLI.isTypeLegal(StoreType)) 11819 return SDValue(); 11820 11821 // Bitcast the original vector into a vector of store-size units 11822 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 11823 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 11824 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 11825 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 11826 SmallVector<SDValue, 8> Chains; 11827 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL, 11828 TLI.getPointerTy(DAG.getDataLayout())); 11829 SDValue BasePtr = St->getBasePtr(); 11830 11831 // Perform one or more big stores into memory. 11832 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 11833 for (unsigned I = 0; I < E; I++) { 11834 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 11835 StoreType, ShuffWide, 11836 DAG.getIntPtrConstant(I, DL)); 11837 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 11838 St->getPointerInfo(), St->getAlignment(), 11839 St->getMemOperand()->getFlags()); 11840 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 11841 Increment); 11842 Chains.push_back(Ch); 11843 } 11844 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11845 } 11846 11847 if (!ISD::isNormalStore(St)) 11848 return SDValue(); 11849 11850 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 11851 // ARM stores of arguments in the same cache line. 11852 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 11853 StVal.getNode()->hasOneUse()) { 11854 SelectionDAG &DAG = DCI.DAG; 11855 bool isBigEndian = DAG.getDataLayout().isBigEndian(); 11856 SDLoc DL(St); 11857 SDValue BasePtr = St->getBasePtr(); 11858 SDValue NewST1 = DAG.getStore( 11859 St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0), 11860 BasePtr, St->getPointerInfo(), St->getAlignment(), 11861 St->getMemOperand()->getFlags()); 11862 11863 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 11864 DAG.getConstant(4, DL, MVT::i32)); 11865 return DAG.getStore(NewST1.getValue(0), DL, 11866 StVal.getNode()->getOperand(isBigEndian ? 0 : 1), 11867 OffsetPtr, St->getPointerInfo(), 11868 std::min(4U, St->getAlignment() / 2), 11869 St->getMemOperand()->getFlags()); 11870 } 11871 11872 if (StVal.getValueType() == MVT::i64 && 11873 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 11874 11875 // Bitcast an i64 store extracted from a vector to f64. 11876 // Otherwise, the i64 value will be legalized to a pair of i32 values. 11877 SelectionDAG &DAG = DCI.DAG; 11878 SDLoc dl(StVal); 11879 SDValue IntVec = StVal.getOperand(0); 11880 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 11881 IntVec.getValueType().getVectorNumElements()); 11882 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 11883 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 11884 Vec, StVal.getOperand(1)); 11885 dl = SDLoc(N); 11886 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 11887 // Make the DAGCombiner fold the bitcasts. 11888 DCI.AddToWorklist(Vec.getNode()); 11889 DCI.AddToWorklist(ExtElt.getNode()); 11890 DCI.AddToWorklist(V.getNode()); 11891 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 11892 St->getPointerInfo(), St->getAlignment(), 11893 St->getMemOperand()->getFlags(), St->getAAInfo()); 11894 } 11895 11896 // If this is a legal vector store, try to combine it into a VST1_UPD. 11897 if (ISD::isNormalStore(N) && VT.isVector() && 11898 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11899 return CombineBaseUpdate(N, DCI); 11900 11901 return SDValue(); 11902 } 11903 11904 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 11905 /// can replace combinations of VMUL and VCVT (floating-point to integer) 11906 /// when the VMUL has a constant operand that is a power of 2. 11907 /// 11908 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11909 /// vmul.f32 d16, d17, d16 11910 /// vcvt.s32.f32 d16, d16 11911 /// becomes: 11912 /// vcvt.s32.f32 d16, d16, #3 11913 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG, 11914 const ARMSubtarget *Subtarget) { 11915 if (!Subtarget->hasNEON()) 11916 return SDValue(); 11917 11918 SDValue Op = N->getOperand(0); 11919 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 11920 Op.getOpcode() != ISD::FMUL) 11921 return SDValue(); 11922 11923 SDValue ConstVec = Op->getOperand(1); 11924 if (!isa<BuildVectorSDNode>(ConstVec)) 11925 return SDValue(); 11926 11927 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 11928 uint32_t FloatBits = FloatTy.getSizeInBits(); 11929 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 11930 uint32_t IntBits = IntTy.getSizeInBits(); 11931 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11932 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11933 // These instructions only exist converting from f32 to i32. We can handle 11934 // smaller integers by generating an extra truncate, but larger ones would 11935 // be lossy. We also can't handle more then 4 lanes, since these intructions 11936 // only support v2i32/v4i32 types. 11937 return SDValue(); 11938 } 11939 11940 BitVector UndefElements; 11941 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 11942 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 11943 if (C == -1 || C == 0 || C > 32) 11944 return SDValue(); 11945 11946 SDLoc dl(N); 11947 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 11948 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 11949 Intrinsic::arm_neon_vcvtfp2fxu; 11950 SDValue FixConv = DAG.getNode( 11951 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 11952 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0), 11953 DAG.getConstant(C, dl, MVT::i32)); 11954 11955 if (IntBits < FloatBits) 11956 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv); 11957 11958 return FixConv; 11959 } 11960 11961 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 11962 /// can replace combinations of VCVT (integer to floating-point) and VDIV 11963 /// when the VDIV has a constant operand that is a power of 2. 11964 /// 11965 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 11966 /// vcvt.f32.s32 d16, d16 11967 /// vdiv.f32 d16, d17, d16 11968 /// becomes: 11969 /// vcvt.f32.s32 d16, d16, #3 11970 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG, 11971 const ARMSubtarget *Subtarget) { 11972 if (!Subtarget->hasNEON()) 11973 return SDValue(); 11974 11975 SDValue Op = N->getOperand(0); 11976 unsigned OpOpcode = Op.getNode()->getOpcode(); 11977 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() || 11978 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 11979 return SDValue(); 11980 11981 SDValue ConstVec = N->getOperand(1); 11982 if (!isa<BuildVectorSDNode>(ConstVec)) 11983 return SDValue(); 11984 11985 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 11986 uint32_t FloatBits = FloatTy.getSizeInBits(); 11987 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 11988 uint32_t IntBits = IntTy.getSizeInBits(); 11989 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 11990 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) { 11991 // These instructions only exist converting from i32 to f32. We can handle 11992 // smaller integers by generating an extra extend, but larger ones would 11993 // be lossy. We also can't handle more then 4 lanes, since these intructions 11994 // only support v2i32/v4i32 types. 11995 return SDValue(); 11996 } 11997 11998 BitVector UndefElements; 11999 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 12000 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33); 12001 if (C == -1 || C == 0 || C > 32) 12002 return SDValue(); 12003 12004 SDLoc dl(N); 12005 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 12006 SDValue ConvInput = Op.getOperand(0); 12007 if (IntBits < FloatBits) 12008 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 12009 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 12010 ConvInput); 12011 12012 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 12013 Intrinsic::arm_neon_vcvtfxu2fp; 12014 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, 12015 Op.getValueType(), 12016 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), 12017 ConvInput, DAG.getConstant(C, dl, MVT::i32)); 12018 } 12019 12020 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 12021 /// operand of a vector shift operation, where all the elements of the 12022 /// build_vector must have the same constant integer value. 12023 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 12024 // Ignore bit_converts. 12025 while (Op.getOpcode() == ISD::BITCAST) 12026 Op = Op.getOperand(0); 12027 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 12028 APInt SplatBits, SplatUndef; 12029 unsigned SplatBitSize; 12030 bool HasAnyUndefs; 12031 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 12032 HasAnyUndefs, ElementBits) || 12033 SplatBitSize > ElementBits) 12034 return false; 12035 Cnt = SplatBits.getSExtValue(); 12036 return true; 12037 } 12038 12039 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 12040 /// operand of a vector shift left operation. That value must be in the range: 12041 /// 0 <= Value < ElementBits for a left shift; or 12042 /// 0 <= Value <= ElementBits for a long left shift. 12043 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 12044 assert(VT.isVector() && "vector shift count is not a vector type"); 12045 int64_t ElementBits = VT.getScalarSizeInBits(); 12046 if (! getVShiftImm(Op, ElementBits, Cnt)) 12047 return false; 12048 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 12049 } 12050 12051 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 12052 /// operand of a vector shift right operation. For a shift opcode, the value 12053 /// is positive, but for an intrinsic the value count must be negative. The 12054 /// absolute value must be in the range: 12055 /// 1 <= |Value| <= ElementBits for a right shift; or 12056 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 12057 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 12058 int64_t &Cnt) { 12059 assert(VT.isVector() && "vector shift count is not a vector type"); 12060 int64_t ElementBits = VT.getScalarSizeInBits(); 12061 if (! getVShiftImm(Op, ElementBits, Cnt)) 12062 return false; 12063 if (!isIntrinsic) 12064 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 12065 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) { 12066 Cnt = -Cnt; 12067 return true; 12068 } 12069 return false; 12070 } 12071 12072 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 12073 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 12074 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12075 switch (IntNo) { 12076 default: 12077 // Don't do anything for most intrinsics. 12078 break; 12079 12080 // Vector shifts: check for immediate versions and lower them. 12081 // Note: This is done during DAG combining instead of DAG legalizing because 12082 // the build_vectors for 64-bit vector element shift counts are generally 12083 // not legal, and it is hard to see their values after they get legalized to 12084 // loads from a constant pool. 12085 case Intrinsic::arm_neon_vshifts: 12086 case Intrinsic::arm_neon_vshiftu: 12087 case Intrinsic::arm_neon_vrshifts: 12088 case Intrinsic::arm_neon_vrshiftu: 12089 case Intrinsic::arm_neon_vrshiftn: 12090 case Intrinsic::arm_neon_vqshifts: 12091 case Intrinsic::arm_neon_vqshiftu: 12092 case Intrinsic::arm_neon_vqshiftsu: 12093 case Intrinsic::arm_neon_vqshiftns: 12094 case Intrinsic::arm_neon_vqshiftnu: 12095 case Intrinsic::arm_neon_vqshiftnsu: 12096 case Intrinsic::arm_neon_vqrshiftns: 12097 case Intrinsic::arm_neon_vqrshiftnu: 12098 case Intrinsic::arm_neon_vqrshiftnsu: { 12099 EVT VT = N->getOperand(1).getValueType(); 12100 int64_t Cnt; 12101 unsigned VShiftOpc = 0; 12102 12103 switch (IntNo) { 12104 case Intrinsic::arm_neon_vshifts: 12105 case Intrinsic::arm_neon_vshiftu: 12106 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 12107 VShiftOpc = ARMISD::VSHL; 12108 break; 12109 } 12110 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 12111 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 12112 ARMISD::VSHRs : ARMISD::VSHRu); 12113 break; 12114 } 12115 return SDValue(); 12116 12117 case Intrinsic::arm_neon_vrshifts: 12118 case Intrinsic::arm_neon_vrshiftu: 12119 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 12120 break; 12121 return SDValue(); 12122 12123 case Intrinsic::arm_neon_vqshifts: 12124 case Intrinsic::arm_neon_vqshiftu: 12125 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12126 break; 12127 return SDValue(); 12128 12129 case Intrinsic::arm_neon_vqshiftsu: 12130 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 12131 break; 12132 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 12133 12134 case Intrinsic::arm_neon_vrshiftn: 12135 case Intrinsic::arm_neon_vqshiftns: 12136 case Intrinsic::arm_neon_vqshiftnu: 12137 case Intrinsic::arm_neon_vqshiftnsu: 12138 case Intrinsic::arm_neon_vqrshiftns: 12139 case Intrinsic::arm_neon_vqrshiftnu: 12140 case Intrinsic::arm_neon_vqrshiftnsu: 12141 // Narrowing shifts require an immediate right shift. 12142 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 12143 break; 12144 llvm_unreachable("invalid shift count for narrowing vector shift " 12145 "intrinsic"); 12146 12147 default: 12148 llvm_unreachable("unhandled vector shift"); 12149 } 12150 12151 switch (IntNo) { 12152 case Intrinsic::arm_neon_vshifts: 12153 case Intrinsic::arm_neon_vshiftu: 12154 // Opcode already set above. 12155 break; 12156 case Intrinsic::arm_neon_vrshifts: 12157 VShiftOpc = ARMISD::VRSHRs; break; 12158 case Intrinsic::arm_neon_vrshiftu: 12159 VShiftOpc = ARMISD::VRSHRu; break; 12160 case Intrinsic::arm_neon_vrshiftn: 12161 VShiftOpc = ARMISD::VRSHRN; break; 12162 case Intrinsic::arm_neon_vqshifts: 12163 VShiftOpc = ARMISD::VQSHLs; break; 12164 case Intrinsic::arm_neon_vqshiftu: 12165 VShiftOpc = ARMISD::VQSHLu; break; 12166 case Intrinsic::arm_neon_vqshiftsu: 12167 VShiftOpc = ARMISD::VQSHLsu; break; 12168 case Intrinsic::arm_neon_vqshiftns: 12169 VShiftOpc = ARMISD::VQSHRNs; break; 12170 case Intrinsic::arm_neon_vqshiftnu: 12171 VShiftOpc = ARMISD::VQSHRNu; break; 12172 case Intrinsic::arm_neon_vqshiftnsu: 12173 VShiftOpc = ARMISD::VQSHRNsu; break; 12174 case Intrinsic::arm_neon_vqrshiftns: 12175 VShiftOpc = ARMISD::VQRSHRNs; break; 12176 case Intrinsic::arm_neon_vqrshiftnu: 12177 VShiftOpc = ARMISD::VQRSHRNu; break; 12178 case Intrinsic::arm_neon_vqrshiftnsu: 12179 VShiftOpc = ARMISD::VQRSHRNsu; break; 12180 } 12181 12182 SDLoc dl(N); 12183 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12184 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32)); 12185 } 12186 12187 case Intrinsic::arm_neon_vshiftins: { 12188 EVT VT = N->getOperand(1).getValueType(); 12189 int64_t Cnt; 12190 unsigned VShiftOpc = 0; 12191 12192 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 12193 VShiftOpc = ARMISD::VSLI; 12194 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 12195 VShiftOpc = ARMISD::VSRI; 12196 else { 12197 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 12198 } 12199 12200 SDLoc dl(N); 12201 return DAG.getNode(VShiftOpc, dl, N->getValueType(0), 12202 N->getOperand(1), N->getOperand(2), 12203 DAG.getConstant(Cnt, dl, MVT::i32)); 12204 } 12205 12206 case Intrinsic::arm_neon_vqrshifts: 12207 case Intrinsic::arm_neon_vqrshiftu: 12208 // No immediate versions of these to check for. 12209 break; 12210 } 12211 12212 return SDValue(); 12213 } 12214 12215 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 12216 /// lowers them. As with the vector shift intrinsics, this is done during DAG 12217 /// combining instead of DAG legalizing because the build_vectors for 64-bit 12218 /// vector element shift counts are generally not legal, and it is hard to see 12219 /// their values after they get legalized to loads from a constant pool. 12220 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 12221 const ARMSubtarget *ST) { 12222 EVT VT = N->getValueType(0); 12223 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 12224 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 12225 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 12226 SDValue N1 = N->getOperand(1); 12227 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 12228 SDValue N0 = N->getOperand(0); 12229 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 12230 DAG.MaskedValueIsZero(N0.getOperand(0), 12231 APInt::getHighBitsSet(32, 16))) 12232 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 12233 } 12234 } 12235 12236 // Nothing to be done for scalar shifts. 12237 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12238 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 12239 return SDValue(); 12240 12241 assert(ST->hasNEON() && "unexpected vector shift"); 12242 int64_t Cnt; 12243 12244 switch (N->getOpcode()) { 12245 default: llvm_unreachable("unexpected shift opcode"); 12246 12247 case ISD::SHL: 12248 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) { 12249 SDLoc dl(N); 12250 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0), 12251 DAG.getConstant(Cnt, dl, MVT::i32)); 12252 } 12253 break; 12254 12255 case ISD::SRA: 12256 case ISD::SRL: 12257 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 12258 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 12259 ARMISD::VSHRs : ARMISD::VSHRu); 12260 SDLoc dl(N); 12261 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), 12262 DAG.getConstant(Cnt, dl, MVT::i32)); 12263 } 12264 } 12265 return SDValue(); 12266 } 12267 12268 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 12269 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 12270 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 12271 const ARMSubtarget *ST) { 12272 SDValue N0 = N->getOperand(0); 12273 12274 // Check for sign- and zero-extensions of vector extract operations of 8- 12275 // and 16-bit vector elements. NEON supports these directly. They are 12276 // handled during DAG combining because type legalization will promote them 12277 // to 32-bit types and it is messy to recognize the operations after that. 12278 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12279 SDValue Vec = N0.getOperand(0); 12280 SDValue Lane = N0.getOperand(1); 12281 EVT VT = N->getValueType(0); 12282 EVT EltVT = N0.getValueType(); 12283 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12284 12285 if (VT == MVT::i32 && 12286 (EltVT == MVT::i8 || EltVT == MVT::i16) && 12287 TLI.isTypeLegal(Vec.getValueType()) && 12288 isa<ConstantSDNode>(Lane)) { 12289 12290 unsigned Opc = 0; 12291 switch (N->getOpcode()) { 12292 default: llvm_unreachable("unexpected opcode"); 12293 case ISD::SIGN_EXTEND: 12294 Opc = ARMISD::VGETLANEs; 12295 break; 12296 case ISD::ZERO_EXTEND: 12297 case ISD::ANY_EXTEND: 12298 Opc = ARMISD::VGETLANEu; 12299 break; 12300 } 12301 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 12302 } 12303 } 12304 12305 return SDValue(); 12306 } 12307 12308 static const APInt *isPowerOf2Constant(SDValue V) { 12309 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 12310 if (!C) 12311 return nullptr; 12312 const APInt *CV = &C->getAPIntValue(); 12313 return CV->isPowerOf2() ? CV : nullptr; 12314 } 12315 12316 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const { 12317 // If we have a CMOV, OR and AND combination such as: 12318 // if (x & CN) 12319 // y |= CM; 12320 // 12321 // And: 12322 // * CN is a single bit; 12323 // * All bits covered by CM are known zero in y 12324 // 12325 // Then we can convert this into a sequence of BFI instructions. This will 12326 // always be a win if CM is a single bit, will always be no worse than the 12327 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is 12328 // three bits (due to the extra IT instruction). 12329 12330 SDValue Op0 = CMOV->getOperand(0); 12331 SDValue Op1 = CMOV->getOperand(1); 12332 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2)); 12333 auto CC = CCNode->getAPIntValue().getLimitedValue(); 12334 SDValue CmpZ = CMOV->getOperand(4); 12335 12336 // The compare must be against zero. 12337 if (!isNullConstant(CmpZ->getOperand(1))) 12338 return SDValue(); 12339 12340 assert(CmpZ->getOpcode() == ARMISD::CMPZ); 12341 SDValue And = CmpZ->getOperand(0); 12342 if (And->getOpcode() != ISD::AND) 12343 return SDValue(); 12344 const APInt *AndC = isPowerOf2Constant(And->getOperand(1)); 12345 if (!AndC) 12346 return SDValue(); 12347 SDValue X = And->getOperand(0); 12348 12349 if (CC == ARMCC::EQ) { 12350 // We're performing an "equal to zero" compare. Swap the operands so we 12351 // canonicalize on a "not equal to zero" compare. 12352 std::swap(Op0, Op1); 12353 } else { 12354 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?"); 12355 } 12356 12357 if (Op1->getOpcode() != ISD::OR) 12358 return SDValue(); 12359 12360 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1)); 12361 if (!OrC) 12362 return SDValue(); 12363 SDValue Y = Op1->getOperand(0); 12364 12365 if (Op0 != Y) 12366 return SDValue(); 12367 12368 // Now, is it profitable to continue? 12369 APInt OrCI = OrC->getAPIntValue(); 12370 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2; 12371 if (OrCI.countPopulation() > Heuristic) 12372 return SDValue(); 12373 12374 // Lastly, can we determine that the bits defined by OrCI 12375 // are zero in Y? 12376 KnownBits Known; 12377 DAG.computeKnownBits(Y, Known); 12378 if ((OrCI & Known.Zero) != OrCI) 12379 return SDValue(); 12380 12381 // OK, we can do the combine. 12382 SDValue V = Y; 12383 SDLoc dl(X); 12384 EVT VT = X.getValueType(); 12385 unsigned BitInX = AndC->logBase2(); 12386 12387 if (BitInX != 0) { 12388 // We must shift X first. 12389 X = DAG.getNode(ISD::SRL, dl, VT, X, 12390 DAG.getConstant(BitInX, dl, VT)); 12391 } 12392 12393 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits(); 12394 BitInY < NumActiveBits; ++BitInY) { 12395 if (OrCI[BitInY] == 0) 12396 continue; 12397 APInt Mask(VT.getSizeInBits(), 0); 12398 Mask.setBit(BitInY); 12399 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X, 12400 // Confusingly, the operand is an *inverted* mask. 12401 DAG.getConstant(~Mask, dl, VT)); 12402 } 12403 12404 return V; 12405 } 12406 12407 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND. 12408 SDValue 12409 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const { 12410 SDValue Cmp = N->getOperand(4); 12411 if (Cmp.getOpcode() != ARMISD::CMPZ) 12412 // Only looking at NE cases. 12413 return SDValue(); 12414 12415 EVT VT = N->getValueType(0); 12416 SDLoc dl(N); 12417 SDValue LHS = Cmp.getOperand(0); 12418 SDValue RHS = Cmp.getOperand(1); 12419 SDValue Chain = N->getOperand(0); 12420 SDValue BB = N->getOperand(1); 12421 SDValue ARMcc = N->getOperand(2); 12422 ARMCC::CondCodes CC = 12423 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12424 12425 // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0)) 12426 // -> (brcond Chain BB CC CPSR Cmp) 12427 if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() && 12428 LHS->getOperand(0)->getOpcode() == ARMISD::CMOV && 12429 LHS->getOperand(0)->hasOneUse()) { 12430 auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0)); 12431 auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1)); 12432 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12433 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12434 if ((LHS00C && LHS00C->getZExtValue() == 0) && 12435 (LHS01C && LHS01C->getZExtValue() == 1) && 12436 (LHS1C && LHS1C->getZExtValue() == 1) && 12437 (RHSC && RHSC->getZExtValue() == 0)) { 12438 return DAG.getNode( 12439 ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2), 12440 LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4)); 12441 } 12442 } 12443 12444 return SDValue(); 12445 } 12446 12447 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 12448 SDValue 12449 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 12450 SDValue Cmp = N->getOperand(4); 12451 if (Cmp.getOpcode() != ARMISD::CMPZ) 12452 // Only looking at EQ and NE cases. 12453 return SDValue(); 12454 12455 EVT VT = N->getValueType(0); 12456 SDLoc dl(N); 12457 SDValue LHS = Cmp.getOperand(0); 12458 SDValue RHS = Cmp.getOperand(1); 12459 SDValue FalseVal = N->getOperand(0); 12460 SDValue TrueVal = N->getOperand(1); 12461 SDValue ARMcc = N->getOperand(2); 12462 ARMCC::CondCodes CC = 12463 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 12464 12465 // BFI is only available on V6T2+. 12466 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) { 12467 SDValue R = PerformCMOVToBFICombine(N, DAG); 12468 if (R) 12469 return R; 12470 } 12471 12472 // Simplify 12473 // mov r1, r0 12474 // cmp r1, x 12475 // mov r0, y 12476 // moveq r0, x 12477 // to 12478 // cmp r0, x 12479 // movne r0, y 12480 // 12481 // mov r1, r0 12482 // cmp r1, x 12483 // mov r0, x 12484 // movne r0, y 12485 // to 12486 // cmp r0, x 12487 // movne r0, y 12488 /// FIXME: Turn this into a target neutral optimization? 12489 SDValue Res; 12490 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 12491 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 12492 N->getOperand(3), Cmp); 12493 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 12494 SDValue ARMcc; 12495 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 12496 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 12497 N->getOperand(3), NewCmp); 12498 } 12499 12500 // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0)) 12501 // -> (cmov F T CC CPSR Cmp) 12502 if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) { 12503 auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)); 12504 auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 12505 auto *RHSC = dyn_cast<ConstantSDNode>(RHS); 12506 if ((LHS0C && LHS0C->getZExtValue() == 0) && 12507 (LHS1C && LHS1C->getZExtValue() == 1) && 12508 (RHSC && RHSC->getZExtValue() == 0)) { 12509 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 12510 LHS->getOperand(2), LHS->getOperand(3), 12511 LHS->getOperand(4)); 12512 } 12513 } 12514 12515 if (Res.getNode()) { 12516 KnownBits Known; 12517 DAG.computeKnownBits(SDValue(N,0), Known); 12518 // Capture demanded bits information that would be otherwise lost. 12519 if (Known.Zero == 0xfffffffe) 12520 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12521 DAG.getValueType(MVT::i1)); 12522 else if (Known.Zero == 0xffffff00) 12523 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12524 DAG.getValueType(MVT::i8)); 12525 else if (Known.Zero == 0xffff0000) 12526 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 12527 DAG.getValueType(MVT::i16)); 12528 } 12529 12530 return Res; 12531 } 12532 12533 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 12534 DAGCombinerInfo &DCI) const { 12535 switch (N->getOpcode()) { 12536 default: break; 12537 case ARMISD::ADDE: return PerformADDECombine(N, DCI, Subtarget); 12538 case ARMISD::UMLAL: return PerformUMLALCombine(N, DCI.DAG, Subtarget); 12539 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 12540 case ISD::SUB: return PerformSUBCombine(N, DCI); 12541 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 12542 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 12543 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 12544 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 12545 case ARMISD::ADDC: 12546 case ARMISD::SUBC: return PerformAddcSubcCombine(N, DCI, Subtarget); 12547 case ARMISD::SUBE: return PerformAddeSubeCombine(N, DCI, Subtarget); 12548 case ARMISD::BFI: return PerformBFICombine(N, DCI); 12549 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget); 12550 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 12551 case ISD::STORE: return PerformSTORECombine(N, DCI); 12552 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget); 12553 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 12554 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 12555 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 12556 case ARMISD::VDUP: return PerformVDUPCombine(N, DCI); 12557 case ISD::FP_TO_SINT: 12558 case ISD::FP_TO_UINT: 12559 return PerformVCVTCombine(N, DCI.DAG, Subtarget); 12560 case ISD::FDIV: 12561 return PerformVDIVCombine(N, DCI.DAG, Subtarget); 12562 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 12563 case ISD::SHL: 12564 case ISD::SRA: 12565 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 12566 case ISD::SIGN_EXTEND: 12567 case ISD::ZERO_EXTEND: 12568 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 12569 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 12570 case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG); 12571 case ISD::LOAD: return PerformLOADCombine(N, DCI); 12572 case ARMISD::VLD1DUP: 12573 case ARMISD::VLD2DUP: 12574 case ARMISD::VLD3DUP: 12575 case ARMISD::VLD4DUP: 12576 return PerformVLDCombine(N, DCI); 12577 case ARMISD::BUILD_VECTOR: 12578 return PerformARMBUILD_VECTORCombine(N, DCI); 12579 case ARMISD::SMULWB: { 12580 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12581 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12582 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12583 return SDValue(); 12584 break; 12585 } 12586 case ARMISD::SMULWT: { 12587 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12588 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12589 if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)) 12590 return SDValue(); 12591 break; 12592 } 12593 case ARMISD::SMLALBB: { 12594 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12595 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16); 12596 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12597 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12598 return SDValue(); 12599 break; 12600 } 12601 case ARMISD::SMLALBT: { 12602 unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits(); 12603 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12604 unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits(); 12605 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12606 if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) || 12607 (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI))) 12608 return SDValue(); 12609 break; 12610 } 12611 case ARMISD::SMLALTB: { 12612 unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits(); 12613 APInt HighMask = APInt::getHighBitsSet(HighWidth, 16); 12614 unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits(); 12615 APInt LowMask = APInt::getLowBitsSet(LowWidth, 16); 12616 if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) || 12617 (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI))) 12618 return SDValue(); 12619 break; 12620 } 12621 case ARMISD::SMLALTT: { 12622 unsigned BitWidth = N->getValueType(0).getSizeInBits(); 12623 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16); 12624 if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) || 12625 (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))) 12626 return SDValue(); 12627 break; 12628 } 12629 case ISD::INTRINSIC_VOID: 12630 case ISD::INTRINSIC_W_CHAIN: 12631 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12632 case Intrinsic::arm_neon_vld1: 12633 case Intrinsic::arm_neon_vld2: 12634 case Intrinsic::arm_neon_vld3: 12635 case Intrinsic::arm_neon_vld4: 12636 case Intrinsic::arm_neon_vld2lane: 12637 case Intrinsic::arm_neon_vld3lane: 12638 case Intrinsic::arm_neon_vld4lane: 12639 case Intrinsic::arm_neon_vst1: 12640 case Intrinsic::arm_neon_vst2: 12641 case Intrinsic::arm_neon_vst3: 12642 case Intrinsic::arm_neon_vst4: 12643 case Intrinsic::arm_neon_vst2lane: 12644 case Intrinsic::arm_neon_vst3lane: 12645 case Intrinsic::arm_neon_vst4lane: 12646 return PerformVLDCombine(N, DCI); 12647 default: break; 12648 } 12649 break; 12650 } 12651 return SDValue(); 12652 } 12653 12654 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 12655 EVT VT) const { 12656 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 12657 } 12658 12659 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 12660 unsigned, 12661 unsigned, 12662 bool *Fast) const { 12663 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 12664 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 12665 12666 switch (VT.getSimpleVT().SimpleTy) { 12667 default: 12668 return false; 12669 case MVT::i8: 12670 case MVT::i16: 12671 case MVT::i32: { 12672 // Unaligned access can use (for example) LRDB, LRDH, LDR 12673 if (AllowsUnaligned) { 12674 if (Fast) 12675 *Fast = Subtarget->hasV7Ops(); 12676 return true; 12677 } 12678 return false; 12679 } 12680 case MVT::f64: 12681 case MVT::v2f64: { 12682 // For any little-endian targets with neon, we can support unaligned ld/st 12683 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 12684 // A big-endian target may also explicitly support unaligned accesses 12685 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) { 12686 if (Fast) 12687 *Fast = true; 12688 return true; 12689 } 12690 return false; 12691 } 12692 } 12693 } 12694 12695 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 12696 unsigned AlignCheck) { 12697 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 12698 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 12699 } 12700 12701 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 12702 unsigned DstAlign, unsigned SrcAlign, 12703 bool IsMemset, bool ZeroMemset, 12704 bool MemcpyStrSrc, 12705 MachineFunction &MF) const { 12706 const Function &F = MF.getFunction(); 12707 12708 // See if we can use NEON instructions for this... 12709 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() && 12710 !F.hasFnAttribute(Attribute::NoImplicitFloat)) { 12711 bool Fast; 12712 if (Size >= 16 && 12713 (memOpAlign(SrcAlign, DstAlign, 16) || 12714 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) { 12715 return MVT::v2f64; 12716 } else if (Size >= 8 && 12717 (memOpAlign(SrcAlign, DstAlign, 8) || 12718 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) && 12719 Fast))) { 12720 return MVT::f64; 12721 } 12722 } 12723 12724 // Let the target-independent logic figure it out. 12725 return MVT::Other; 12726 } 12727 12728 // 64-bit integers are split into their high and low parts and held in two 12729 // different registers, so the trunc is free since the low register can just 12730 // be used. 12731 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 12732 if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 12733 return false; 12734 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 12735 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 12736 return (SrcBits == 64 && DestBits == 32); 12737 } 12738 12739 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 12740 if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() || 12741 !DstVT.isInteger()) 12742 return false; 12743 unsigned SrcBits = SrcVT.getSizeInBits(); 12744 unsigned DestBits = DstVT.getSizeInBits(); 12745 return (SrcBits == 64 && DestBits == 32); 12746 } 12747 12748 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12749 if (Val.getOpcode() != ISD::LOAD) 12750 return false; 12751 12752 EVT VT1 = Val.getValueType(); 12753 if (!VT1.isSimple() || !VT1.isInteger() || 12754 !VT2.isSimple() || !VT2.isInteger()) 12755 return false; 12756 12757 switch (VT1.getSimpleVT().SimpleTy) { 12758 default: break; 12759 case MVT::i1: 12760 case MVT::i8: 12761 case MVT::i16: 12762 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 12763 return true; 12764 } 12765 12766 return false; 12767 } 12768 12769 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 12770 EVT VT = ExtVal.getValueType(); 12771 12772 if (!isTypeLegal(VT)) 12773 return false; 12774 12775 // Don't create a loadext if we can fold the extension into a wide/long 12776 // instruction. 12777 // If there's more than one user instruction, the loadext is desirable no 12778 // matter what. There can be two uses by the same instruction. 12779 if (ExtVal->use_empty() || 12780 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode())) 12781 return true; 12782 12783 SDNode *U = *ExtVal->use_begin(); 12784 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB || 12785 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL)) 12786 return false; 12787 12788 return true; 12789 } 12790 12791 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 12792 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12793 return false; 12794 12795 if (!isTypeLegal(EVT::getEVT(Ty1))) 12796 return false; 12797 12798 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 12799 12800 // Assuming the caller doesn't have a zeroext or signext return parameter, 12801 // truncation all the way down to i1 is valid. 12802 return true; 12803 } 12804 12805 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL, 12806 const AddrMode &AM, Type *Ty, 12807 unsigned AS) const { 12808 if (isLegalAddressingMode(DL, AM, Ty, AS)) { 12809 if (Subtarget->hasFPAO()) 12810 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster 12811 return 0; 12812 } 12813 return -1; 12814 } 12815 12816 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 12817 if (V < 0) 12818 return false; 12819 12820 unsigned Scale = 1; 12821 switch (VT.getSimpleVT().SimpleTy) { 12822 default: return false; 12823 case MVT::i1: 12824 case MVT::i8: 12825 // Scale == 1; 12826 break; 12827 case MVT::i16: 12828 // Scale == 2; 12829 Scale = 2; 12830 break; 12831 case MVT::i32: 12832 // Scale == 4; 12833 Scale = 4; 12834 break; 12835 } 12836 12837 if ((V & (Scale - 1)) != 0) 12838 return false; 12839 V /= Scale; 12840 return V == (V & ((1LL << 5) - 1)); 12841 } 12842 12843 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 12844 const ARMSubtarget *Subtarget) { 12845 bool isNeg = false; 12846 if (V < 0) { 12847 isNeg = true; 12848 V = - V; 12849 } 12850 12851 switch (VT.getSimpleVT().SimpleTy) { 12852 default: return false; 12853 case MVT::i1: 12854 case MVT::i8: 12855 case MVT::i16: 12856 case MVT::i32: 12857 // + imm12 or - imm8 12858 if (isNeg) 12859 return V == (V & ((1LL << 8) - 1)); 12860 return V == (V & ((1LL << 12) - 1)); 12861 case MVT::f32: 12862 case MVT::f64: 12863 // Same as ARM mode. FIXME: NEON? 12864 if (!Subtarget->hasVFP2()) 12865 return false; 12866 if ((V & 3) != 0) 12867 return false; 12868 V >>= 2; 12869 return V == (V & ((1LL << 8) - 1)); 12870 } 12871 } 12872 12873 /// isLegalAddressImmediate - Return true if the integer value can be used 12874 /// as the offset of the target addressing mode for load / store of the 12875 /// given type. 12876 static bool isLegalAddressImmediate(int64_t V, EVT VT, 12877 const ARMSubtarget *Subtarget) { 12878 if (V == 0) 12879 return true; 12880 12881 if (!VT.isSimple()) 12882 return false; 12883 12884 if (Subtarget->isThumb1Only()) 12885 return isLegalT1AddressImmediate(V, VT); 12886 else if (Subtarget->isThumb2()) 12887 return isLegalT2AddressImmediate(V, VT, Subtarget); 12888 12889 // ARM mode. 12890 if (V < 0) 12891 V = - V; 12892 switch (VT.getSimpleVT().SimpleTy) { 12893 default: return false; 12894 case MVT::i1: 12895 case MVT::i8: 12896 case MVT::i32: 12897 // +- imm12 12898 return V == (V & ((1LL << 12) - 1)); 12899 case MVT::i16: 12900 // +- imm8 12901 return V == (V & ((1LL << 8) - 1)); 12902 case MVT::f32: 12903 case MVT::f64: 12904 if (!Subtarget->hasVFP2()) // FIXME: NEON? 12905 return false; 12906 if ((V & 3) != 0) 12907 return false; 12908 V >>= 2; 12909 return V == (V & ((1LL << 8) - 1)); 12910 } 12911 } 12912 12913 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 12914 EVT VT) const { 12915 int Scale = AM.Scale; 12916 if (Scale < 0) 12917 return false; 12918 12919 switch (VT.getSimpleVT().SimpleTy) { 12920 default: return false; 12921 case MVT::i1: 12922 case MVT::i8: 12923 case MVT::i16: 12924 case MVT::i32: 12925 if (Scale == 1) 12926 return true; 12927 // r + r << imm 12928 Scale = Scale & ~1; 12929 return Scale == 2 || Scale == 4 || Scale == 8; 12930 case MVT::i64: 12931 // FIXME: What are we trying to model here? ldrd doesn't have an r + r 12932 // version in Thumb mode. 12933 // r + r 12934 if (Scale == 1) 12935 return true; 12936 // r * 2 (this can be lowered to r + r). 12937 if (!AM.HasBaseReg && Scale == 2) 12938 return true; 12939 return false; 12940 case MVT::isVoid: 12941 // Note, we allow "void" uses (basically, uses that aren't loads or 12942 // stores), because arm allows folding a scale into many arithmetic 12943 // operations. This should be made more precise and revisited later. 12944 12945 // Allow r << imm, but the imm has to be a multiple of two. 12946 if (Scale & 1) return false; 12947 return isPowerOf2_32(Scale); 12948 } 12949 } 12950 12951 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM, 12952 EVT VT) const { 12953 const int Scale = AM.Scale; 12954 12955 // Negative scales are not supported in Thumb1. 12956 if (Scale < 0) 12957 return false; 12958 12959 // Thumb1 addressing modes do not support register scaling excepting the 12960 // following cases: 12961 // 1. Scale == 1 means no scaling. 12962 // 2. Scale == 2 this can be lowered to r + r if there is no base register. 12963 return (Scale == 1) || (!AM.HasBaseReg && Scale == 2); 12964 } 12965 12966 /// isLegalAddressingMode - Return true if the addressing mode represented 12967 /// by AM is legal for this target, for a load/store of the specified type. 12968 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL, 12969 const AddrMode &AM, Type *Ty, 12970 unsigned AS, Instruction *I) const { 12971 EVT VT = getValueType(DL, Ty, true); 12972 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 12973 return false; 12974 12975 // Can never fold addr of global into load/store. 12976 if (AM.BaseGV) 12977 return false; 12978 12979 switch (AM.Scale) { 12980 case 0: // no scale reg, must be "r+i" or "r", or "i". 12981 break; 12982 default: 12983 // ARM doesn't support any R+R*scale+imm addr modes. 12984 if (AM.BaseOffs) 12985 return false; 12986 12987 if (!VT.isSimple()) 12988 return false; 12989 12990 if (Subtarget->isThumb1Only()) 12991 return isLegalT1ScaledAddressingMode(AM, VT); 12992 12993 if (Subtarget->isThumb2()) 12994 return isLegalT2ScaledAddressingMode(AM, VT); 12995 12996 int Scale = AM.Scale; 12997 switch (VT.getSimpleVT().SimpleTy) { 12998 default: return false; 12999 case MVT::i1: 13000 case MVT::i8: 13001 case MVT::i32: 13002 if (Scale < 0) Scale = -Scale; 13003 if (Scale == 1) 13004 return true; 13005 // r + r << imm 13006 return isPowerOf2_32(Scale & ~1); 13007 case MVT::i16: 13008 case MVT::i64: 13009 // r +/- r 13010 if (Scale == 1 || (AM.HasBaseReg && Scale == -1)) 13011 return true; 13012 // r * 2 (this can be lowered to r + r). 13013 if (!AM.HasBaseReg && Scale == 2) 13014 return true; 13015 return false; 13016 13017 case MVT::isVoid: 13018 // Note, we allow "void" uses (basically, uses that aren't loads or 13019 // stores), because arm allows folding a scale into many arithmetic 13020 // operations. This should be made more precise and revisited later. 13021 13022 // Allow r << imm, but the imm has to be a multiple of two. 13023 if (Scale & 1) return false; 13024 return isPowerOf2_32(Scale); 13025 } 13026 } 13027 return true; 13028 } 13029 13030 /// isLegalICmpImmediate - Return true if the specified immediate is legal 13031 /// icmp immediate, that is the target has icmp instructions which can compare 13032 /// a register against the immediate without having to materialize the 13033 /// immediate into a register. 13034 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13035 // Thumb2 and ARM modes can use cmn for negative immediates. 13036 if (!Subtarget->isThumb()) 13037 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1; 13038 if (Subtarget->isThumb2()) 13039 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1; 13040 // Thumb1 doesn't have cmn, and only 8-bit immediates. 13041 return Imm >= 0 && Imm <= 255; 13042 } 13043 13044 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 13045 /// *or sub* immediate, that is the target has add or sub instructions which can 13046 /// add a register with the immediate without having to materialize the 13047 /// immediate into a register. 13048 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13049 // Same encoding for add/sub, just flip the sign. 13050 int64_t AbsImm = std::abs(Imm); 13051 if (!Subtarget->isThumb()) 13052 return ARM_AM::getSOImmVal(AbsImm) != -1; 13053 if (Subtarget->isThumb2()) 13054 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 13055 // Thumb1 only has 8-bit unsigned immediate. 13056 return AbsImm >= 0 && AbsImm <= 255; 13057 } 13058 13059 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 13060 bool isSEXTLoad, SDValue &Base, 13061 SDValue &Offset, bool &isInc, 13062 SelectionDAG &DAG) { 13063 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13064 return false; 13065 13066 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 13067 // AddressingMode 3 13068 Base = Ptr->getOperand(0); 13069 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13070 int RHSC = (int)RHS->getZExtValue(); 13071 if (RHSC < 0 && RHSC > -256) { 13072 assert(Ptr->getOpcode() == ISD::ADD); 13073 isInc = false; 13074 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13075 return true; 13076 } 13077 } 13078 isInc = (Ptr->getOpcode() == ISD::ADD); 13079 Offset = Ptr->getOperand(1); 13080 return true; 13081 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 13082 // AddressingMode 2 13083 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13084 int RHSC = (int)RHS->getZExtValue(); 13085 if (RHSC < 0 && RHSC > -0x1000) { 13086 assert(Ptr->getOpcode() == ISD::ADD); 13087 isInc = false; 13088 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13089 Base = Ptr->getOperand(0); 13090 return true; 13091 } 13092 } 13093 13094 if (Ptr->getOpcode() == ISD::ADD) { 13095 isInc = true; 13096 ARM_AM::ShiftOpc ShOpcVal= 13097 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 13098 if (ShOpcVal != ARM_AM::no_shift) { 13099 Base = Ptr->getOperand(1); 13100 Offset = Ptr->getOperand(0); 13101 } else { 13102 Base = Ptr->getOperand(0); 13103 Offset = Ptr->getOperand(1); 13104 } 13105 return true; 13106 } 13107 13108 isInc = (Ptr->getOpcode() == ISD::ADD); 13109 Base = Ptr->getOperand(0); 13110 Offset = Ptr->getOperand(1); 13111 return true; 13112 } 13113 13114 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 13115 return false; 13116 } 13117 13118 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 13119 bool isSEXTLoad, SDValue &Base, 13120 SDValue &Offset, bool &isInc, 13121 SelectionDAG &DAG) { 13122 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 13123 return false; 13124 13125 Base = Ptr->getOperand(0); 13126 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 13127 int RHSC = (int)RHS->getZExtValue(); 13128 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 13129 assert(Ptr->getOpcode() == ISD::ADD); 13130 isInc = false; 13131 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13132 return true; 13133 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 13134 isInc = Ptr->getOpcode() == ISD::ADD; 13135 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0)); 13136 return true; 13137 } 13138 } 13139 13140 return false; 13141 } 13142 13143 /// getPreIndexedAddressParts - returns true by value, base pointer and 13144 /// offset pointer and addressing mode by reference if the node's address 13145 /// can be legally represented as pre-indexed load / store address. 13146 bool 13147 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 13148 SDValue &Offset, 13149 ISD::MemIndexedMode &AM, 13150 SelectionDAG &DAG) const { 13151 if (Subtarget->isThumb1Only()) 13152 return false; 13153 13154 EVT VT; 13155 SDValue Ptr; 13156 bool isSEXTLoad = false; 13157 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13158 Ptr = LD->getBasePtr(); 13159 VT = LD->getMemoryVT(); 13160 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13161 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13162 Ptr = ST->getBasePtr(); 13163 VT = ST->getMemoryVT(); 13164 } else 13165 return false; 13166 13167 bool isInc; 13168 bool isLegal = false; 13169 if (Subtarget->isThumb2()) 13170 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13171 Offset, isInc, DAG); 13172 else 13173 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 13174 Offset, isInc, DAG); 13175 if (!isLegal) 13176 return false; 13177 13178 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 13179 return true; 13180 } 13181 13182 /// getPostIndexedAddressParts - returns true by value, base pointer and 13183 /// offset pointer and addressing mode by reference if this node can be 13184 /// combined with a load / store to form a post-indexed load / store. 13185 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 13186 SDValue &Base, 13187 SDValue &Offset, 13188 ISD::MemIndexedMode &AM, 13189 SelectionDAG &DAG) const { 13190 EVT VT; 13191 SDValue Ptr; 13192 bool isSEXTLoad = false, isNonExt; 13193 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13194 VT = LD->getMemoryVT(); 13195 Ptr = LD->getBasePtr(); 13196 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 13197 isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD; 13198 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13199 VT = ST->getMemoryVT(); 13200 Ptr = ST->getBasePtr(); 13201 isNonExt = !ST->isTruncatingStore(); 13202 } else 13203 return false; 13204 13205 if (Subtarget->isThumb1Only()) { 13206 // Thumb-1 can do a limited post-inc load or store as an updating LDM. It 13207 // must be non-extending/truncating, i32, with an offset of 4. 13208 assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!"); 13209 if (Op->getOpcode() != ISD::ADD || !isNonExt) 13210 return false; 13211 auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 13212 if (!RHS || RHS->getZExtValue() != 4) 13213 return false; 13214 13215 Offset = Op->getOperand(1); 13216 Base = Op->getOperand(0); 13217 AM = ISD::POST_INC; 13218 return true; 13219 } 13220 13221 bool isInc; 13222 bool isLegal = false; 13223 if (Subtarget->isThumb2()) 13224 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13225 isInc, DAG); 13226 else 13227 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 13228 isInc, DAG); 13229 if (!isLegal) 13230 return false; 13231 13232 if (Ptr != Base) { 13233 // Swap base ptr and offset to catch more post-index load / store when 13234 // it's legal. In Thumb2 mode, offset must be an immediate. 13235 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 13236 !Subtarget->isThumb2()) 13237 std::swap(Base, Offset); 13238 13239 // Post-indexed load / store update the base pointer. 13240 if (Ptr != Base) 13241 return false; 13242 } 13243 13244 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 13245 return true; 13246 } 13247 13248 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13249 KnownBits &Known, 13250 const APInt &DemandedElts, 13251 const SelectionDAG &DAG, 13252 unsigned Depth) const { 13253 unsigned BitWidth = Known.getBitWidth(); 13254 Known.resetAll(); 13255 switch (Op.getOpcode()) { 13256 default: break; 13257 case ARMISD::ADDC: 13258 case ARMISD::ADDE: 13259 case ARMISD::SUBC: 13260 case ARMISD::SUBE: 13261 // Special cases when we convert a carry to a boolean. 13262 if (Op.getResNo() == 0) { 13263 SDValue LHS = Op.getOperand(0); 13264 SDValue RHS = Op.getOperand(1); 13265 // (ADDE 0, 0, C) will give us a single bit. 13266 if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) && 13267 isNullConstant(RHS)) { 13268 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 13269 return; 13270 } 13271 } 13272 break; 13273 case ARMISD::CMOV: { 13274 // Bits are known zero/one if known on the LHS and RHS. 13275 DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1); 13276 if (Known.isUnknown()) 13277 return; 13278 13279 KnownBits KnownRHS; 13280 DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1); 13281 Known.Zero &= KnownRHS.Zero; 13282 Known.One &= KnownRHS.One; 13283 return; 13284 } 13285 case ISD::INTRINSIC_W_CHAIN: { 13286 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 13287 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 13288 switch (IntID) { 13289 default: return; 13290 case Intrinsic::arm_ldaex: 13291 case Intrinsic::arm_ldrex: { 13292 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 13293 unsigned MemBits = VT.getScalarSizeInBits(); 13294 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 13295 return; 13296 } 13297 } 13298 } 13299 case ARMISD::BFI: { 13300 // Conservatively, we can recurse down the first operand 13301 // and just mask out all affected bits. 13302 DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1); 13303 13304 // The operand to BFI is already a mask suitable for removing the bits it 13305 // sets. 13306 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2)); 13307 const APInt &Mask = CI->getAPIntValue(); 13308 Known.Zero &= Mask; 13309 Known.One &= Mask; 13310 return; 13311 } 13312 } 13313 } 13314 13315 //===----------------------------------------------------------------------===// 13316 // ARM Inline Assembly Support 13317 //===----------------------------------------------------------------------===// 13318 13319 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 13320 // Looking for "rev" which is V6+. 13321 if (!Subtarget->hasV6Ops()) 13322 return false; 13323 13324 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 13325 std::string AsmStr = IA->getAsmString(); 13326 SmallVector<StringRef, 4> AsmPieces; 13327 SplitString(AsmStr, AsmPieces, ";\n"); 13328 13329 switch (AsmPieces.size()) { 13330 default: return false; 13331 case 1: 13332 AsmStr = AsmPieces[0]; 13333 AsmPieces.clear(); 13334 SplitString(AsmStr, AsmPieces, " \t,"); 13335 13336 // rev $0, $1 13337 if (AsmPieces.size() == 3 && 13338 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 13339 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 13340 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 13341 if (Ty && Ty->getBitWidth() == 32) 13342 return IntrinsicLowering::LowerToByteSwap(CI); 13343 } 13344 break; 13345 } 13346 13347 return false; 13348 } 13349 13350 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const { 13351 // At this point, we have to lower this constraint to something else, so we 13352 // lower it to an "r" or "w". However, by doing this we will force the result 13353 // to be in register, while the X constraint is much more permissive. 13354 // 13355 // Although we are correct (we are free to emit anything, without 13356 // constraints), we might break use cases that would expect us to be more 13357 // efficient and emit something else. 13358 if (!Subtarget->hasVFP2()) 13359 return "r"; 13360 if (ConstraintVT.isFloatingPoint()) 13361 return "w"; 13362 if (ConstraintVT.isVector() && Subtarget->hasNEON() && 13363 (ConstraintVT.getSizeInBits() == 64 || 13364 ConstraintVT.getSizeInBits() == 128)) 13365 return "w"; 13366 13367 return "r"; 13368 } 13369 13370 /// getConstraintType - Given a constraint letter, return the type of 13371 /// constraint it is for this target. 13372 ARMTargetLowering::ConstraintType 13373 ARMTargetLowering::getConstraintType(StringRef Constraint) const { 13374 if (Constraint.size() == 1) { 13375 switch (Constraint[0]) { 13376 default: break; 13377 case 'l': return C_RegisterClass; 13378 case 'w': return C_RegisterClass; 13379 case 'h': return C_RegisterClass; 13380 case 'x': return C_RegisterClass; 13381 case 't': return C_RegisterClass; 13382 case 'j': return C_Other; // Constant for movw. 13383 // An address with a single base register. Due to the way we 13384 // currently handle addresses it is the same as an 'r' memory constraint. 13385 case 'Q': return C_Memory; 13386 } 13387 } else if (Constraint.size() == 2) { 13388 switch (Constraint[0]) { 13389 default: break; 13390 // All 'U+' constraints are addresses. 13391 case 'U': return C_Memory; 13392 } 13393 } 13394 return TargetLowering::getConstraintType(Constraint); 13395 } 13396 13397 /// Examine constraint type and operand type and determine a weight value. 13398 /// This object must already have been set up with the operand type 13399 /// and the current alternative constraint selected. 13400 TargetLowering::ConstraintWeight 13401 ARMTargetLowering::getSingleConstraintMatchWeight( 13402 AsmOperandInfo &info, const char *constraint) const { 13403 ConstraintWeight weight = CW_Invalid; 13404 Value *CallOperandVal = info.CallOperandVal; 13405 // If we don't have a value, we can't do a match, 13406 // but allow it at the lowest weight. 13407 if (!CallOperandVal) 13408 return CW_Default; 13409 Type *type = CallOperandVal->getType(); 13410 // Look at the constraint type. 13411 switch (*constraint) { 13412 default: 13413 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 13414 break; 13415 case 'l': 13416 if (type->isIntegerTy()) { 13417 if (Subtarget->isThumb()) 13418 weight = CW_SpecificReg; 13419 else 13420 weight = CW_Register; 13421 } 13422 break; 13423 case 'w': 13424 if (type->isFloatingPointTy()) 13425 weight = CW_Register; 13426 break; 13427 } 13428 return weight; 13429 } 13430 13431 using RCPair = std::pair<unsigned, const TargetRegisterClass *>; 13432 13433 RCPair ARMTargetLowering::getRegForInlineAsmConstraint( 13434 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 13435 if (Constraint.size() == 1) { 13436 // GCC ARM Constraint Letters 13437 switch (Constraint[0]) { 13438 case 'l': // Low regs or general regs. 13439 if (Subtarget->isThumb()) 13440 return RCPair(0U, &ARM::tGPRRegClass); 13441 return RCPair(0U, &ARM::GPRRegClass); 13442 case 'h': // High regs or no regs. 13443 if (Subtarget->isThumb()) 13444 return RCPair(0U, &ARM::hGPRRegClass); 13445 break; 13446 case 'r': 13447 if (Subtarget->isThumb1Only()) 13448 return RCPair(0U, &ARM::tGPRRegClass); 13449 return RCPair(0U, &ARM::GPRRegClass); 13450 case 'w': 13451 if (VT == MVT::Other) 13452 break; 13453 if (VT == MVT::f32) 13454 return RCPair(0U, &ARM::SPRRegClass); 13455 if (VT.getSizeInBits() == 64) 13456 return RCPair(0U, &ARM::DPRRegClass); 13457 if (VT.getSizeInBits() == 128) 13458 return RCPair(0U, &ARM::QPRRegClass); 13459 break; 13460 case 'x': 13461 if (VT == MVT::Other) 13462 break; 13463 if (VT == MVT::f32) 13464 return RCPair(0U, &ARM::SPR_8RegClass); 13465 if (VT.getSizeInBits() == 64) 13466 return RCPair(0U, &ARM::DPR_8RegClass); 13467 if (VT.getSizeInBits() == 128) 13468 return RCPair(0U, &ARM::QPR_8RegClass); 13469 break; 13470 case 't': 13471 if (VT == MVT::f32 || VT == MVT::i32) 13472 return RCPair(0U, &ARM::SPRRegClass); 13473 break; 13474 } 13475 } 13476 if (StringRef("{cc}").equals_lower(Constraint)) 13477 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 13478 13479 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13480 } 13481 13482 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13483 /// vector. If it is invalid, don't add anything to Ops. 13484 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13485 std::string &Constraint, 13486 std::vector<SDValue>&Ops, 13487 SelectionDAG &DAG) const { 13488 SDValue Result; 13489 13490 // Currently only support length 1 constraints. 13491 if (Constraint.length() != 1) return; 13492 13493 char ConstraintLetter = Constraint[0]; 13494 switch (ConstraintLetter) { 13495 default: break; 13496 case 'j': 13497 case 'I': case 'J': case 'K': case 'L': 13498 case 'M': case 'N': case 'O': 13499 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 13500 if (!C) 13501 return; 13502 13503 int64_t CVal64 = C->getSExtValue(); 13504 int CVal = (int) CVal64; 13505 // None of these constraints allow values larger than 32 bits. Check 13506 // that the value fits in an int. 13507 if (CVal != CVal64) 13508 return; 13509 13510 switch (ConstraintLetter) { 13511 case 'j': 13512 // Constant suitable for movw, must be between 0 and 13513 // 65535. 13514 if (Subtarget->hasV6T2Ops()) 13515 if (CVal >= 0 && CVal <= 65535) 13516 break; 13517 return; 13518 case 'I': 13519 if (Subtarget->isThumb1Only()) { 13520 // This must be a constant between 0 and 255, for ADD 13521 // immediates. 13522 if (CVal >= 0 && CVal <= 255) 13523 break; 13524 } else if (Subtarget->isThumb2()) { 13525 // A constant that can be used as an immediate value in a 13526 // data-processing instruction. 13527 if (ARM_AM::getT2SOImmVal(CVal) != -1) 13528 break; 13529 } else { 13530 // A constant that can be used as an immediate value in a 13531 // data-processing instruction. 13532 if (ARM_AM::getSOImmVal(CVal) != -1) 13533 break; 13534 } 13535 return; 13536 13537 case 'J': 13538 if (Subtarget->isThumb1Only()) { 13539 // This must be a constant between -255 and -1, for negated ADD 13540 // immediates. This can be used in GCC with an "n" modifier that 13541 // prints the negated value, for use with SUB instructions. It is 13542 // not useful otherwise but is implemented for compatibility. 13543 if (CVal >= -255 && CVal <= -1) 13544 break; 13545 } else { 13546 // This must be a constant between -4095 and 4095. It is not clear 13547 // what this constraint is intended for. Implemented for 13548 // compatibility with GCC. 13549 if (CVal >= -4095 && CVal <= 4095) 13550 break; 13551 } 13552 return; 13553 13554 case 'K': 13555 if (Subtarget->isThumb1Only()) { 13556 // A 32-bit value where only one byte has a nonzero value. Exclude 13557 // zero to match GCC. This constraint is used by GCC internally for 13558 // constants that can be loaded with a move/shift combination. 13559 // It is not useful otherwise but is implemented for compatibility. 13560 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 13561 break; 13562 } else if (Subtarget->isThumb2()) { 13563 // A constant whose bitwise inverse can be used as an immediate 13564 // value in a data-processing instruction. This can be used in GCC 13565 // with a "B" modifier that prints the inverted value, for use with 13566 // BIC and MVN instructions. It is not useful otherwise but is 13567 // implemented for compatibility. 13568 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 13569 break; 13570 } else { 13571 // A constant whose bitwise inverse can be used as an immediate 13572 // value in a data-processing instruction. This can be used in GCC 13573 // with a "B" modifier that prints the inverted value, for use with 13574 // BIC and MVN instructions. It is not useful otherwise but is 13575 // implemented for compatibility. 13576 if (ARM_AM::getSOImmVal(~CVal) != -1) 13577 break; 13578 } 13579 return; 13580 13581 case 'L': 13582 if (Subtarget->isThumb1Only()) { 13583 // This must be a constant between -7 and 7, 13584 // for 3-operand ADD/SUB immediate instructions. 13585 if (CVal >= -7 && CVal < 7) 13586 break; 13587 } else if (Subtarget->isThumb2()) { 13588 // A constant whose negation can be used as an immediate value in a 13589 // data-processing instruction. This can be used in GCC with an "n" 13590 // modifier that prints the negated value, for use with SUB 13591 // instructions. It is not useful otherwise but is implemented for 13592 // compatibility. 13593 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 13594 break; 13595 } else { 13596 // A constant whose negation can be used as an immediate value in a 13597 // data-processing instruction. This can be used in GCC with an "n" 13598 // modifier that prints the negated value, for use with SUB 13599 // instructions. It is not useful otherwise but is implemented for 13600 // compatibility. 13601 if (ARM_AM::getSOImmVal(-CVal) != -1) 13602 break; 13603 } 13604 return; 13605 13606 case 'M': 13607 if (Subtarget->isThumb1Only()) { 13608 // This must be a multiple of 4 between 0 and 1020, for 13609 // ADD sp + immediate. 13610 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 13611 break; 13612 } else { 13613 // A power of two or a constant between 0 and 32. This is used in 13614 // GCC for the shift amount on shifted register operands, but it is 13615 // useful in general for any shift amounts. 13616 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 13617 break; 13618 } 13619 return; 13620 13621 case 'N': 13622 if (Subtarget->isThumb()) { // FIXME thumb2 13623 // This must be a constant between 0 and 31, for shift amounts. 13624 if (CVal >= 0 && CVal <= 31) 13625 break; 13626 } 13627 return; 13628 13629 case 'O': 13630 if (Subtarget->isThumb()) { // FIXME thumb2 13631 // This must be a multiple of 4 between -508 and 508, for 13632 // ADD/SUB sp = sp + immediate. 13633 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 13634 break; 13635 } 13636 return; 13637 } 13638 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType()); 13639 break; 13640 } 13641 13642 if (Result.getNode()) { 13643 Ops.push_back(Result); 13644 return; 13645 } 13646 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13647 } 13648 13649 static RTLIB::Libcall getDivRemLibcall( 13650 const SDNode *N, MVT::SimpleValueType SVT) { 13651 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13652 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13653 "Unhandled Opcode in getDivRemLibcall"); 13654 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13655 N->getOpcode() == ISD::SREM; 13656 RTLIB::Libcall LC; 13657 switch (SVT) { 13658 default: llvm_unreachable("Unexpected request for libcall!"); 13659 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 13660 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 13661 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 13662 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 13663 } 13664 return LC; 13665 } 13666 13667 static TargetLowering::ArgListTy getDivRemArgList( 13668 const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) { 13669 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM || 13670 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) && 13671 "Unhandled Opcode in getDivRemArgList"); 13672 bool isSigned = N->getOpcode() == ISD::SDIVREM || 13673 N->getOpcode() == ISD::SREM; 13674 TargetLowering::ArgListTy Args; 13675 TargetLowering::ArgListEntry Entry; 13676 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13677 EVT ArgVT = N->getOperand(i).getValueType(); 13678 Type *ArgTy = ArgVT.getTypeForEVT(*Context); 13679 Entry.Node = N->getOperand(i); 13680 Entry.Ty = ArgTy; 13681 Entry.IsSExt = isSigned; 13682 Entry.IsZExt = !isSigned; 13683 Args.push_back(Entry); 13684 } 13685 if (Subtarget->isTargetWindows() && Args.size() >= 2) 13686 std::swap(Args[0], Args[1]); 13687 return Args; 13688 } 13689 13690 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 13691 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() || 13692 Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() || 13693 Subtarget->isTargetWindows()) && 13694 "Register-based DivRem lowering only"); 13695 unsigned Opcode = Op->getOpcode(); 13696 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 13697 "Invalid opcode for Div/Rem lowering"); 13698 bool isSigned = (Opcode == ISD::SDIVREM); 13699 EVT VT = Op->getValueType(0); 13700 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 13701 SDLoc dl(Op); 13702 13703 // If the target has hardware divide, use divide + multiply + subtract: 13704 // div = a / b 13705 // rem = a - b * div 13706 // return {div, rem} 13707 // This should be lowered into UDIV/SDIV + MLS later on. 13708 bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode() 13709 : Subtarget->hasDivideInARMMode(); 13710 if (hasDivide && Op->getValueType(0).isSimple() && 13711 Op->getSimpleValueType(0) == MVT::i32) { 13712 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 13713 const SDValue Dividend = Op->getOperand(0); 13714 const SDValue Divisor = Op->getOperand(1); 13715 SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor); 13716 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor); 13717 SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul); 13718 13719 SDValue Values[2] = {Div, Rem}; 13720 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values); 13721 } 13722 13723 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(), 13724 VT.getSimpleVT().SimpleTy); 13725 SDValue InChain = DAG.getEntryNode(); 13726 13727 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(), 13728 DAG.getContext(), 13729 Subtarget); 13730 13731 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13732 getPointerTy(DAG.getDataLayout())); 13733 13734 Type *RetTy = StructType::get(Ty, Ty); 13735 13736 if (Subtarget->isTargetWindows()) 13737 InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain); 13738 13739 TargetLowering::CallLoweringInfo CLI(DAG); 13740 CLI.setDebugLoc(dl).setChain(InChain) 13741 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 13742 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned); 13743 13744 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 13745 return CallInfo.first; 13746 } 13747 13748 // Lowers REM using divmod helpers 13749 // see RTABI section 4.2/4.3 13750 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const { 13751 // Build return types (div and rem) 13752 std::vector<Type*> RetTyParams; 13753 Type *RetTyElement; 13754 13755 switch (N->getValueType(0).getSimpleVT().SimpleTy) { 13756 default: llvm_unreachable("Unexpected request for libcall!"); 13757 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break; 13758 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break; 13759 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break; 13760 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break; 13761 } 13762 13763 RetTyParams.push_back(RetTyElement); 13764 RetTyParams.push_back(RetTyElement); 13765 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams); 13766 Type *RetTy = StructType::get(*DAG.getContext(), ret); 13767 13768 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT(). 13769 SimpleTy); 13770 SDValue InChain = DAG.getEntryNode(); 13771 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(), 13772 Subtarget); 13773 bool isSigned = N->getOpcode() == ISD::SREM; 13774 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 13775 getPointerTy(DAG.getDataLayout())); 13776 13777 if (Subtarget->isTargetWindows()) 13778 InChain = WinDBZCheckDenominator(DAG, N, InChain); 13779 13780 // Lower call 13781 CallLoweringInfo CLI(DAG); 13782 CLI.setChain(InChain) 13783 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args)) 13784 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N)); 13785 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 13786 13787 // Return second (rem) result operand (first contains div) 13788 SDNode *ResNode = CallResult.first.getNode(); 13789 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands"); 13790 return ResNode->getOperand(1); 13791 } 13792 13793 SDValue 13794 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { 13795 assert(Subtarget->isTargetWindows() && "unsupported target platform"); 13796 SDLoc DL(Op); 13797 13798 // Get the inputs. 13799 SDValue Chain = Op.getOperand(0); 13800 SDValue Size = Op.getOperand(1); 13801 13802 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size, 13803 DAG.getConstant(2, DL, MVT::i32)); 13804 13805 SDValue Flag; 13806 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag); 13807 Flag = Chain.getValue(1); 13808 13809 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 13810 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag); 13811 13812 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32); 13813 Chain = NewSP.getValue(1); 13814 13815 SDValue Ops[2] = { NewSP, Chain }; 13816 return DAG.getMergeValues(Ops, DL); 13817 } 13818 13819 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 13820 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() && 13821 "Unexpected type for custom-lowering FP_EXTEND"); 13822 13823 RTLIB::Libcall LC; 13824 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 13825 13826 SDValue SrcVal = Op.getOperand(0); 13827 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13828 SDLoc(Op)).first; 13829 } 13830 13831 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 13832 assert(Op.getOperand(0).getValueType() == MVT::f64 && 13833 Subtarget->isFPOnlySP() && 13834 "Unexpected type for custom-lowering FP_ROUND"); 13835 13836 RTLIB::Libcall LC; 13837 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 13838 13839 SDValue SrcVal = Op.getOperand(0); 13840 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 13841 SDLoc(Op)).first; 13842 } 13843 13844 bool 13845 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13846 // The ARM target isn't yet aware of offsets. 13847 return false; 13848 } 13849 13850 bool ARM::isBitFieldInvertedMask(unsigned v) { 13851 if (v == 0xffffffff) 13852 return false; 13853 13854 // there can be 1's on either or both "outsides", all the "inside" 13855 // bits must be 0's 13856 return isShiftedMask_32(~v); 13857 } 13858 13859 /// isFPImmLegal - Returns true if the target can instruction select the 13860 /// specified FP immediate natively. If false, the legalizer will 13861 /// materialize the FP immediate as a load from a constant pool. 13862 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13863 if (!Subtarget->hasVFP3()) 13864 return false; 13865 if (VT == MVT::f32) 13866 return ARM_AM::getFP32Imm(Imm) != -1; 13867 if (VT == MVT::f64 && !Subtarget->isFPOnlySP()) 13868 return ARM_AM::getFP64Imm(Imm) != -1; 13869 return false; 13870 } 13871 13872 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 13873 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 13874 /// specified in the intrinsic calls. 13875 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13876 const CallInst &I, 13877 MachineFunction &MF, 13878 unsigned Intrinsic) const { 13879 switch (Intrinsic) { 13880 case Intrinsic::arm_neon_vld1: 13881 case Intrinsic::arm_neon_vld2: 13882 case Intrinsic::arm_neon_vld3: 13883 case Intrinsic::arm_neon_vld4: 13884 case Intrinsic::arm_neon_vld2lane: 13885 case Intrinsic::arm_neon_vld3lane: 13886 case Intrinsic::arm_neon_vld4lane: { 13887 Info.opc = ISD::INTRINSIC_W_CHAIN; 13888 // Conservatively set memVT to the entire set of vectors loaded. 13889 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13890 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 13891 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13892 Info.ptrVal = I.getArgOperand(0); 13893 Info.offset = 0; 13894 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13895 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13896 // volatile loads with NEON intrinsics not supported 13897 Info.flags = MachineMemOperand::MOLoad; 13898 return true; 13899 } 13900 case Intrinsic::arm_neon_vst1: 13901 case Intrinsic::arm_neon_vst2: 13902 case Intrinsic::arm_neon_vst3: 13903 case Intrinsic::arm_neon_vst4: 13904 case Intrinsic::arm_neon_vst2lane: 13905 case Intrinsic::arm_neon_vst3lane: 13906 case Intrinsic::arm_neon_vst4lane: { 13907 Info.opc = ISD::INTRINSIC_VOID; 13908 // Conservatively set memVT to the entire set of vectors stored. 13909 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13910 unsigned NumElts = 0; 13911 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 13912 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 13913 if (!ArgTy->isVectorTy()) 13914 break; 13915 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 13916 } 13917 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 13918 Info.ptrVal = I.getArgOperand(0); 13919 Info.offset = 0; 13920 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 13921 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 13922 // volatile stores with NEON intrinsics not supported 13923 Info.flags = MachineMemOperand::MOStore; 13924 return true; 13925 } 13926 case Intrinsic::arm_ldaex: 13927 case Intrinsic::arm_ldrex: { 13928 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13929 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 13930 Info.opc = ISD::INTRINSIC_W_CHAIN; 13931 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13932 Info.ptrVal = I.getArgOperand(0); 13933 Info.offset = 0; 13934 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13935 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 13936 return true; 13937 } 13938 case Intrinsic::arm_stlex: 13939 case Intrinsic::arm_strex: { 13940 auto &DL = I.getCalledFunction()->getParent()->getDataLayout(); 13941 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 13942 Info.opc = ISD::INTRINSIC_W_CHAIN; 13943 Info.memVT = MVT::getVT(PtrTy->getElementType()); 13944 Info.ptrVal = I.getArgOperand(1); 13945 Info.offset = 0; 13946 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 13947 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 13948 return true; 13949 } 13950 case Intrinsic::arm_stlexd: 13951 case Intrinsic::arm_strexd: 13952 Info.opc = ISD::INTRINSIC_W_CHAIN; 13953 Info.memVT = MVT::i64; 13954 Info.ptrVal = I.getArgOperand(2); 13955 Info.offset = 0; 13956 Info.align = 8; 13957 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 13958 return true; 13959 13960 case Intrinsic::arm_ldaexd: 13961 case Intrinsic::arm_ldrexd: 13962 Info.opc = ISD::INTRINSIC_W_CHAIN; 13963 Info.memVT = MVT::i64; 13964 Info.ptrVal = I.getArgOperand(0); 13965 Info.offset = 0; 13966 Info.align = 8; 13967 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 13968 return true; 13969 13970 default: 13971 break; 13972 } 13973 13974 return false; 13975 } 13976 13977 /// \brief Returns true if it is beneficial to convert a load of a constant 13978 /// to just the constant itself. 13979 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13980 Type *Ty) const { 13981 assert(Ty->isIntegerTy()); 13982 13983 unsigned Bits = Ty->getPrimitiveSizeInBits(); 13984 if (Bits == 0 || Bits > 32) 13985 return false; 13986 return true; 13987 } 13988 13989 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 13990 unsigned Index) const { 13991 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 13992 return false; 13993 13994 return (Index == 0 || Index == ResVT.getVectorNumElements()); 13995 } 13996 13997 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder, 13998 ARM_MB::MemBOpt Domain) const { 13999 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14000 14001 // First, if the target has no DMB, see what fallback we can use. 14002 if (!Subtarget->hasDataBarrier()) { 14003 // Some ARMv6 cpus can support data barriers with an mcr instruction. 14004 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 14005 // here. 14006 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) { 14007 Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr); 14008 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0), 14009 Builder.getInt32(0), Builder.getInt32(7), 14010 Builder.getInt32(10), Builder.getInt32(5)}; 14011 return Builder.CreateCall(MCR, args); 14012 } else { 14013 // Instead of using barriers, atomic accesses on these subtargets use 14014 // libcalls. 14015 llvm_unreachable("makeDMB on a target so old that it has no barriers"); 14016 } 14017 } else { 14018 Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb); 14019 // Only a full system barrier exists in the M-class architectures. 14020 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain; 14021 Constant *CDomain = Builder.getInt32(Domain); 14022 return Builder.CreateCall(DMB, CDomain); 14023 } 14024 } 14025 14026 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 14027 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 14028 Instruction *Inst, 14029 AtomicOrdering Ord) const { 14030 switch (Ord) { 14031 case AtomicOrdering::NotAtomic: 14032 case AtomicOrdering::Unordered: 14033 llvm_unreachable("Invalid fence: unordered/non-atomic"); 14034 case AtomicOrdering::Monotonic: 14035 case AtomicOrdering::Acquire: 14036 return nullptr; // Nothing to do 14037 case AtomicOrdering::SequentiallyConsistent: 14038 if (!Inst->hasAtomicStore()) 14039 return nullptr; // Nothing to do 14040 LLVM_FALLTHROUGH; 14041 case AtomicOrdering::Release: 14042 case AtomicOrdering::AcquireRelease: 14043 if (Subtarget->preferISHSTBarriers()) 14044 return makeDMB(Builder, ARM_MB::ISHST); 14045 // FIXME: add a comment with a link to documentation justifying this. 14046 else 14047 return makeDMB(Builder, ARM_MB::ISH); 14048 } 14049 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 14050 } 14051 14052 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 14053 Instruction *Inst, 14054 AtomicOrdering Ord) const { 14055 switch (Ord) { 14056 case AtomicOrdering::NotAtomic: 14057 case AtomicOrdering::Unordered: 14058 llvm_unreachable("Invalid fence: unordered/not-atomic"); 14059 case AtomicOrdering::Monotonic: 14060 case AtomicOrdering::Release: 14061 return nullptr; // Nothing to do 14062 case AtomicOrdering::Acquire: 14063 case AtomicOrdering::AcquireRelease: 14064 case AtomicOrdering::SequentiallyConsistent: 14065 return makeDMB(Builder, ARM_MB::ISH); 14066 } 14067 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 14068 } 14069 14070 // Loads and stores less than 64-bits are already atomic; ones above that 14071 // are doomed anyway, so defer to the default libcall and blame the OS when 14072 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14073 // anything for those. 14074 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 14075 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 14076 return (Size == 64) && !Subtarget->isMClass(); 14077 } 14078 14079 // Loads and stores less than 64-bits are already atomic; ones above that 14080 // are doomed anyway, so defer to the default libcall and blame the OS when 14081 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit 14082 // anything for those. 14083 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that 14084 // guarantee, see DDI0406C ARM architecture reference manual, 14085 // sections A8.8.72-74 LDRD) 14086 TargetLowering::AtomicExpansionKind 14087 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 14088 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 14089 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly 14090 : AtomicExpansionKind::None; 14091 } 14092 14093 // For the real atomic operations, we have ldrex/strex up to 32 bits, 14094 // and up to 64 bits on the non-M profiles 14095 TargetLowering::AtomicExpansionKind 14096 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 14097 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 14098 bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14099 return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) 14100 ? AtomicExpansionKind::LLSC 14101 : AtomicExpansionKind::None; 14102 } 14103 14104 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR( 14105 AtomicCmpXchgInst *AI) const { 14106 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 14107 // implement cmpxchg without spilling. If the address being exchanged is also 14108 // on the stack and close enough to the spill slot, this can lead to a 14109 // situation where the monitor always gets cleared and the atomic operation 14110 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 14111 bool hasAtomicCmpXchg = 14112 !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps(); 14113 return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg; 14114 } 14115 14116 bool ARMTargetLowering::shouldInsertFencesForAtomic( 14117 const Instruction *I) const { 14118 return InsertFencesForAtomic; 14119 } 14120 14121 // This has so far only been implemented for MachO. 14122 bool ARMTargetLowering::useLoadStackGuardNode() const { 14123 return Subtarget->isTargetMachO(); 14124 } 14125 14126 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx, 14127 unsigned &Cost) const { 14128 // If we do not have NEON, vector types are not natively supported. 14129 if (!Subtarget->hasNEON()) 14130 return false; 14131 14132 // Floating point values and vector values map to the same register file. 14133 // Therefore, although we could do a store extract of a vector type, this is 14134 // better to leave at float as we have more freedom in the addressing mode for 14135 // those. 14136 if (VectorTy->isFPOrFPVectorTy()) 14137 return false; 14138 14139 // If the index is unknown at compile time, this is very expensive to lower 14140 // and it is not possible to combine the store with the extract. 14141 if (!isa<ConstantInt>(Idx)) 14142 return false; 14143 14144 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type"); 14145 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 14146 // We can do a store + vector extract on any vector that fits perfectly in a D 14147 // or Q register. 14148 if (BitWidth == 64 || BitWidth == 128) { 14149 Cost = 0; 14150 return true; 14151 } 14152 return false; 14153 } 14154 14155 bool ARMTargetLowering::isCheapToSpeculateCttz() const { 14156 return Subtarget->hasV6T2Ops(); 14157 } 14158 14159 bool ARMTargetLowering::isCheapToSpeculateCtlz() const { 14160 return Subtarget->hasV6T2Ops(); 14161 } 14162 14163 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 14164 AtomicOrdering Ord) const { 14165 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14166 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 14167 bool IsAcquire = isAcquireOrStronger(Ord); 14168 14169 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 14170 // intrinsic must return {i32, i32} and we have to recombine them into a 14171 // single i64 here. 14172 if (ValTy->getPrimitiveSizeInBits() == 64) { 14173 Intrinsic::ID Int = 14174 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 14175 Function *Ldrex = Intrinsic::getDeclaration(M, Int); 14176 14177 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14178 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 14179 14180 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 14181 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 14182 if (!Subtarget->isLittle()) 14183 std::swap (Lo, Hi); 14184 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 14185 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 14186 return Builder.CreateOr( 14187 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 14188 } 14189 14190 Type *Tys[] = { Addr->getType() }; 14191 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 14192 Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys); 14193 14194 return Builder.CreateTruncOrBitCast( 14195 Builder.CreateCall(Ldrex, Addr), 14196 cast<PointerType>(Addr->getType())->getElementType()); 14197 } 14198 14199 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 14200 IRBuilder<> &Builder) const { 14201 if (!Subtarget->hasV7Ops()) 14202 return; 14203 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14204 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex)); 14205 } 14206 14207 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 14208 Value *Addr, 14209 AtomicOrdering Ord) const { 14210 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 14211 bool IsRelease = isReleaseOrStronger(Ord); 14212 14213 // Since the intrinsics must have legal type, the i64 intrinsics take two 14214 // parameters: "i32, i32". We must marshal Val into the appropriate form 14215 // before the call. 14216 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 14217 Intrinsic::ID Int = 14218 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 14219 Function *Strex = Intrinsic::getDeclaration(M, Int); 14220 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 14221 14222 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 14223 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 14224 if (!Subtarget->isLittle()) 14225 std::swap(Lo, Hi); 14226 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 14227 return Builder.CreateCall(Strex, {Lo, Hi, Addr}); 14228 } 14229 14230 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 14231 Type *Tys[] = { Addr->getType() }; 14232 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 14233 14234 return Builder.CreateCall( 14235 Strex, {Builder.CreateZExtOrBitCast( 14236 Val, Strex->getFunctionType()->getParamType(0)), 14237 Addr}); 14238 } 14239 14240 /// A helper function for determining the number of interleaved accesses we 14241 /// will generate when lowering accesses of the given type. 14242 unsigned 14243 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 14244 const DataLayout &DL) const { 14245 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 14246 } 14247 14248 bool ARMTargetLowering::isLegalInterleavedAccessType( 14249 VectorType *VecTy, const DataLayout &DL) const { 14250 14251 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 14252 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 14253 14254 // Ensure the vector doesn't have f16 elements. Even though we could do an 14255 // i16 vldN, we can't hold the f16 vectors and will end up converting via 14256 // f32. 14257 if (VecTy->getElementType()->isHalfTy()) 14258 return false; 14259 14260 // Ensure the number of vector elements is greater than 1. 14261 if (VecTy->getNumElements() < 2) 14262 return false; 14263 14264 // Ensure the element type is legal. 14265 if (ElSize != 8 && ElSize != 16 && ElSize != 32) 14266 return false; 14267 14268 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 14269 // 128 will be split into multiple interleaved accesses. 14270 return VecSize == 64 || VecSize % 128 == 0; 14271 } 14272 14273 /// \brief Lower an interleaved load into a vldN intrinsic. 14274 /// 14275 /// E.g. Lower an interleaved load (Factor = 2): 14276 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4 14277 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 14278 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 14279 /// 14280 /// Into: 14281 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4) 14282 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0 14283 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1 14284 bool ARMTargetLowering::lowerInterleavedLoad( 14285 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 14286 ArrayRef<unsigned> Indices, unsigned Factor) const { 14287 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14288 "Invalid interleave factor"); 14289 assert(!Shuffles.empty() && "Empty shufflevector input"); 14290 assert(Shuffles.size() == Indices.size() && 14291 "Unmatched number of shufflevectors and indices"); 14292 14293 VectorType *VecTy = Shuffles[0]->getType(); 14294 Type *EltTy = VecTy->getVectorElementType(); 14295 14296 const DataLayout &DL = LI->getModule()->getDataLayout(); 14297 14298 // Skip if we do not have NEON and skip illegal vector types. We can 14299 // "legalize" wide vector types into multiple interleaved accesses as long as 14300 // the vector types are divisible by 128. 14301 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 14302 return false; 14303 14304 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 14305 14306 // A pointer vector can not be the return type of the ldN intrinsics. Need to 14307 // load integer vectors first and then convert to pointer vectors. 14308 if (EltTy->isPointerTy()) 14309 VecTy = 14310 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 14311 14312 IRBuilder<> Builder(LI); 14313 14314 // The base address of the load. 14315 Value *BaseAddr = LI->getPointerOperand(); 14316 14317 if (NumLoads > 1) { 14318 // If we're going to generate more than one load, reset the sub-vector type 14319 // to something legal. 14320 VecTy = VectorType::get(VecTy->getVectorElementType(), 14321 VecTy->getVectorNumElements() / NumLoads); 14322 14323 // We will compute the pointer operand of each load from the original base 14324 // address using GEPs. Cast the base address to a pointer to the scalar 14325 // element type. 14326 BaseAddr = Builder.CreateBitCast( 14327 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 14328 LI->getPointerAddressSpace())); 14329 } 14330 14331 assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!"); 14332 14333 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace()); 14334 Type *Tys[] = {VecTy, Int8Ptr}; 14335 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2, 14336 Intrinsic::arm_neon_vld3, 14337 Intrinsic::arm_neon_vld4}; 14338 Function *VldnFunc = 14339 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 14340 14341 // Holds sub-vectors extracted from the load intrinsic return values. The 14342 // sub-vectors are associated with the shufflevector instructions they will 14343 // replace. 14344 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 14345 14346 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 14347 // If we're generating more than one load, compute the base address of 14348 // subsequent loads as an offset from the previous. 14349 if (LoadCount > 0) 14350 BaseAddr = Builder.CreateConstGEP1_32( 14351 BaseAddr, VecTy->getVectorNumElements() * Factor); 14352 14353 SmallVector<Value *, 2> Ops; 14354 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14355 Ops.push_back(Builder.getInt32(LI->getAlignment())); 14356 14357 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN"); 14358 14359 // Replace uses of each shufflevector with the corresponding vector loaded 14360 // by ldN. 14361 for (unsigned i = 0; i < Shuffles.size(); i++) { 14362 ShuffleVectorInst *SV = Shuffles[i]; 14363 unsigned Index = Indices[i]; 14364 14365 Value *SubVec = Builder.CreateExtractValue(VldN, Index); 14366 14367 // Convert the integer vector to pointer vector if the element is pointer. 14368 if (EltTy->isPointerTy()) 14369 SubVec = Builder.CreateIntToPtr( 14370 SubVec, VectorType::get(SV->getType()->getVectorElementType(), 14371 VecTy->getVectorNumElements())); 14372 14373 SubVecs[SV].push_back(SubVec); 14374 } 14375 } 14376 14377 // Replace uses of the shufflevector instructions with the sub-vectors 14378 // returned by the load intrinsic. If a shufflevector instruction is 14379 // associated with more than one sub-vector, those sub-vectors will be 14380 // concatenated into a single wide vector. 14381 for (ShuffleVectorInst *SVI : Shuffles) { 14382 auto &SubVec = SubVecs[SVI]; 14383 auto *WideVec = 14384 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 14385 SVI->replaceAllUsesWith(WideVec); 14386 } 14387 14388 return true; 14389 } 14390 14391 /// \brief Lower an interleaved store into a vstN intrinsic. 14392 /// 14393 /// E.g. Lower an interleaved store (Factor = 3): 14394 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 14395 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 14396 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4 14397 /// 14398 /// Into: 14399 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 14400 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 14401 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 14402 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14403 /// 14404 /// Note that the new shufflevectors will be removed and we'll only generate one 14405 /// vst3 instruction in CodeGen. 14406 /// 14407 /// Example for a more general valid mask (Factor 3). Lower: 14408 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 14409 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 14410 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 14411 /// 14412 /// Into: 14413 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 14414 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 14415 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 14416 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4) 14417 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI, 14418 ShuffleVectorInst *SVI, 14419 unsigned Factor) const { 14420 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 14421 "Invalid interleave factor"); 14422 14423 VectorType *VecTy = SVI->getType(); 14424 assert(VecTy->getVectorNumElements() % Factor == 0 && 14425 "Invalid interleaved store"); 14426 14427 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 14428 Type *EltTy = VecTy->getVectorElementType(); 14429 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 14430 14431 const DataLayout &DL = SI->getModule()->getDataLayout(); 14432 14433 // Skip if we do not have NEON and skip illegal vector types. We can 14434 // "legalize" wide vector types into multiple interleaved accesses as long as 14435 // the vector types are divisible by 128. 14436 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 14437 return false; 14438 14439 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 14440 14441 Value *Op0 = SVI->getOperand(0); 14442 Value *Op1 = SVI->getOperand(1); 14443 IRBuilder<> Builder(SI); 14444 14445 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 14446 // vectors to integer vectors. 14447 if (EltTy->isPointerTy()) { 14448 Type *IntTy = DL.getIntPtrType(EltTy); 14449 14450 // Convert to the corresponding integer vector. 14451 Type *IntVecTy = 14452 VectorType::get(IntTy, Op0->getType()->getVectorNumElements()); 14453 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 14454 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 14455 14456 SubVecTy = VectorType::get(IntTy, LaneLen); 14457 } 14458 14459 // The base address of the store. 14460 Value *BaseAddr = SI->getPointerOperand(); 14461 14462 if (NumStores > 1) { 14463 // If we're going to generate more than one store, reset the lane length 14464 // and sub-vector type to something legal. 14465 LaneLen /= NumStores; 14466 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 14467 14468 // We will compute the pointer operand of each store from the original base 14469 // address using GEPs. Cast the base address to a pointer to the scalar 14470 // element type. 14471 BaseAddr = Builder.CreateBitCast( 14472 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 14473 SI->getPointerAddressSpace())); 14474 } 14475 14476 assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!"); 14477 14478 auto Mask = SVI->getShuffleMask(); 14479 14480 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace()); 14481 Type *Tys[] = {Int8Ptr, SubVecTy}; 14482 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2, 14483 Intrinsic::arm_neon_vst3, 14484 Intrinsic::arm_neon_vst4}; 14485 14486 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 14487 // If we generating more than one store, we compute the base address of 14488 // subsequent stores as an offset from the previous. 14489 if (StoreCount > 0) 14490 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor); 14491 14492 SmallVector<Value *, 6> Ops; 14493 Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr)); 14494 14495 Function *VstNFunc = 14496 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 14497 14498 // Split the shufflevector operands into sub vectors for the new vstN call. 14499 for (unsigned i = 0; i < Factor; i++) { 14500 unsigned IdxI = StoreCount * LaneLen * Factor + i; 14501 if (Mask[IdxI] >= 0) { 14502 Ops.push_back(Builder.CreateShuffleVector( 14503 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 14504 } else { 14505 unsigned StartMask = 0; 14506 for (unsigned j = 1; j < LaneLen; j++) { 14507 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 14508 if (Mask[IdxJ * Factor + IdxI] >= 0) { 14509 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 14510 break; 14511 } 14512 } 14513 // Note: If all elements in a chunk are undefs, StartMask=0! 14514 // Note: Filling undef gaps with random elements is ok, since 14515 // those elements were being written anyway (with undefs). 14516 // In the case of all undefs we're defaulting to using elems from 0 14517 // Note: StartMask cannot be negative, it's checked in 14518 // isReInterleaveMask 14519 Ops.push_back(Builder.CreateShuffleVector( 14520 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 14521 } 14522 } 14523 14524 Ops.push_back(Builder.getInt32(SI->getAlignment())); 14525 Builder.CreateCall(VstNFunc, Ops); 14526 } 14527 return true; 14528 } 14529 14530 enum HABaseType { 14531 HA_UNKNOWN = 0, 14532 HA_FLOAT, 14533 HA_DOUBLE, 14534 HA_VECT64, 14535 HA_VECT128 14536 }; 14537 14538 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base, 14539 uint64_t &Members) { 14540 if (auto *ST = dyn_cast<StructType>(Ty)) { 14541 for (unsigned i = 0; i < ST->getNumElements(); ++i) { 14542 uint64_t SubMembers = 0; 14543 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers)) 14544 return false; 14545 Members += SubMembers; 14546 } 14547 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) { 14548 uint64_t SubMembers = 0; 14549 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers)) 14550 return false; 14551 Members += SubMembers * AT->getNumElements(); 14552 } else if (Ty->isFloatTy()) { 14553 if (Base != HA_UNKNOWN && Base != HA_FLOAT) 14554 return false; 14555 Members = 1; 14556 Base = HA_FLOAT; 14557 } else if (Ty->isDoubleTy()) { 14558 if (Base != HA_UNKNOWN && Base != HA_DOUBLE) 14559 return false; 14560 Members = 1; 14561 Base = HA_DOUBLE; 14562 } else if (auto *VT = dyn_cast<VectorType>(Ty)) { 14563 Members = 1; 14564 switch (Base) { 14565 case HA_FLOAT: 14566 case HA_DOUBLE: 14567 return false; 14568 case HA_VECT64: 14569 return VT->getBitWidth() == 64; 14570 case HA_VECT128: 14571 return VT->getBitWidth() == 128; 14572 case HA_UNKNOWN: 14573 switch (VT->getBitWidth()) { 14574 case 64: 14575 Base = HA_VECT64; 14576 return true; 14577 case 128: 14578 Base = HA_VECT128; 14579 return true; 14580 default: 14581 return false; 14582 } 14583 } 14584 } 14585 14586 return (Members > 0 && Members <= 4); 14587 } 14588 14589 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of 14590 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when 14591 /// passing according to AAPCS rules. 14592 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters( 14593 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 14594 if (getEffectiveCallingConv(CallConv, isVarArg) != 14595 CallingConv::ARM_AAPCS_VFP) 14596 return false; 14597 14598 HABaseType Base = HA_UNKNOWN; 14599 uint64_t Members = 0; 14600 bool IsHA = isHomogeneousAggregate(Ty, Base, Members); 14601 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump()); 14602 14603 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy(); 14604 return IsHA || IsIntArray; 14605 } 14606 14607 unsigned ARMTargetLowering::getExceptionPointerRegister( 14608 const Constant *PersonalityFn) const { 14609 // Platforms which do not use SjLj EH may return values in these registers 14610 // via the personality function. 14611 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0; 14612 } 14613 14614 unsigned ARMTargetLowering::getExceptionSelectorRegister( 14615 const Constant *PersonalityFn) const { 14616 // Platforms which do not use SjLj EH may return values in these registers 14617 // via the personality function. 14618 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1; 14619 } 14620 14621 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14622 // Update IsSplitCSR in ARMFunctionInfo. 14623 ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>(); 14624 AFI->setIsSplitCSR(true); 14625 } 14626 14627 void ARMTargetLowering::insertCopiesSplitCSR( 14628 MachineBasicBlock *Entry, 14629 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14630 const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo(); 14631 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14632 if (!IStart) 14633 return; 14634 14635 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 14636 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14637 MachineBasicBlock::iterator MBBI = Entry->begin(); 14638 for (const MCPhysReg *I = IStart; *I; ++I) { 14639 const TargetRegisterClass *RC = nullptr; 14640 if (ARM::GPRRegClass.contains(*I)) 14641 RC = &ARM::GPRRegClass; 14642 else if (ARM::DPRRegClass.contains(*I)) 14643 RC = &ARM::DPRRegClass; 14644 else 14645 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14646 14647 unsigned NewVR = MRI->createVirtualRegister(RC); 14648 // Create copy from CSR to a virtual register. 14649 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14650 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14651 // nounwind. If we want to generalize this later, we may need to emit 14652 // CFI pseudo-instructions. 14653 assert(Entry->getParent()->getFunction().hasFnAttribute( 14654 Attribute::NoUnwind) && 14655 "Function should be nounwind in insertCopiesSplitCSR!"); 14656 Entry->addLiveIn(*I); 14657 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14658 .addReg(*I); 14659 14660 // Insert the copy-back instructions right before the terminator. 14661 for (auto *Exit : Exits) 14662 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14663 TII->get(TargetOpcode::COPY), *I) 14664 .addReg(NewVR); 14665 } 14666 } 14667 14668 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const { 14669 MF.getFrameInfo().computeMaxCallFrameSize(MF); 14670 TargetLoweringBase::finalizeLowering(MF); 14671 } 14672