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 #define DEBUG_TYPE "arm-isel" 16 #include "ARMISelLowering.h" 17 #include "ARMCallingConv.h" 18 #include "ARMConstantPoolValue.h" 19 #include "ARMMachineFunctionInfo.h" 20 #include "ARMPerfectShuffle.h" 21 #include "ARMSubtarget.h" 22 #include "ARMTargetMachine.h" 23 #include "ARMTargetObjectFile.h" 24 #include "MCTargetDesc/ARMAddressingModes.h" 25 #include "llvm/ADT/Statistic.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/CodeGen/CallingConvLower.h" 28 #include "llvm/CodeGen/IntrinsicLowering.h" 29 #include "llvm/CodeGen/MachineBasicBlock.h" 30 #include "llvm/CodeGen/MachineFrameInfo.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachineModuleInfo.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/SelectionDAG.h" 36 #include "llvm/IR/CallingConv.h" 37 #include "llvm/IR/Constants.h" 38 #include "llvm/IR/Function.h" 39 #include "llvm/IR/GlobalValue.h" 40 #include "llvm/IR/IRBuilder.h" 41 #include "llvm/IR/Instruction.h" 42 #include "llvm/IR/Instructions.h" 43 #include "llvm/IR/Intrinsics.h" 44 #include "llvm/IR/Type.h" 45 #include "llvm/MC/MCSectionMachO.h" 46 #include "llvm/Support/CommandLine.h" 47 #include "llvm/Support/ErrorHandling.h" 48 #include "llvm/Support/MathExtras.h" 49 #include "llvm/Target/TargetOptions.h" 50 #include <utility> 51 using namespace llvm; 52 53 STATISTIC(NumTailCalls, "Number of tail calls"); 54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt"); 55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments"); 56 57 cl::opt<bool> 58 EnableARMLongCalls("arm-long-calls", cl::Hidden, 59 cl::desc("Generate calls via indirect call instructions"), 60 cl::init(false)); 61 62 static cl::opt<bool> 63 ARMInterworking("arm-interworking", cl::Hidden, 64 cl::desc("Enable / disable ARM interworking (for debugging only)"), 65 cl::init(true)); 66 67 namespace { 68 class ARMCCState : public CCState { 69 public: 70 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF, 71 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs, 72 LLVMContext &C, ParmContext PC) 73 : CCState(CC, isVarArg, MF, TM, locs, C) { 74 assert(((PC == Call) || (PC == Prologue)) && 75 "ARMCCState users must specify whether their context is call" 76 "or prologue generation."); 77 CallOrPrologue = PC; 78 } 79 }; 80 } 81 82 // The APCS parameter registers. 83 static const MCPhysReg GPRArgRegs[] = { 84 ARM::R0, ARM::R1, ARM::R2, ARM::R3 85 }; 86 87 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT, 88 MVT PromotedBitwiseVT) { 89 if (VT != PromotedLdStVT) { 90 setOperationAction(ISD::LOAD, VT, Promote); 91 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT); 92 93 setOperationAction(ISD::STORE, VT, Promote); 94 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT); 95 } 96 97 MVT ElemTy = VT.getVectorElementType(); 98 if (ElemTy != MVT::i64 && ElemTy != MVT::f64) 99 setOperationAction(ISD::SETCC, VT, Custom); 100 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 101 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 102 if (ElemTy == MVT::i32) { 103 setOperationAction(ISD::SINT_TO_FP, VT, Custom); 104 setOperationAction(ISD::UINT_TO_FP, VT, Custom); 105 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 106 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 107 } else { 108 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 109 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 110 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 111 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 112 } 113 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 114 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 115 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 116 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 117 setOperationAction(ISD::SELECT, VT, Expand); 118 setOperationAction(ISD::SELECT_CC, VT, Expand); 119 setOperationAction(ISD::VSELECT, VT, Expand); 120 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 121 if (VT.isInteger()) { 122 setOperationAction(ISD::SHL, VT, Custom); 123 setOperationAction(ISD::SRA, VT, Custom); 124 setOperationAction(ISD::SRL, VT, Custom); 125 } 126 127 // Promote all bit-wise operations. 128 if (VT.isInteger() && VT != PromotedBitwiseVT) { 129 setOperationAction(ISD::AND, VT, Promote); 130 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT); 131 setOperationAction(ISD::OR, VT, Promote); 132 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT); 133 setOperationAction(ISD::XOR, VT, Promote); 134 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT); 135 } 136 137 // Neon does not support vector divide/remainder operations. 138 setOperationAction(ISD::SDIV, VT, Expand); 139 setOperationAction(ISD::UDIV, VT, Expand); 140 setOperationAction(ISD::FDIV, VT, Expand); 141 setOperationAction(ISD::SREM, VT, Expand); 142 setOperationAction(ISD::UREM, VT, Expand); 143 setOperationAction(ISD::FREM, VT, Expand); 144 } 145 146 void ARMTargetLowering::addDRTypeForNEON(MVT VT) { 147 addRegisterClass(VT, &ARM::DPRRegClass); 148 addTypeForNEON(VT, MVT::f64, MVT::v2i32); 149 } 150 151 void ARMTargetLowering::addQRTypeForNEON(MVT VT) { 152 addRegisterClass(VT, &ARM::DPairRegClass); 153 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32); 154 } 155 156 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) { 157 if (TM.getSubtarget<ARMSubtarget>().isTargetMachO()) 158 return new TargetLoweringObjectFileMachO(); 159 160 return new ARMElfTargetObjectFile(); 161 } 162 163 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM) 164 : TargetLowering(TM, createTLOF(TM)) { 165 Subtarget = &TM.getSubtarget<ARMSubtarget>(); 166 RegInfo = TM.getRegisterInfo(); 167 Itins = TM.getInstrItineraryData(); 168 169 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 170 171 if (Subtarget->isTargetMachO()) { 172 // Uses VFP for Thumb libfuncs if available. 173 if (Subtarget->isThumb() && Subtarget->hasVFP2() && 174 Subtarget->hasARMOps()) { 175 // Single-precision floating-point arithmetic. 176 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp"); 177 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp"); 178 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp"); 179 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp"); 180 181 // Double-precision floating-point arithmetic. 182 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp"); 183 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp"); 184 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp"); 185 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp"); 186 187 // Single-precision comparisons. 188 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp"); 189 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp"); 190 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp"); 191 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp"); 192 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp"); 193 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp"); 194 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp"); 195 setLibcallName(RTLIB::O_F32, "__unordsf2vfp"); 196 197 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE); 198 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE); 199 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE); 200 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE); 201 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE); 202 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE); 203 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE); 204 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ); 205 206 // Double-precision comparisons. 207 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp"); 208 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp"); 209 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp"); 210 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp"); 211 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp"); 212 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp"); 213 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp"); 214 setLibcallName(RTLIB::O_F64, "__unorddf2vfp"); 215 216 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE); 217 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE); 218 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE); 219 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE); 220 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE); 221 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE); 222 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE); 223 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ); 224 225 // Floating-point to integer conversions. 226 // i64 conversions are done via library routines even when generating VFP 227 // instructions, so use the same ones. 228 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp"); 229 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp"); 230 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp"); 231 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp"); 232 233 // Conversions between floating types. 234 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp"); 235 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp"); 236 237 // Integer to floating-point conversions. 238 // i64 conversions are done via library routines even when generating VFP 239 // instructions, so use the same ones. 240 // FIXME: There appears to be some naming inconsistency in ARM libgcc: 241 // e.g., __floatunsidf vs. __floatunssidfvfp. 242 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp"); 243 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp"); 244 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp"); 245 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp"); 246 } 247 } 248 249 // These libcalls are not available in 32-bit. 250 setLibcallName(RTLIB::SHL_I128, 0); 251 setLibcallName(RTLIB::SRL_I128, 0); 252 setLibcallName(RTLIB::SRA_I128, 0); 253 254 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() && 255 !Subtarget->isTargetWindows()) { 256 // Double-precision floating-point arithmetic helper functions 257 // RTABI chapter 4.1.2, Table 2 258 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd"); 259 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv"); 260 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul"); 261 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub"); 262 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS); 263 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS); 264 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS); 265 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS); 266 267 // Double-precision floating-point comparison helper functions 268 // RTABI chapter 4.1.2, Table 3 269 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq"); 270 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE); 271 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq"); 272 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ); 273 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt"); 274 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE); 275 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple"); 276 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE); 277 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge"); 278 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE); 279 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt"); 280 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE); 281 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun"); 282 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE); 283 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun"); 284 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ); 285 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS); 286 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS); 287 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS); 288 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS); 289 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS); 290 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS); 291 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS); 292 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS); 293 294 // Single-precision floating-point arithmetic helper functions 295 // RTABI chapter 4.1.2, Table 4 296 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd"); 297 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv"); 298 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul"); 299 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub"); 300 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS); 301 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS); 302 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS); 303 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS); 304 305 // Single-precision floating-point comparison helper functions 306 // RTABI chapter 4.1.2, Table 5 307 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq"); 308 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE); 309 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq"); 310 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ); 311 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt"); 312 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE); 313 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple"); 314 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE); 315 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge"); 316 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE); 317 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt"); 318 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE); 319 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun"); 320 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE); 321 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun"); 322 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ); 323 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS); 324 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS); 325 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS); 326 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS); 327 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS); 328 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS); 329 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS); 330 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS); 331 332 // Floating-point to integer conversions. 333 // RTABI chapter 4.1.2, Table 6 334 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz"); 335 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz"); 336 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz"); 337 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz"); 338 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz"); 339 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz"); 340 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz"); 341 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz"); 342 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS); 343 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS); 344 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS); 345 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS); 346 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS); 347 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS); 348 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS); 349 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS); 350 351 // Conversions between floating types. 352 // RTABI chapter 4.1.2, Table 7 353 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f"); 354 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d"); 355 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS); 356 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS); 357 358 // Integer to floating-point conversions. 359 // RTABI chapter 4.1.2, Table 8 360 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d"); 361 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d"); 362 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d"); 363 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d"); 364 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f"); 365 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f"); 366 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f"); 367 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f"); 368 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS); 369 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS); 370 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS); 371 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS); 372 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS); 373 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS); 374 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS); 375 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS); 376 377 // Long long helper functions 378 // RTABI chapter 4.2, Table 9 379 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul"); 380 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl"); 381 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr"); 382 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr"); 383 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS); 384 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS); 385 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS); 386 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS); 387 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS); 388 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS); 389 390 // Integer division functions 391 // RTABI chapter 4.3.1 392 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv"); 393 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv"); 394 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv"); 395 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod"); 396 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv"); 397 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv"); 398 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv"); 399 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod"); 400 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS); 401 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS); 402 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS); 403 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS); 404 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS); 405 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS); 406 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS); 407 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS); 408 409 // Memory operations 410 // RTABI chapter 4.3.4 411 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy"); 412 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove"); 413 setLibcallName(RTLIB::MEMSET, "__aeabi_memset"); 414 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS); 415 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS); 416 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS); 417 } 418 419 // Use divmod compiler-rt calls for iOS 5.0 and later. 420 if (Subtarget->getTargetTriple().isiOS() && 421 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) { 422 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4"); 423 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4"); 424 } 425 426 if (Subtarget->isThumb1Only()) 427 addRegisterClass(MVT::i32, &ARM::tGPRRegClass); 428 else 429 addRegisterClass(MVT::i32, &ARM::GPRRegClass); 430 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() && 431 !Subtarget->isThumb1Only()) { 432 addRegisterClass(MVT::f32, &ARM::SPRRegClass); 433 if (!Subtarget->isFPOnlySP()) 434 addRegisterClass(MVT::f64, &ARM::DPRRegClass); 435 436 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 437 } 438 439 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 440 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) { 441 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 442 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT) 443 setTruncStoreAction((MVT::SimpleValueType)VT, 444 (MVT::SimpleValueType)InnerVT, Expand); 445 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand); 446 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand); 447 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand); 448 } 449 450 setOperationAction(ISD::ConstantFP, MVT::f32, Custom); 451 setOperationAction(ISD::ConstantFP, MVT::f64, Custom); 452 453 if (Subtarget->hasNEON()) { 454 addDRTypeForNEON(MVT::v2f32); 455 addDRTypeForNEON(MVT::v8i8); 456 addDRTypeForNEON(MVT::v4i16); 457 addDRTypeForNEON(MVT::v2i32); 458 addDRTypeForNEON(MVT::v1i64); 459 460 addQRTypeForNEON(MVT::v4f32); 461 addQRTypeForNEON(MVT::v2f64); 462 addQRTypeForNEON(MVT::v16i8); 463 addQRTypeForNEON(MVT::v8i16); 464 addQRTypeForNEON(MVT::v4i32); 465 addQRTypeForNEON(MVT::v2i64); 466 467 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but 468 // neither Neon nor VFP support any arithmetic operations on it. 469 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively 470 // supported for v4f32. 471 setOperationAction(ISD::FADD, MVT::v2f64, Expand); 472 setOperationAction(ISD::FSUB, MVT::v2f64, Expand); 473 setOperationAction(ISD::FMUL, MVT::v2f64, Expand); 474 // FIXME: Code duplication: FDIV and FREM are expanded always, see 475 // ARMTargetLowering::addTypeForNEON method for details. 476 setOperationAction(ISD::FDIV, MVT::v2f64, Expand); 477 setOperationAction(ISD::FREM, MVT::v2f64, Expand); 478 // FIXME: Create unittest. 479 // In another words, find a way when "copysign" appears in DAG with vector 480 // operands. 481 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand); 482 // FIXME: Code duplication: SETCC has custom operation action, see 483 // ARMTargetLowering::addTypeForNEON method for details. 484 setOperationAction(ISD::SETCC, MVT::v2f64, Expand); 485 // FIXME: Create unittest for FNEG and for FABS. 486 setOperationAction(ISD::FNEG, MVT::v2f64, Expand); 487 setOperationAction(ISD::FABS, MVT::v2f64, Expand); 488 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand); 489 setOperationAction(ISD::FSIN, MVT::v2f64, Expand); 490 setOperationAction(ISD::FCOS, MVT::v2f64, Expand); 491 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand); 492 setOperationAction(ISD::FPOW, MVT::v2f64, Expand); 493 setOperationAction(ISD::FLOG, MVT::v2f64, Expand); 494 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand); 495 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand); 496 setOperationAction(ISD::FEXP, MVT::v2f64, Expand); 497 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand); 498 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR. 499 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand); 500 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand); 501 setOperationAction(ISD::FRINT, MVT::v2f64, Expand); 502 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand); 503 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand); 504 setOperationAction(ISD::FMA, MVT::v2f64, Expand); 505 506 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 507 setOperationAction(ISD::FSIN, MVT::v4f32, Expand); 508 setOperationAction(ISD::FCOS, MVT::v4f32, Expand); 509 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand); 510 setOperationAction(ISD::FPOW, MVT::v4f32, Expand); 511 setOperationAction(ISD::FLOG, MVT::v4f32, Expand); 512 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand); 513 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand); 514 setOperationAction(ISD::FEXP, MVT::v4f32, Expand); 515 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand); 516 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand); 517 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand); 518 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 519 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 520 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand); 521 522 // Mark v2f32 intrinsics. 523 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand); 524 setOperationAction(ISD::FSIN, MVT::v2f32, Expand); 525 setOperationAction(ISD::FCOS, MVT::v2f32, Expand); 526 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand); 527 setOperationAction(ISD::FPOW, MVT::v2f32, Expand); 528 setOperationAction(ISD::FLOG, MVT::v2f32, Expand); 529 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand); 530 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand); 531 setOperationAction(ISD::FEXP, MVT::v2f32, Expand); 532 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand); 533 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand); 534 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand); 535 setOperationAction(ISD::FRINT, MVT::v2f32, Expand); 536 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand); 537 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand); 538 539 // Neon does not support some operations on v1i64 and v2i64 types. 540 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 541 // Custom handling for some quad-vector types to detect VMULL. 542 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 543 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 544 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 545 // Custom handling for some vector types to avoid expensive expansions 546 setOperationAction(ISD::SDIV, MVT::v4i16, Custom); 547 setOperationAction(ISD::SDIV, MVT::v8i8, Custom); 548 setOperationAction(ISD::UDIV, MVT::v4i16, Custom); 549 setOperationAction(ISD::UDIV, MVT::v8i8, Custom); 550 setOperationAction(ISD::SETCC, MVT::v1i64, Expand); 551 setOperationAction(ISD::SETCC, MVT::v2i64, Expand); 552 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with 553 // a destination type that is wider than the source, and nor does 554 // it have a FP_TO_[SU]INT instruction with a narrower destination than 555 // source. 556 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 557 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 558 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom); 559 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom); 560 561 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 562 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand); 563 564 // NEON does not have single instruction CTPOP for vectors with element 565 // types wider than 8-bits. However, custom lowering can leverage the 566 // v8i8/v16i8 vcnt instruction. 567 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom); 568 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom); 569 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom); 570 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom); 571 572 // NEON only has FMA instructions as of VFP4. 573 if (!Subtarget->hasVFP4()) { 574 setOperationAction(ISD::FMA, MVT::v2f32, Expand); 575 setOperationAction(ISD::FMA, MVT::v4f32, Expand); 576 } 577 578 setTargetDAGCombine(ISD::INTRINSIC_VOID); 579 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 580 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 581 setTargetDAGCombine(ISD::SHL); 582 setTargetDAGCombine(ISD::SRL); 583 setTargetDAGCombine(ISD::SRA); 584 setTargetDAGCombine(ISD::SIGN_EXTEND); 585 setTargetDAGCombine(ISD::ZERO_EXTEND); 586 setTargetDAGCombine(ISD::ANY_EXTEND); 587 setTargetDAGCombine(ISD::SELECT_CC); 588 setTargetDAGCombine(ISD::BUILD_VECTOR); 589 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 590 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 591 setTargetDAGCombine(ISD::STORE); 592 setTargetDAGCombine(ISD::FP_TO_SINT); 593 setTargetDAGCombine(ISD::FP_TO_UINT); 594 setTargetDAGCombine(ISD::FDIV); 595 596 // It is legal to extload from v4i8 to v4i16 or v4i32. 597 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8, 598 MVT::v4i16, MVT::v2i16, 599 MVT::v2i32}; 600 for (unsigned i = 0; i < 6; ++i) { 601 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal); 602 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal); 603 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal); 604 } 605 } 606 607 // ARM and Thumb2 support UMLAL/SMLAL. 608 if (!Subtarget->isThumb1Only()) 609 setTargetDAGCombine(ISD::ADDC); 610 611 612 computeRegisterProperties(); 613 614 // ARM does not have f32 extending load. 615 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand); 616 617 // ARM does not have i1 sign extending load. 618 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 619 620 // ARM supports all 4 flavors of integer indexed load / store. 621 if (!Subtarget->isThumb1Only()) { 622 for (unsigned im = (unsigned)ISD::PRE_INC; 623 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 624 setIndexedLoadAction(im, MVT::i1, Legal); 625 setIndexedLoadAction(im, MVT::i8, Legal); 626 setIndexedLoadAction(im, MVT::i16, Legal); 627 setIndexedLoadAction(im, MVT::i32, Legal); 628 setIndexedStoreAction(im, MVT::i1, Legal); 629 setIndexedStoreAction(im, MVT::i8, Legal); 630 setIndexedStoreAction(im, MVT::i16, Legal); 631 setIndexedStoreAction(im, MVT::i32, Legal); 632 } 633 } 634 635 // i64 operation support. 636 setOperationAction(ISD::MUL, MVT::i64, Expand); 637 setOperationAction(ISD::MULHU, MVT::i32, Expand); 638 if (Subtarget->isThumb1Only()) { 639 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 640 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 641 } 642 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops() 643 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP())) 644 setOperationAction(ISD::MULHS, MVT::i32, Expand); 645 646 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 647 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 648 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 649 setOperationAction(ISD::SRL, MVT::i64, Custom); 650 setOperationAction(ISD::SRA, MVT::i64, Custom); 651 652 if (!Subtarget->isThumb1Only()) { 653 // FIXME: We should do this for Thumb1 as well. 654 setOperationAction(ISD::ADDC, MVT::i32, Custom); 655 setOperationAction(ISD::ADDE, MVT::i32, Custom); 656 setOperationAction(ISD::SUBC, MVT::i32, Custom); 657 setOperationAction(ISD::SUBE, MVT::i32, Custom); 658 } 659 660 // ARM does not have ROTL. 661 setOperationAction(ISD::ROTL, MVT::i32, Expand); 662 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 663 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 664 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) 665 setOperationAction(ISD::CTLZ, MVT::i32, Expand); 666 667 // These just redirect to CTTZ and CTLZ on ARM. 668 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand); 669 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand); 670 671 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom); 672 673 // Only ARMv6 has BSWAP. 674 if (!Subtarget->hasV6Ops()) 675 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 676 677 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) && 678 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) { 679 // These are expanded into libcalls if the cpu doesn't have HW divider. 680 setOperationAction(ISD::SDIV, MVT::i32, Expand); 681 setOperationAction(ISD::UDIV, MVT::i32, Expand); 682 } 683 684 // FIXME: Also set divmod for SREM on EABI 685 setOperationAction(ISD::SREM, MVT::i32, Expand); 686 setOperationAction(ISD::UREM, MVT::i32, Expand); 687 // Register based DivRem for AEABI (RTABI 4.2) 688 if (Subtarget->isTargetAEABI()) { 689 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod"); 690 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod"); 691 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod"); 692 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod"); 693 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod"); 694 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod"); 695 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod"); 696 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod"); 697 698 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS); 699 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS); 700 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS); 701 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS); 702 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS); 703 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS); 704 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS); 705 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS); 706 707 setOperationAction(ISD::SDIVREM, MVT::i32, Custom); 708 setOperationAction(ISD::UDIVREM, MVT::i32, Custom); 709 } else { 710 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 711 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 712 } 713 714 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 715 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 716 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom); 717 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 718 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 719 720 setOperationAction(ISD::TRAP, MVT::Other, Legal); 721 722 // Use the default implementation. 723 setOperationAction(ISD::VASTART, MVT::Other, Custom); 724 setOperationAction(ISD::VAARG, MVT::Other, Expand); 725 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 726 setOperationAction(ISD::VAEND, MVT::Other, Expand); 727 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 728 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 729 730 if (!Subtarget->isTargetMachO()) { 731 // Non-MachO platforms may return values in these registers via the 732 // personality function. 733 setExceptionPointerRegister(ARM::R0); 734 setExceptionSelectorRegister(ARM::R1); 735 } 736 737 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 738 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use 739 // the default expansion. 740 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) { 741 // ATOMIC_FENCE needs custom lowering; the others should have been expanded 742 // to ldrex/strex loops already. 743 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 744 745 // On v8, we have particularly efficient implementations of atomic fences 746 // if they can be combined with nearby atomic loads and stores. 747 if (!Subtarget->hasV8Ops()) { 748 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc. 749 setInsertFencesForAtomic(true); 750 } 751 } else { 752 // If there's anything we can use as a barrier, go through custom lowering 753 // for ATOMIC_FENCE. 754 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, 755 Subtarget->hasAnyDataBarrier() ? Custom : Expand); 756 757 // Set them all for expansion, which will force libcalls. 758 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand); 759 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand); 760 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand); 761 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand); 762 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand); 763 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand); 764 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand); 765 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand); 766 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand); 767 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand); 768 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand); 769 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand); 770 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the 771 // Unordered/Monotonic case. 772 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom); 773 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom); 774 } 775 776 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 777 778 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes. 779 if (!Subtarget->hasV6Ops()) { 780 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand); 781 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand); 782 } 783 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 784 785 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() && 786 !Subtarget->isThumb1Only()) { 787 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR 788 // iff target supports vfp2. 789 setOperationAction(ISD::BITCAST, MVT::i64, Custom); 790 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 791 } 792 793 // We want to custom lower some of our intrinsics. 794 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 795 if (Subtarget->isTargetDarwin()) { 796 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 797 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 798 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 799 } 800 801 setOperationAction(ISD::SETCC, MVT::i32, Expand); 802 setOperationAction(ISD::SETCC, MVT::f32, Expand); 803 setOperationAction(ISD::SETCC, MVT::f64, Expand); 804 setOperationAction(ISD::SELECT, MVT::i32, Custom); 805 setOperationAction(ISD::SELECT, MVT::f32, Custom); 806 setOperationAction(ISD::SELECT, MVT::f64, Custom); 807 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 808 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 809 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 810 811 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 812 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 813 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 814 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 815 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 816 817 // We don't support sin/cos/fmod/copysign/pow 818 setOperationAction(ISD::FSIN, MVT::f64, Expand); 819 setOperationAction(ISD::FSIN, MVT::f32, Expand); 820 setOperationAction(ISD::FCOS, MVT::f32, Expand); 821 setOperationAction(ISD::FCOS, MVT::f64, Expand); 822 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 823 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 824 setOperationAction(ISD::FREM, MVT::f64, Expand); 825 setOperationAction(ISD::FREM, MVT::f32, Expand); 826 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() && 827 !Subtarget->isThumb1Only()) { 828 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 829 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 830 } 831 setOperationAction(ISD::FPOW, MVT::f64, Expand); 832 setOperationAction(ISD::FPOW, MVT::f32, Expand); 833 834 if (!Subtarget->hasVFP4()) { 835 setOperationAction(ISD::FMA, MVT::f64, Expand); 836 setOperationAction(ISD::FMA, MVT::f32, Expand); 837 } 838 839 // Various VFP goodness 840 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) { 841 // int <-> fp are custom expanded into bit_convert + ARMISD ops. 842 if (Subtarget->hasVFP2()) { 843 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 844 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 845 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 846 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 847 } 848 // Special handling for half-precision FP. 849 if (!Subtarget->hasFP16()) { 850 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand); 851 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand); 852 } 853 } 854 855 // Combine sin / cos into one node or libcall if possible. 856 if (Subtarget->hasSinCos()) { 857 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 858 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 859 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) { 860 // For iOS, we don't want to the normal expansion of a libcall to 861 // sincos. We want to issue a libcall to __sincos_stret. 862 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 863 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 864 } 865 } 866 867 // We have target-specific dag combine patterns for the following nodes: 868 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine 869 setTargetDAGCombine(ISD::ADD); 870 setTargetDAGCombine(ISD::SUB); 871 setTargetDAGCombine(ISD::MUL); 872 setTargetDAGCombine(ISD::AND); 873 setTargetDAGCombine(ISD::OR); 874 setTargetDAGCombine(ISD::XOR); 875 876 if (Subtarget->hasV6Ops()) 877 setTargetDAGCombine(ISD::SRL); 878 879 setStackPointerRegisterToSaveRestore(ARM::SP); 880 881 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() || 882 !Subtarget->hasVFP2()) 883 setSchedulingPreference(Sched::RegPressure); 884 else 885 setSchedulingPreference(Sched::Hybrid); 886 887 //// temporary - rewrite interface to use type 888 MaxStoresPerMemset = 8; 889 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 890 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores 891 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2; 892 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores 893 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2; 894 895 // On ARM arguments smaller than 4 bytes are extended, so all arguments 896 // are at least 4 bytes aligned. 897 setMinStackArgumentAlignment(4); 898 899 // Prefer likely predicted branches to selects on out-of-order cores. 900 PredictableSelectIsExpensive = Subtarget->isLikeA9(); 901 902 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2); 903 } 904 905 // FIXME: It might make sense to define the representative register class as the 906 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is 907 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently, 908 // SPR's representative would be DPR_VFP2. This should work well if register 909 // pressure tracking were modified such that a register use would increment the 910 // pressure of the register class's representative and all of it's super 911 // classes' representatives transitively. We have not implemented this because 912 // of the difficulty prior to coalescing of modeling operand register classes 913 // due to the common occurrence of cross class copies and subregister insertions 914 // and extractions. 915 std::pair<const TargetRegisterClass*, uint8_t> 916 ARMTargetLowering::findRepresentativeClass(MVT VT) const{ 917 const TargetRegisterClass *RRC = 0; 918 uint8_t Cost = 1; 919 switch (VT.SimpleTy) { 920 default: 921 return TargetLowering::findRepresentativeClass(VT); 922 // Use DPR as representative register class for all floating point 923 // and vector types. Since there are 32 SPR registers and 32 DPR registers so 924 // the cost is 1 for both f32 and f64. 925 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16: 926 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32: 927 RRC = &ARM::DPRRegClass; 928 // When NEON is used for SP, only half of the register file is available 929 // because operations that define both SP and DP results will be constrained 930 // to the VFP2 class (D0-D15). We currently model this constraint prior to 931 // coalescing by double-counting the SP regs. See the FIXME above. 932 if (Subtarget->useNEONForSinglePrecisionFP()) 933 Cost = 2; 934 break; 935 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 936 case MVT::v4f32: case MVT::v2f64: 937 RRC = &ARM::DPRRegClass; 938 Cost = 2; 939 break; 940 case MVT::v4i64: 941 RRC = &ARM::DPRRegClass; 942 Cost = 4; 943 break; 944 case MVT::v8i64: 945 RRC = &ARM::DPRRegClass; 946 Cost = 8; 947 break; 948 } 949 return std::make_pair(RRC, Cost); 950 } 951 952 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const { 953 switch (Opcode) { 954 default: return 0; 955 case ARMISD::Wrapper: return "ARMISD::Wrapper"; 956 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC"; 957 case ARMISD::WrapperJT: return "ARMISD::WrapperJT"; 958 case ARMISD::CALL: return "ARMISD::CALL"; 959 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED"; 960 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK"; 961 case ARMISD::tCALL: return "ARMISD::tCALL"; 962 case ARMISD::BRCOND: return "ARMISD::BRCOND"; 963 case ARMISD::BR_JT: return "ARMISD::BR_JT"; 964 case ARMISD::BR2_JT: return "ARMISD::BR2_JT"; 965 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG"; 966 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG"; 967 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD"; 968 case ARMISD::CMP: return "ARMISD::CMP"; 969 case ARMISD::CMN: return "ARMISD::CMN"; 970 case ARMISD::CMPZ: return "ARMISD::CMPZ"; 971 case ARMISD::CMPFP: return "ARMISD::CMPFP"; 972 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0"; 973 case ARMISD::BCC_i64: return "ARMISD::BCC_i64"; 974 case ARMISD::FMSTAT: return "ARMISD::FMSTAT"; 975 976 case ARMISD::CMOV: return "ARMISD::CMOV"; 977 978 case ARMISD::RBIT: return "ARMISD::RBIT"; 979 980 case ARMISD::FTOSI: return "ARMISD::FTOSI"; 981 case ARMISD::FTOUI: return "ARMISD::FTOUI"; 982 case ARMISD::SITOF: return "ARMISD::SITOF"; 983 case ARMISD::UITOF: return "ARMISD::UITOF"; 984 985 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG"; 986 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG"; 987 case ARMISD::RRX: return "ARMISD::RRX"; 988 989 case ARMISD::ADDC: return "ARMISD::ADDC"; 990 case ARMISD::ADDE: return "ARMISD::ADDE"; 991 case ARMISD::SUBC: return "ARMISD::SUBC"; 992 case ARMISD::SUBE: return "ARMISD::SUBE"; 993 994 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD"; 995 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR"; 996 997 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP"; 998 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP"; 999 1000 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN"; 1001 1002 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER"; 1003 1004 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC"; 1005 1006 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR"; 1007 1008 case ARMISD::PRELOAD: return "ARMISD::PRELOAD"; 1009 1010 case ARMISD::VCEQ: return "ARMISD::VCEQ"; 1011 case ARMISD::VCEQZ: return "ARMISD::VCEQZ"; 1012 case ARMISD::VCGE: return "ARMISD::VCGE"; 1013 case ARMISD::VCGEZ: return "ARMISD::VCGEZ"; 1014 case ARMISD::VCLEZ: return "ARMISD::VCLEZ"; 1015 case ARMISD::VCGEU: return "ARMISD::VCGEU"; 1016 case ARMISD::VCGT: return "ARMISD::VCGT"; 1017 case ARMISD::VCGTZ: return "ARMISD::VCGTZ"; 1018 case ARMISD::VCLTZ: return "ARMISD::VCLTZ"; 1019 case ARMISD::VCGTU: return "ARMISD::VCGTU"; 1020 case ARMISD::VTST: return "ARMISD::VTST"; 1021 1022 case ARMISD::VSHL: return "ARMISD::VSHL"; 1023 case ARMISD::VSHRs: return "ARMISD::VSHRs"; 1024 case ARMISD::VSHRu: return "ARMISD::VSHRu"; 1025 case ARMISD::VRSHRs: return "ARMISD::VRSHRs"; 1026 case ARMISD::VRSHRu: return "ARMISD::VRSHRu"; 1027 case ARMISD::VRSHRN: return "ARMISD::VRSHRN"; 1028 case ARMISD::VQSHLs: return "ARMISD::VQSHLs"; 1029 case ARMISD::VQSHLu: return "ARMISD::VQSHLu"; 1030 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu"; 1031 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs"; 1032 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu"; 1033 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu"; 1034 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs"; 1035 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu"; 1036 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu"; 1037 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu"; 1038 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs"; 1039 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM"; 1040 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM"; 1041 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM"; 1042 case ARMISD::VDUP: return "ARMISD::VDUP"; 1043 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE"; 1044 case ARMISD::VEXT: return "ARMISD::VEXT"; 1045 case ARMISD::VREV64: return "ARMISD::VREV64"; 1046 case ARMISD::VREV32: return "ARMISD::VREV32"; 1047 case ARMISD::VREV16: return "ARMISD::VREV16"; 1048 case ARMISD::VZIP: return "ARMISD::VZIP"; 1049 case ARMISD::VUZP: return "ARMISD::VUZP"; 1050 case ARMISD::VTRN: return "ARMISD::VTRN"; 1051 case ARMISD::VTBL1: return "ARMISD::VTBL1"; 1052 case ARMISD::VTBL2: return "ARMISD::VTBL2"; 1053 case ARMISD::VMULLs: return "ARMISD::VMULLs"; 1054 case ARMISD::VMULLu: return "ARMISD::VMULLu"; 1055 case ARMISD::UMLAL: return "ARMISD::UMLAL"; 1056 case ARMISD::SMLAL: return "ARMISD::SMLAL"; 1057 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR"; 1058 case ARMISD::FMAX: return "ARMISD::FMAX"; 1059 case ARMISD::FMIN: return "ARMISD::FMIN"; 1060 case ARMISD::VMAXNM: return "ARMISD::VMAX"; 1061 case ARMISD::VMINNM: return "ARMISD::VMIN"; 1062 case ARMISD::BFI: return "ARMISD::BFI"; 1063 case ARMISD::VORRIMM: return "ARMISD::VORRIMM"; 1064 case ARMISD::VBICIMM: return "ARMISD::VBICIMM"; 1065 case ARMISD::VBSL: return "ARMISD::VBSL"; 1066 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP"; 1067 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP"; 1068 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP"; 1069 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD"; 1070 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD"; 1071 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD"; 1072 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD"; 1073 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD"; 1074 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD"; 1075 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD"; 1076 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD"; 1077 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD"; 1078 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD"; 1079 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD"; 1080 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD"; 1081 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD"; 1082 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD"; 1083 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD"; 1084 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD"; 1085 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD"; 1086 } 1087 } 1088 1089 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const { 1090 if (!VT.isVector()) return getPointerTy(); 1091 return VT.changeVectorElementTypeToInteger(); 1092 } 1093 1094 /// getRegClassFor - Return the register class that should be used for the 1095 /// specified value type. 1096 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const { 1097 // Map v4i64 to QQ registers but do not make the type legal. Similarly map 1098 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to 1099 // load / store 4 to 8 consecutive D registers. 1100 if (Subtarget->hasNEON()) { 1101 if (VT == MVT::v4i64) 1102 return &ARM::QQPRRegClass; 1103 if (VT == MVT::v8i64) 1104 return &ARM::QQQQPRRegClass; 1105 } 1106 return TargetLowering::getRegClassFor(VT); 1107 } 1108 1109 // Create a fast isel object. 1110 FastISel * 1111 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1112 const TargetLibraryInfo *libInfo) const { 1113 return ARM::createFastISel(funcInfo, libInfo); 1114 } 1115 1116 /// getMaximalGlobalOffset - Returns the maximal possible offset which can 1117 /// be used for loads / stores from the global. 1118 unsigned ARMTargetLowering::getMaximalGlobalOffset() const { 1119 return (Subtarget->isThumb1Only() ? 127 : 4095); 1120 } 1121 1122 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const { 1123 unsigned NumVals = N->getNumValues(); 1124 if (!NumVals) 1125 return Sched::RegPressure; 1126 1127 for (unsigned i = 0; i != NumVals; ++i) { 1128 EVT VT = N->getValueType(i); 1129 if (VT == MVT::Glue || VT == MVT::Other) 1130 continue; 1131 if (VT.isFloatingPoint() || VT.isVector()) 1132 return Sched::ILP; 1133 } 1134 1135 if (!N->isMachineOpcode()) 1136 return Sched::RegPressure; 1137 1138 // Load are scheduled for latency even if there instruction itinerary 1139 // is not available. 1140 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 1141 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); 1142 1143 if (MCID.getNumDefs() == 0) 1144 return Sched::RegPressure; 1145 if (!Itins->isEmpty() && 1146 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2) 1147 return Sched::ILP; 1148 1149 return Sched::RegPressure; 1150 } 1151 1152 //===----------------------------------------------------------------------===// 1153 // Lowering Code 1154 //===----------------------------------------------------------------------===// 1155 1156 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC 1157 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) { 1158 switch (CC) { 1159 default: llvm_unreachable("Unknown condition code!"); 1160 case ISD::SETNE: return ARMCC::NE; 1161 case ISD::SETEQ: return ARMCC::EQ; 1162 case ISD::SETGT: return ARMCC::GT; 1163 case ISD::SETGE: return ARMCC::GE; 1164 case ISD::SETLT: return ARMCC::LT; 1165 case ISD::SETLE: return ARMCC::LE; 1166 case ISD::SETUGT: return ARMCC::HI; 1167 case ISD::SETUGE: return ARMCC::HS; 1168 case ISD::SETULT: return ARMCC::LO; 1169 case ISD::SETULE: return ARMCC::LS; 1170 } 1171 } 1172 1173 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. 1174 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 1175 ARMCC::CondCodes &CondCode2) { 1176 CondCode2 = ARMCC::AL; 1177 switch (CC) { 1178 default: llvm_unreachable("Unknown FP condition!"); 1179 case ISD::SETEQ: 1180 case ISD::SETOEQ: CondCode = ARMCC::EQ; break; 1181 case ISD::SETGT: 1182 case ISD::SETOGT: CondCode = ARMCC::GT; break; 1183 case ISD::SETGE: 1184 case ISD::SETOGE: CondCode = ARMCC::GE; break; 1185 case ISD::SETOLT: CondCode = ARMCC::MI; break; 1186 case ISD::SETOLE: CondCode = ARMCC::LS; break; 1187 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break; 1188 case ISD::SETO: CondCode = ARMCC::VC; break; 1189 case ISD::SETUO: CondCode = ARMCC::VS; break; 1190 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break; 1191 case ISD::SETUGT: CondCode = ARMCC::HI; break; 1192 case ISD::SETUGE: CondCode = ARMCC::PL; break; 1193 case ISD::SETLT: 1194 case ISD::SETULT: CondCode = ARMCC::LT; break; 1195 case ISD::SETLE: 1196 case ISD::SETULE: CondCode = ARMCC::LE; break; 1197 case ISD::SETNE: 1198 case ISD::SETUNE: CondCode = ARMCC::NE; break; 1199 } 1200 } 1201 1202 //===----------------------------------------------------------------------===// 1203 // Calling Convention Implementation 1204 //===----------------------------------------------------------------------===// 1205 1206 #include "ARMGenCallingConv.inc" 1207 1208 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the 1209 /// given CallingConvention value. 1210 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC, 1211 bool Return, 1212 bool isVarArg) const { 1213 switch (CC) { 1214 default: 1215 llvm_unreachable("Unsupported calling convention"); 1216 case CallingConv::Fast: 1217 if (Subtarget->hasVFP2() && !isVarArg) { 1218 if (!Subtarget->isAAPCS_ABI()) 1219 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS); 1220 // For AAPCS ABI targets, just use VFP variant of the calling convention. 1221 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1222 } 1223 // Fallthrough 1224 case CallingConv::C: { 1225 // Use target triple & subtarget features to do actual dispatch. 1226 if (!Subtarget->isAAPCS_ABI()) 1227 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1228 else if (Subtarget->hasVFP2() && 1229 getTargetMachine().Options.FloatABIType == FloatABI::Hard && 1230 !isVarArg) 1231 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1232 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1233 } 1234 case CallingConv::ARM_AAPCS_VFP: 1235 if (!isVarArg) 1236 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP); 1237 // Fallthrough 1238 case CallingConv::ARM_AAPCS: 1239 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS); 1240 case CallingConv::ARM_APCS: 1241 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS); 1242 case CallingConv::GHC: 1243 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC); 1244 } 1245 } 1246 1247 /// LowerCallResult - Lower the result values of a call into the 1248 /// appropriate copies out of appropriate physical registers. 1249 SDValue 1250 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1251 CallingConv::ID CallConv, bool isVarArg, 1252 const SmallVectorImpl<ISD::InputArg> &Ins, 1253 SDLoc dl, SelectionDAG &DAG, 1254 SmallVectorImpl<SDValue> &InVals, 1255 bool isThisReturn, SDValue ThisVal) const { 1256 1257 // Assign locations to each value returned by this call. 1258 SmallVector<CCValAssign, 16> RVLocs; 1259 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1260 getTargetMachine(), RVLocs, *DAG.getContext(), Call); 1261 CCInfo.AnalyzeCallResult(Ins, 1262 CCAssignFnForNode(CallConv, /* Return*/ true, 1263 isVarArg)); 1264 1265 // Copy all of the result registers out of their specified physreg. 1266 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1267 CCValAssign VA = RVLocs[i]; 1268 1269 // Pass 'this' value directly from the argument to return value, to avoid 1270 // reg unit interference 1271 if (i == 0 && isThisReturn) { 1272 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 && 1273 "unexpected return calling convention register assignment"); 1274 InVals.push_back(ThisVal); 1275 continue; 1276 } 1277 1278 SDValue Val; 1279 if (VA.needsCustom()) { 1280 // Handle f64 or half of a v2f64. 1281 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1282 InFlag); 1283 Chain = Lo.getValue(1); 1284 InFlag = Lo.getValue(2); 1285 VA = RVLocs[++i]; // skip ahead to next loc 1286 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 1287 InFlag); 1288 Chain = Hi.getValue(1); 1289 InFlag = Hi.getValue(2); 1290 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1291 1292 if (VA.getLocVT() == MVT::v2f64) { 1293 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 1294 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1295 DAG.getConstant(0, MVT::i32)); 1296 1297 VA = RVLocs[++i]; // skip ahead to next loc 1298 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1299 Chain = Lo.getValue(1); 1300 InFlag = Lo.getValue(2); 1301 VA = RVLocs[++i]; // skip ahead to next loc 1302 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag); 1303 Chain = Hi.getValue(1); 1304 InFlag = Hi.getValue(2); 1305 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 1306 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val, 1307 DAG.getConstant(1, MVT::i32)); 1308 } 1309 } else { 1310 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), 1311 InFlag); 1312 Chain = Val.getValue(1); 1313 InFlag = Val.getValue(2); 1314 } 1315 1316 switch (VA.getLocInfo()) { 1317 default: llvm_unreachable("Unknown loc info!"); 1318 case CCValAssign::Full: break; 1319 case CCValAssign::BCvt: 1320 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val); 1321 break; 1322 } 1323 1324 InVals.push_back(Val); 1325 } 1326 1327 return Chain; 1328 } 1329 1330 /// LowerMemOpCallTo - Store the argument to the stack. 1331 SDValue 1332 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, 1333 SDValue StackPtr, SDValue Arg, 1334 SDLoc dl, SelectionDAG &DAG, 1335 const CCValAssign &VA, 1336 ISD::ArgFlagsTy Flags) const { 1337 unsigned LocMemOffset = VA.getLocMemOffset(); 1338 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 1339 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 1340 return DAG.getStore(Chain, dl, Arg, PtrOff, 1341 MachinePointerInfo::getStack(LocMemOffset), 1342 false, false, 0); 1343 } 1344 1345 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG, 1346 SDValue Chain, SDValue &Arg, 1347 RegsToPassVector &RegsToPass, 1348 CCValAssign &VA, CCValAssign &NextVA, 1349 SDValue &StackPtr, 1350 SmallVectorImpl<SDValue> &MemOpChains, 1351 ISD::ArgFlagsTy Flags) const { 1352 1353 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 1354 DAG.getVTList(MVT::i32, MVT::i32), Arg); 1355 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd)); 1356 1357 if (NextVA.isRegLoc()) 1358 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1))); 1359 else { 1360 assert(NextVA.isMemLoc()); 1361 if (StackPtr.getNode() == 0) 1362 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy()); 1363 1364 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1), 1365 dl, DAG, NextVA, 1366 Flags)); 1367 } 1368 } 1369 1370 /// LowerCall - Lowering a call into a callseq_start <- 1371 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter 1372 /// nodes. 1373 SDValue 1374 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 1375 SmallVectorImpl<SDValue> &InVals) const { 1376 SelectionDAG &DAG = CLI.DAG; 1377 SDLoc &dl = CLI.DL; 1378 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1379 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1380 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1381 SDValue Chain = CLI.Chain; 1382 SDValue Callee = CLI.Callee; 1383 bool &isTailCall = CLI.IsTailCall; 1384 CallingConv::ID CallConv = CLI.CallConv; 1385 bool doesNotRet = CLI.DoesNotReturn; 1386 bool isVarArg = CLI.IsVarArg; 1387 1388 MachineFunction &MF = DAG.getMachineFunction(); 1389 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet(); 1390 bool isThisReturn = false; 1391 bool isSibCall = false; 1392 1393 // Disable tail calls if they're not supported. 1394 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls) 1395 isTailCall = false; 1396 1397 if (isTailCall) { 1398 // Check if it's really possible to do a tail call. 1399 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1400 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(), 1401 Outs, OutVals, Ins, DAG); 1402 // We don't support GuaranteedTailCallOpt for ARM, only automatically 1403 // detected sibcalls. 1404 if (isTailCall) { 1405 ++NumTailCalls; 1406 isSibCall = true; 1407 } 1408 } 1409 1410 // Analyze operands of the call, assigning locations to each operand. 1411 SmallVector<CCValAssign, 16> ArgLocs; 1412 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1413 getTargetMachine(), ArgLocs, *DAG.getContext(), Call); 1414 CCInfo.AnalyzeCallOperands(Outs, 1415 CCAssignFnForNode(CallConv, /* Return*/ false, 1416 isVarArg)); 1417 1418 // Get a count of how many bytes are to be pushed on the stack. 1419 unsigned NumBytes = CCInfo.getNextStackOffset(); 1420 1421 // For tail calls, memory operands are available in our caller's stack. 1422 if (isSibCall) 1423 NumBytes = 0; 1424 1425 // Adjust the stack pointer for the new arguments... 1426 // These operations are automatically eliminated by the prolog/epilog pass 1427 if (!isSibCall) 1428 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 1429 dl); 1430 1431 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy()); 1432 1433 RegsToPassVector RegsToPass; 1434 SmallVector<SDValue, 8> MemOpChains; 1435 1436 // Walk the register/memloc assignments, inserting copies/loads. In the case 1437 // of tail call optimization, arguments are handled later. 1438 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1439 i != e; 1440 ++i, ++realArgIdx) { 1441 CCValAssign &VA = ArgLocs[i]; 1442 SDValue Arg = OutVals[realArgIdx]; 1443 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1444 bool isByVal = Flags.isByVal(); 1445 1446 // Promote the value if needed. 1447 switch (VA.getLocInfo()) { 1448 default: llvm_unreachable("Unknown loc info!"); 1449 case CCValAssign::Full: break; 1450 case CCValAssign::SExt: 1451 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 1452 break; 1453 case CCValAssign::ZExt: 1454 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 1455 break; 1456 case CCValAssign::AExt: 1457 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 1458 break; 1459 case CCValAssign::BCvt: 1460 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 1461 break; 1462 } 1463 1464 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces 1465 if (VA.needsCustom()) { 1466 if (VA.getLocVT() == MVT::v2f64) { 1467 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1468 DAG.getConstant(0, MVT::i32)); 1469 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 1470 DAG.getConstant(1, MVT::i32)); 1471 1472 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, 1473 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1474 1475 VA = ArgLocs[++i]; // skip ahead to next loc 1476 if (VA.isRegLoc()) { 1477 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, 1478 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags); 1479 } else { 1480 assert(VA.isMemLoc()); 1481 1482 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1, 1483 dl, DAG, VA, Flags)); 1484 } 1485 } else { 1486 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i], 1487 StackPtr, MemOpChains, Flags); 1488 } 1489 } else if (VA.isRegLoc()) { 1490 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) { 1491 assert(VA.getLocVT() == MVT::i32 && 1492 "unexpected calling convention register assignment"); 1493 assert(!Ins.empty() && Ins[0].VT == MVT::i32 && 1494 "unexpected use of 'returned'"); 1495 isThisReturn = true; 1496 } 1497 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 1498 } else if (isByVal) { 1499 assert(VA.isMemLoc()); 1500 unsigned offset = 0; 1501 1502 // True if this byval aggregate will be split between registers 1503 // and memory. 1504 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount(); 1505 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed(); 1506 1507 if (CurByValIdx < ByValArgsCount) { 1508 1509 unsigned RegBegin, RegEnd; 1510 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd); 1511 1512 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 1513 unsigned int i, j; 1514 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) { 1515 SDValue Const = DAG.getConstant(4*i, MVT::i32); 1516 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 1517 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, 1518 MachinePointerInfo(), 1519 false, false, false, 1520 DAG.InferPtrAlignment(AddArg)); 1521 MemOpChains.push_back(Load.getValue(1)); 1522 RegsToPass.push_back(std::make_pair(j, Load)); 1523 } 1524 1525 // If parameter size outsides register area, "offset" value 1526 // helps us to calculate stack slot for remained part properly. 1527 offset = RegEnd - RegBegin; 1528 1529 CCInfo.nextInRegsParam(); 1530 } 1531 1532 if (Flags.getByValSize() > 4*offset) { 1533 unsigned LocMemOffset = VA.getLocMemOffset(); 1534 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset); 1535 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, 1536 StkPtrOff); 1537 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset); 1538 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset); 1539 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, 1540 MVT::i32); 1541 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32); 1542 1543 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 1544 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode}; 1545 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, 1546 Ops, array_lengthof(Ops))); 1547 } 1548 } else if (!isSibCall) { 1549 assert(VA.isMemLoc()); 1550 1551 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 1552 dl, DAG, VA, Flags)); 1553 } 1554 } 1555 1556 if (!MemOpChains.empty()) 1557 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 1558 &MemOpChains[0], MemOpChains.size()); 1559 1560 // Build a sequence of copy-to-reg nodes chained together with token chain 1561 // and flag operands which copy the outgoing args into the appropriate regs. 1562 SDValue InFlag; 1563 // Tail call byval lowering might overwrite argument registers so in case of 1564 // tail call optimization the copies to registers are lowered later. 1565 if (!isTailCall) 1566 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1567 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1568 RegsToPass[i].second, InFlag); 1569 InFlag = Chain.getValue(1); 1570 } 1571 1572 // For tail calls lower the arguments to the 'real' stack slot. 1573 if (isTailCall) { 1574 // Force all the incoming stack arguments to be loaded from the stack 1575 // before any new outgoing arguments are stored to the stack, because the 1576 // outgoing stack slots may alias the incoming argument stack slots, and 1577 // the alias isn't otherwise explicit. This is slightly more conservative 1578 // than necessary, because it means that each store effectively depends 1579 // on every argument instead of just those arguments it would clobber. 1580 1581 // Do not flag preceding copytoreg stuff together with the following stuff. 1582 InFlag = SDValue(); 1583 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 1584 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 1585 RegsToPass[i].second, InFlag); 1586 InFlag = Chain.getValue(1); 1587 } 1588 InFlag = SDValue(); 1589 } 1590 1591 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 1592 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 1593 // node so that legalize doesn't hack it. 1594 bool isDirect = false; 1595 bool isARMFunc = false; 1596 bool isLocalARMFunc = false; 1597 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1598 1599 if (EnableARMLongCalls) { 1600 assert (getTargetMachine().getRelocationModel() == Reloc::Static 1601 && "long-calls with non-static relocation model!"); 1602 // Handle a global address or an external symbol. If it's not one of 1603 // those, the target's already in a register, so we don't need to do 1604 // anything extra. 1605 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1606 const GlobalValue *GV = G->getGlobal(); 1607 // Create a constant pool entry for the callee address 1608 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1609 ARMConstantPoolValue *CPV = 1610 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0); 1611 1612 // Get the address of the callee into a register 1613 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4); 1614 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1615 Callee = DAG.getLoad(getPointerTy(), dl, 1616 DAG.getEntryNode(), CPAddr, 1617 MachinePointerInfo::getConstantPool(), 1618 false, false, false, 0); 1619 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) { 1620 const char *Sym = S->getSymbol(); 1621 1622 // Create a constant pool entry for the callee address 1623 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1624 ARMConstantPoolValue *CPV = 1625 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1626 ARMPCLabelIndex, 0); 1627 // Get the address of the callee into a register 1628 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4); 1629 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1630 Callee = DAG.getLoad(getPointerTy(), dl, 1631 DAG.getEntryNode(), CPAddr, 1632 MachinePointerInfo::getConstantPool(), 1633 false, false, false, 0); 1634 } 1635 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 1636 const GlobalValue *GV = G->getGlobal(); 1637 isDirect = true; 1638 bool isExt = GV->isDeclaration() || GV->isWeakForLinker(); 1639 bool isStub = (isExt && Subtarget->isTargetMachO()) && 1640 getTargetMachine().getRelocationModel() != Reloc::Static; 1641 isARMFunc = !Subtarget->isThumb() || isStub; 1642 // ARM call to a local ARM function is predicable. 1643 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking); 1644 // tBX takes a register source operand. 1645 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1646 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?"); 1647 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(), 1648 DAG.getTargetGlobalAddress(GV, dl, getPointerTy())); 1649 } else { 1650 // On ELF targets for PIC code, direct calls should go through the PLT 1651 unsigned OpFlags = 0; 1652 if (Subtarget->isTargetELF() && 1653 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1654 OpFlags = ARMII::MO_PLT; 1655 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags); 1656 } 1657 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 1658 isDirect = true; 1659 bool isStub = Subtarget->isTargetMachO() && 1660 getTargetMachine().getRelocationModel() != Reloc::Static; 1661 isARMFunc = !Subtarget->isThumb() || isStub; 1662 // tBX takes a register source operand. 1663 const char *Sym = S->getSymbol(); 1664 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) { 1665 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 1666 ARMConstantPoolValue *CPV = 1667 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym, 1668 ARMPCLabelIndex, 4); 1669 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4); 1670 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 1671 Callee = DAG.getLoad(getPointerTy(), dl, 1672 DAG.getEntryNode(), CPAddr, 1673 MachinePointerInfo::getConstantPool(), 1674 false, false, false, 0); 1675 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32); 1676 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, 1677 getPointerTy(), Callee, PICLabel); 1678 } else { 1679 unsigned OpFlags = 0; 1680 // On ELF targets for PIC code, direct calls should go through the PLT 1681 if (Subtarget->isTargetELF() && 1682 getTargetMachine().getRelocationModel() == Reloc::PIC_) 1683 OpFlags = ARMII::MO_PLT; 1684 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags); 1685 } 1686 } 1687 1688 // FIXME: handle tail calls differently. 1689 unsigned CallOpc; 1690 bool HasMinSizeAttr = Subtarget->isMinSize(); 1691 if (Subtarget->isThumb()) { 1692 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps()) 1693 CallOpc = ARMISD::CALL_NOLINK; 1694 else 1695 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL; 1696 } else { 1697 if (!isDirect && !Subtarget->hasV5TOps()) 1698 CallOpc = ARMISD::CALL_NOLINK; 1699 else if (doesNotRet && isDirect && Subtarget->hasRAS() && 1700 // Emit regular call when code size is the priority 1701 !HasMinSizeAttr) 1702 // "mov lr, pc; b _foo" to avoid confusing the RSP 1703 CallOpc = ARMISD::CALL_NOLINK; 1704 else 1705 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL; 1706 } 1707 1708 std::vector<SDValue> Ops; 1709 Ops.push_back(Chain); 1710 Ops.push_back(Callee); 1711 1712 // Add argument registers to the end of the list so that they are known live 1713 // into the call. 1714 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 1715 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 1716 RegsToPass[i].second.getValueType())); 1717 1718 // Add a register mask operand representing the call-preserved registers. 1719 if (!isTailCall) { 1720 const uint32_t *Mask; 1721 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo(); 1722 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI); 1723 if (isThisReturn) { 1724 // For 'this' returns, use the R0-preserving mask if applicable 1725 Mask = ARI->getThisReturnPreservedMask(CallConv); 1726 if (!Mask) { 1727 // Set isThisReturn to false if the calling convention is not one that 1728 // allows 'returned' to be modeled in this way, so LowerCallResult does 1729 // not try to pass 'this' straight through 1730 isThisReturn = false; 1731 Mask = ARI->getCallPreservedMask(CallConv); 1732 } 1733 } else 1734 Mask = ARI->getCallPreservedMask(CallConv); 1735 1736 assert(Mask && "Missing call preserved mask for calling convention"); 1737 Ops.push_back(DAG.getRegisterMask(Mask)); 1738 } 1739 1740 if (InFlag.getNode()) 1741 Ops.push_back(InFlag); 1742 1743 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1744 if (isTailCall) 1745 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size()); 1746 1747 // Returns a chain and a flag for retval copy to use. 1748 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size()); 1749 InFlag = Chain.getValue(1); 1750 1751 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 1752 DAG.getIntPtrConstant(0, true), InFlag, dl); 1753 if (!Ins.empty()) 1754 InFlag = Chain.getValue(1); 1755 1756 // Handle result values, copying them out of physregs into vregs that we 1757 // return. 1758 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, 1759 InVals, isThisReturn, 1760 isThisReturn ? OutVals[0] : SDValue()); 1761 } 1762 1763 /// HandleByVal - Every parameter *after* a byval parameter is passed 1764 /// on the stack. Remember the next parameter register to allocate, 1765 /// and then confiscate the rest of the parameter registers to insure 1766 /// this. 1767 void 1768 ARMTargetLowering::HandleByVal( 1769 CCState *State, unsigned &size, unsigned Align) const { 1770 unsigned reg = State->AllocateReg(GPRArgRegs, 4); 1771 assert((State->getCallOrPrologue() == Prologue || 1772 State->getCallOrPrologue() == Call) && 1773 "unhandled ParmContext"); 1774 1775 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) { 1776 if (Subtarget->isAAPCS_ABI() && Align > 4) { 1777 unsigned AlignInRegs = Align / 4; 1778 unsigned Waste = (ARM::R4 - reg) % AlignInRegs; 1779 for (unsigned i = 0; i < Waste; ++i) 1780 reg = State->AllocateReg(GPRArgRegs, 4); 1781 } 1782 if (reg != 0) { 1783 unsigned excess = 4 * (ARM::R4 - reg); 1784 1785 // Special case when NSAA != SP and parameter size greater than size of 1786 // all remained GPR regs. In that case we can't split parameter, we must 1787 // send it to stack. We also must set NCRN to R4, so waste all 1788 // remained registers. 1789 const unsigned NSAAOffset = State->getNextStackOffset(); 1790 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) { 1791 while (State->AllocateReg(GPRArgRegs, 4)) 1792 ; 1793 return; 1794 } 1795 1796 // First register for byval parameter is the first register that wasn't 1797 // allocated before this method call, so it would be "reg". 1798 // If parameter is small enough to be saved in range [reg, r4), then 1799 // the end (first after last) register would be reg + param-size-in-regs, 1800 // else parameter would be splitted between registers and stack, 1801 // end register would be r4 in this case. 1802 unsigned ByValRegBegin = reg; 1803 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4; 1804 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd); 1805 // Note, first register is allocated in the beginning of function already, 1806 // allocate remained amount of registers we need. 1807 for (unsigned i = reg+1; i != ByValRegEnd; ++i) 1808 State->AllocateReg(GPRArgRegs, 4); 1809 // A byval parameter that is split between registers and memory needs its 1810 // size truncated here. 1811 // In the case where the entire structure fits in registers, we set the 1812 // size in memory to zero. 1813 if (size < excess) 1814 size = 0; 1815 else 1816 size -= excess; 1817 } 1818 } 1819 } 1820 1821 /// MatchingStackOffset - Return true if the given stack call argument is 1822 /// already available in the same position (relatively) of the caller's 1823 /// incoming argument stack. 1824 static 1825 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 1826 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 1827 const TargetInstrInfo *TII) { 1828 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 1829 int FI = INT_MAX; 1830 if (Arg.getOpcode() == ISD::CopyFromReg) { 1831 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 1832 if (!TargetRegisterInfo::isVirtualRegister(VR)) 1833 return false; 1834 MachineInstr *Def = MRI->getVRegDef(VR); 1835 if (!Def) 1836 return false; 1837 if (!Flags.isByVal()) { 1838 if (!TII->isLoadFromStackSlot(Def, FI)) 1839 return false; 1840 } else { 1841 return false; 1842 } 1843 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 1844 if (Flags.isByVal()) 1845 // ByVal argument is passed in as a pointer but it's now being 1846 // dereferenced. e.g. 1847 // define @foo(%struct.X* %A) { 1848 // tail call @bar(%struct.X* byval %A) 1849 // } 1850 return false; 1851 SDValue Ptr = Ld->getBasePtr(); 1852 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 1853 if (!FINode) 1854 return false; 1855 FI = FINode->getIndex(); 1856 } else 1857 return false; 1858 1859 assert(FI != INT_MAX); 1860 if (!MFI->isFixedObjectIndex(FI)) 1861 return false; 1862 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 1863 } 1864 1865 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 1866 /// for tail call optimization. Targets which want to do tail call 1867 /// optimization should implement this function. 1868 bool 1869 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 1870 CallingConv::ID CalleeCC, 1871 bool isVarArg, 1872 bool isCalleeStructRet, 1873 bool isCallerStructRet, 1874 const SmallVectorImpl<ISD::OutputArg> &Outs, 1875 const SmallVectorImpl<SDValue> &OutVals, 1876 const SmallVectorImpl<ISD::InputArg> &Ins, 1877 SelectionDAG& DAG) const { 1878 const Function *CallerF = DAG.getMachineFunction().getFunction(); 1879 CallingConv::ID CallerCC = CallerF->getCallingConv(); 1880 bool CCMatch = CallerCC == CalleeCC; 1881 1882 // Look for obvious safe cases to perform tail call optimization that do not 1883 // require ABI changes. This is what gcc calls sibcall. 1884 1885 // Do not sibcall optimize vararg calls unless the call site is not passing 1886 // any arguments. 1887 if (isVarArg && !Outs.empty()) 1888 return false; 1889 1890 // Exception-handling functions need a special set of instructions to indicate 1891 // a return to the hardware. Tail-calling another function would probably 1892 // break this. 1893 if (CallerF->hasFnAttribute("interrupt")) 1894 return false; 1895 1896 // Also avoid sibcall optimization if either caller or callee uses struct 1897 // return semantics. 1898 if (isCalleeStructRet || isCallerStructRet) 1899 return false; 1900 1901 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo:: 1902 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as 1903 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation 1904 // support in the assembler and linker to be used. This would need to be 1905 // fixed to fully support tail calls in Thumb1. 1906 // 1907 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take 1908 // LR. This means if we need to reload LR, it takes an extra instructions, 1909 // which outweighs the value of the tail call; but here we don't know yet 1910 // whether LR is going to be used. Probably the right approach is to 1911 // generate the tail call here and turn it back into CALL/RET in 1912 // emitEpilogue if LR is used. 1913 1914 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls, 1915 // but we need to make sure there are enough registers; the only valid 1916 // registers are the 4 used for parameters. We don't currently do this 1917 // case. 1918 if (Subtarget->isThumb1Only()) 1919 return false; 1920 1921 // If the calling conventions do not match, then we'd better make sure the 1922 // results are returned in the same way as what the caller expects. 1923 if (!CCMatch) { 1924 SmallVector<CCValAssign, 16> RVLocs1; 1925 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), 1926 getTargetMachine(), RVLocs1, *DAG.getContext(), Call); 1927 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg)); 1928 1929 SmallVector<CCValAssign, 16> RVLocs2; 1930 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), 1931 getTargetMachine(), RVLocs2, *DAG.getContext(), Call); 1932 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg)); 1933 1934 if (RVLocs1.size() != RVLocs2.size()) 1935 return false; 1936 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 1937 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 1938 return false; 1939 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 1940 return false; 1941 if (RVLocs1[i].isRegLoc()) { 1942 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 1943 return false; 1944 } else { 1945 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 1946 return false; 1947 } 1948 } 1949 } 1950 1951 // If Caller's vararg or byval argument has been split between registers and 1952 // stack, do not perform tail call, since part of the argument is in caller's 1953 // local frame. 1954 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction(). 1955 getInfo<ARMFunctionInfo>(); 1956 if (AFI_Caller->getArgRegsSaveSize()) 1957 return false; 1958 1959 // If the callee takes no arguments then go on to check the results of the 1960 // call. 1961 if (!Outs.empty()) { 1962 // Check if stack adjustment is needed. For now, do not do this if any 1963 // argument is passed on the stack. 1964 SmallVector<CCValAssign, 16> ArgLocs; 1965 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 1966 getTargetMachine(), ArgLocs, *DAG.getContext(), Call); 1967 CCInfo.AnalyzeCallOperands(Outs, 1968 CCAssignFnForNode(CalleeCC, false, isVarArg)); 1969 if (CCInfo.getNextStackOffset()) { 1970 MachineFunction &MF = DAG.getMachineFunction(); 1971 1972 // Check if the arguments are already laid out in the right way as 1973 // the caller's fixed stack objects. 1974 MachineFrameInfo *MFI = MF.getFrameInfo(); 1975 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 1976 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 1977 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); 1978 i != e; 1979 ++i, ++realArgIdx) { 1980 CCValAssign &VA = ArgLocs[i]; 1981 EVT RegVT = VA.getLocVT(); 1982 SDValue Arg = OutVals[realArgIdx]; 1983 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 1984 if (VA.getLocInfo() == CCValAssign::Indirect) 1985 return false; 1986 if (VA.needsCustom()) { 1987 // f64 and vector types are split into multiple registers or 1988 // register/stack-slot combinations. The types will not match 1989 // the registers; give up on memory f64 refs until we figure 1990 // out what to do about this. 1991 if (!VA.isRegLoc()) 1992 return false; 1993 if (!ArgLocs[++i].isRegLoc()) 1994 return false; 1995 if (RegVT == MVT::v2f64) { 1996 if (!ArgLocs[++i].isRegLoc()) 1997 return false; 1998 if (!ArgLocs[++i].isRegLoc()) 1999 return false; 2000 } 2001 } else if (!VA.isRegLoc()) { 2002 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2003 MFI, MRI, TII)) 2004 return false; 2005 } 2006 } 2007 } 2008 } 2009 2010 return true; 2011 } 2012 2013 bool 2014 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 2015 MachineFunction &MF, bool isVarArg, 2016 const SmallVectorImpl<ISD::OutputArg> &Outs, 2017 LLVMContext &Context) const { 2018 SmallVector<CCValAssign, 16> RVLocs; 2019 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context); 2020 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true, 2021 isVarArg)); 2022 } 2023 2024 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps, 2025 SDLoc DL, SelectionDAG &DAG) { 2026 const MachineFunction &MF = DAG.getMachineFunction(); 2027 const Function *F = MF.getFunction(); 2028 2029 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString(); 2030 2031 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset 2032 // version of the "preferred return address". These offsets affect the return 2033 // instruction if this is a return from PL1 without hypervisor extensions. 2034 // IRQ/FIQ: +4 "subs pc, lr, #4" 2035 // SWI: 0 "subs pc, lr, #0" 2036 // ABORT: +4 "subs pc, lr, #4" 2037 // UNDEF: +4/+2 "subs pc, lr, #0" 2038 // UNDEF varies depending on where the exception came from ARM or Thumb 2039 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0. 2040 2041 int64_t LROffset; 2042 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" || 2043 IntKind == "ABORT") 2044 LROffset = 4; 2045 else if (IntKind == "SWI" || IntKind == "UNDEF") 2046 LROffset = 0; 2047 else 2048 report_fatal_error("Unsupported interrupt attribute. If present, value " 2049 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF"); 2050 2051 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false)); 2052 2053 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, 2054 RetOps.data(), RetOps.size()); 2055 } 2056 2057 SDValue 2058 ARMTargetLowering::LowerReturn(SDValue Chain, 2059 CallingConv::ID CallConv, bool isVarArg, 2060 const SmallVectorImpl<ISD::OutputArg> &Outs, 2061 const SmallVectorImpl<SDValue> &OutVals, 2062 SDLoc dl, SelectionDAG &DAG) const { 2063 2064 // CCValAssign - represent the assignment of the return value to a location. 2065 SmallVector<CCValAssign, 16> RVLocs; 2066 2067 // CCState - Info about the registers and stack slots. 2068 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 2069 getTargetMachine(), RVLocs, *DAG.getContext(), Call); 2070 2071 // Analyze outgoing return values. 2072 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true, 2073 isVarArg)); 2074 2075 SDValue Flag; 2076 SmallVector<SDValue, 4> RetOps; 2077 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2078 2079 // Copy the result values into the output registers. 2080 for (unsigned i = 0, realRVLocIdx = 0; 2081 i != RVLocs.size(); 2082 ++i, ++realRVLocIdx) { 2083 CCValAssign &VA = RVLocs[i]; 2084 assert(VA.isRegLoc() && "Can only return in registers!"); 2085 2086 SDValue Arg = OutVals[realRVLocIdx]; 2087 2088 switch (VA.getLocInfo()) { 2089 default: llvm_unreachable("Unknown loc info!"); 2090 case CCValAssign::Full: break; 2091 case CCValAssign::BCvt: 2092 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg); 2093 break; 2094 } 2095 2096 if (VA.needsCustom()) { 2097 if (VA.getLocVT() == MVT::v2f64) { 2098 // Extract the first half and return it in two registers. 2099 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2100 DAG.getConstant(0, MVT::i32)); 2101 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl, 2102 DAG.getVTList(MVT::i32, MVT::i32), Half); 2103 2104 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag); 2105 Flag = Chain.getValue(1); 2106 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2107 VA = RVLocs[++i]; // skip ahead to next loc 2108 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 2109 HalfGPRs.getValue(1), Flag); 2110 Flag = Chain.getValue(1); 2111 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2112 VA = RVLocs[++i]; // skip ahead to next loc 2113 2114 // Extract the 2nd half and fall through to handle it as an f64 value. 2115 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg, 2116 DAG.getConstant(1, MVT::i32)); 2117 } 2118 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is 2119 // available. 2120 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl, 2121 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1); 2122 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag); 2123 Flag = Chain.getValue(1); 2124 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2125 VA = RVLocs[++i]; // skip ahead to next loc 2126 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1), 2127 Flag); 2128 } else 2129 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 2130 2131 // Guarantee that all emitted copies are 2132 // stuck together, avoiding something bad. 2133 Flag = Chain.getValue(1); 2134 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2135 } 2136 2137 // Update chain and glue. 2138 RetOps[0] = Chain; 2139 if (Flag.getNode()) 2140 RetOps.push_back(Flag); 2141 2142 // CPUs which aren't M-class use a special sequence to return from 2143 // exceptions (roughly, any instruction setting pc and cpsr simultaneously, 2144 // though we use "subs pc, lr, #N"). 2145 // 2146 // M-class CPUs actually use a normal return sequence with a special 2147 // (hardware-provided) value in LR, so the normal code path works. 2148 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") && 2149 !Subtarget->isMClass()) { 2150 if (Subtarget->isThumb1Only()) 2151 report_fatal_error("interrupt attribute is not supported in Thumb1"); 2152 return LowerInterruptReturn(RetOps, dl, DAG); 2153 } 2154 2155 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, 2156 RetOps.data(), RetOps.size()); 2157 } 2158 2159 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 2160 if (N->getNumValues() != 1) 2161 return false; 2162 if (!N->hasNUsesOfValue(1, 0)) 2163 return false; 2164 2165 SDValue TCChain = Chain; 2166 SDNode *Copy = *N->use_begin(); 2167 if (Copy->getOpcode() == ISD::CopyToReg) { 2168 // If the copy has a glue operand, we conservatively assume it isn't safe to 2169 // perform a tail call. 2170 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 2171 return false; 2172 TCChain = Copy->getOperand(0); 2173 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) { 2174 SDNode *VMov = Copy; 2175 // f64 returned in a pair of GPRs. 2176 SmallPtrSet<SDNode*, 2> Copies; 2177 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2178 UI != UE; ++UI) { 2179 if (UI->getOpcode() != ISD::CopyToReg) 2180 return false; 2181 Copies.insert(*UI); 2182 } 2183 if (Copies.size() > 2) 2184 return false; 2185 2186 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end(); 2187 UI != UE; ++UI) { 2188 SDValue UseChain = UI->getOperand(0); 2189 if (Copies.count(UseChain.getNode())) 2190 // Second CopyToReg 2191 Copy = *UI; 2192 else 2193 // First CopyToReg 2194 TCChain = UseChain; 2195 } 2196 } else if (Copy->getOpcode() == ISD::BITCAST) { 2197 // f32 returned in a single GPR. 2198 if (!Copy->hasOneUse()) 2199 return false; 2200 Copy = *Copy->use_begin(); 2201 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0)) 2202 return false; 2203 TCChain = Copy->getOperand(0); 2204 } else { 2205 return false; 2206 } 2207 2208 bool HasRet = false; 2209 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 2210 UI != UE; ++UI) { 2211 if (UI->getOpcode() != ARMISD::RET_FLAG && 2212 UI->getOpcode() != ARMISD::INTRET_FLAG) 2213 return false; 2214 HasRet = true; 2215 } 2216 2217 if (!HasRet) 2218 return false; 2219 2220 Chain = TCChain; 2221 return true; 2222 } 2223 2224 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2225 if (!Subtarget->supportsTailCall()) 2226 return false; 2227 2228 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls) 2229 return false; 2230 2231 return !Subtarget->isThumb1Only(); 2232 } 2233 2234 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 2235 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is 2236 // one of the above mentioned nodes. It has to be wrapped because otherwise 2237 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 2238 // be used to form addressing mode. These wrapped nodes will be selected 2239 // into MOVi. 2240 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) { 2241 EVT PtrVT = Op.getValueType(); 2242 // FIXME there is no actual debug info here 2243 SDLoc dl(Op); 2244 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2245 SDValue Res; 2246 if (CP->isMachineConstantPoolEntry()) 2247 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 2248 CP->getAlignment()); 2249 else 2250 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 2251 CP->getAlignment()); 2252 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res); 2253 } 2254 2255 unsigned ARMTargetLowering::getJumpTableEncoding() const { 2256 return MachineJumpTableInfo::EK_Inline; 2257 } 2258 2259 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op, 2260 SelectionDAG &DAG) const { 2261 MachineFunction &MF = DAG.getMachineFunction(); 2262 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2263 unsigned ARMPCLabelIndex = 0; 2264 SDLoc DL(Op); 2265 EVT PtrVT = getPointerTy(); 2266 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 2267 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2268 SDValue CPAddr; 2269 if (RelocM == Reloc::Static) { 2270 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4); 2271 } else { 2272 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2273 ARMPCLabelIndex = AFI->createPICLabelUId(); 2274 ARMConstantPoolValue *CPV = 2275 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex, 2276 ARMCP::CPBlockAddress, PCAdj); 2277 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2278 } 2279 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr); 2280 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr, 2281 MachinePointerInfo::getConstantPool(), 2282 false, false, false, 0); 2283 if (RelocM == Reloc::Static) 2284 return Result; 2285 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32); 2286 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel); 2287 } 2288 2289 // Lower ISD::GlobalTLSAddress using the "general dynamic" model 2290 SDValue 2291 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, 2292 SelectionDAG &DAG) const { 2293 SDLoc dl(GA); 2294 EVT PtrVT = getPointerTy(); 2295 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2296 MachineFunction &MF = DAG.getMachineFunction(); 2297 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2298 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2299 ARMConstantPoolValue *CPV = 2300 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2301 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true); 2302 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2303 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument); 2304 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, 2305 MachinePointerInfo::getConstantPool(), 2306 false, false, false, 0); 2307 SDValue Chain = Argument.getValue(1); 2308 2309 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32); 2310 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel); 2311 2312 // call __tls_get_addr. 2313 ArgListTy Args; 2314 ArgListEntry Entry; 2315 Entry.Node = Argument; 2316 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext()); 2317 Args.push_back(Entry); 2318 // FIXME: is there useful debug info available here? 2319 TargetLowering::CallLoweringInfo CLI(Chain, 2320 (Type *) Type::getInt32Ty(*DAG.getContext()), 2321 false, false, false, false, 2322 0, CallingConv::C, /*isTailCall=*/false, 2323 /*doesNotRet=*/false, /*isReturnValueUsed=*/true, 2324 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl); 2325 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2326 return CallResult.first; 2327 } 2328 2329 // Lower ISD::GlobalTLSAddress using the "initial exec" or 2330 // "local exec" model. 2331 SDValue 2332 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA, 2333 SelectionDAG &DAG, 2334 TLSModel::Model model) const { 2335 const GlobalValue *GV = GA->getGlobal(); 2336 SDLoc dl(GA); 2337 SDValue Offset; 2338 SDValue Chain = DAG.getEntryNode(); 2339 EVT PtrVT = getPointerTy(); 2340 // Get the Thread Pointer 2341 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2342 2343 if (model == TLSModel::InitialExec) { 2344 MachineFunction &MF = DAG.getMachineFunction(); 2345 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2346 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2347 // Initial exec model. 2348 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8; 2349 ARMConstantPoolValue *CPV = 2350 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex, 2351 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, 2352 true); 2353 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2354 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2355 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, 2356 MachinePointerInfo::getConstantPool(), 2357 false, false, false, 0); 2358 Chain = Offset.getValue(1); 2359 2360 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32); 2361 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel); 2362 2363 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, 2364 MachinePointerInfo::getConstantPool(), 2365 false, false, false, 0); 2366 } else { 2367 // local exec model 2368 assert(model == TLSModel::LocalExec); 2369 ARMConstantPoolValue *CPV = 2370 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF); 2371 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2372 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset); 2373 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, 2374 MachinePointerInfo::getConstantPool(), 2375 false, false, false, 0); 2376 } 2377 2378 // The address of the thread local variable is the add of the thread 2379 // pointer with the offset of the variable. 2380 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 2381 } 2382 2383 SDValue 2384 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 2385 // TODO: implement the "local dynamic" model 2386 assert(Subtarget->isTargetELF() && 2387 "TLS not implemented for non-ELF targets"); 2388 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2389 2390 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal()); 2391 2392 switch (model) { 2393 case TLSModel::GeneralDynamic: 2394 case TLSModel::LocalDynamic: 2395 return LowerToTLSGeneralDynamicModel(GA, DAG); 2396 case TLSModel::InitialExec: 2397 case TLSModel::LocalExec: 2398 return LowerToTLSExecModels(GA, DAG, model); 2399 } 2400 llvm_unreachable("bogus TLS model"); 2401 } 2402 2403 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op, 2404 SelectionDAG &DAG) const { 2405 EVT PtrVT = getPointerTy(); 2406 SDLoc dl(Op); 2407 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2408 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2409 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility(); 2410 ARMConstantPoolValue *CPV = 2411 ARMConstantPoolConstant::Create(GV, 2412 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT); 2413 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2414 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2415 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 2416 CPAddr, 2417 MachinePointerInfo::getConstantPool(), 2418 false, false, false, 0); 2419 SDValue Chain = Result.getValue(1); 2420 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT); 2421 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT); 2422 if (!UseGOTOFF) 2423 Result = DAG.getLoad(PtrVT, dl, Chain, Result, 2424 MachinePointerInfo::getGOT(), 2425 false, false, false, 0); 2426 return Result; 2427 } 2428 2429 // If we have T2 ops, we can materialize the address directly via movt/movw 2430 // pair. This is always cheaper. 2431 if (Subtarget->useMovt()) { 2432 ++NumMovwMovt; 2433 // FIXME: Once remat is capable of dealing with instructions with register 2434 // operands, expand this into two nodes. 2435 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT, 2436 DAG.getTargetGlobalAddress(GV, dl, PtrVT)); 2437 } else { 2438 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4); 2439 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2440 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, 2441 MachinePointerInfo::getConstantPool(), 2442 false, false, false, 0); 2443 } 2444 } 2445 2446 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op, 2447 SelectionDAG &DAG) const { 2448 EVT PtrVT = getPointerTy(); 2449 SDLoc dl(Op); 2450 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 2451 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2452 2453 if (Subtarget->useMovt()) 2454 ++NumMovwMovt; 2455 2456 // FIXME: Once remat is capable of dealing with instructions with register 2457 // operands, expand this into multiple nodes 2458 unsigned Wrapper = 2459 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper; 2460 2461 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY); 2462 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G); 2463 2464 if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) 2465 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result, 2466 MachinePointerInfo::getGOT(), false, false, false, 0); 2467 return Result; 2468 } 2469 2470 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op, 2471 SelectionDAG &DAG) const { 2472 assert(Subtarget->isTargetELF() && 2473 "GLOBAL OFFSET TABLE not implemented for non-ELF targets"); 2474 MachineFunction &MF = DAG.getMachineFunction(); 2475 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2476 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2477 EVT PtrVT = getPointerTy(); 2478 SDLoc dl(Op); 2479 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8; 2480 ARMConstantPoolValue *CPV = 2481 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_", 2482 ARMPCLabelIndex, PCAdj); 2483 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2484 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2485 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, 2486 MachinePointerInfo::getConstantPool(), 2487 false, false, false, 0); 2488 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32); 2489 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2490 } 2491 2492 SDValue 2493 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { 2494 SDLoc dl(Op); 2495 SDValue Val = DAG.getConstant(0, MVT::i32); 2496 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, 2497 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 2498 Op.getOperand(1), Val); 2499 } 2500 2501 SDValue 2502 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { 2503 SDLoc dl(Op); 2504 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0), 2505 Op.getOperand(1), DAG.getConstant(0, MVT::i32)); 2506 } 2507 2508 SDValue 2509 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG, 2510 const ARMSubtarget *Subtarget) const { 2511 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2512 SDLoc dl(Op); 2513 switch (IntNo) { 2514 default: return SDValue(); // Don't custom lower most intrinsics. 2515 case Intrinsic::arm_thread_pointer: { 2516 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2517 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT); 2518 } 2519 case Intrinsic::eh_sjlj_lsda: { 2520 MachineFunction &MF = DAG.getMachineFunction(); 2521 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2522 unsigned ARMPCLabelIndex = AFI->createPICLabelUId(); 2523 EVT PtrVT = getPointerTy(); 2524 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 2525 SDValue CPAddr; 2526 unsigned PCAdj = (RelocM != Reloc::PIC_) 2527 ? 0 : (Subtarget->isThumb() ? 4 : 8); 2528 ARMConstantPoolValue *CPV = 2529 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex, 2530 ARMCP::CPLSDA, PCAdj); 2531 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4); 2532 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr); 2533 SDValue Result = 2534 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, 2535 MachinePointerInfo::getConstantPool(), 2536 false, false, false, 0); 2537 2538 if (RelocM == Reloc::PIC_) { 2539 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32); 2540 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel); 2541 } 2542 return Result; 2543 } 2544 case Intrinsic::arm_neon_vmulls: 2545 case Intrinsic::arm_neon_vmullu: { 2546 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls) 2547 ? ARMISD::VMULLs : ARMISD::VMULLu; 2548 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(), 2549 Op.getOperand(1), Op.getOperand(2)); 2550 } 2551 } 2552 } 2553 2554 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG, 2555 const ARMSubtarget *Subtarget) { 2556 // FIXME: handle "fence singlethread" more efficiently. 2557 SDLoc dl(Op); 2558 if (!Subtarget->hasDataBarrier()) { 2559 // Some ARMv6 cpus can support data barriers with an mcr instruction. 2560 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get 2561 // here. 2562 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() && 2563 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!"); 2564 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0), 2565 DAG.getConstant(0, MVT::i32)); 2566 } 2567 2568 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1)); 2569 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue()); 2570 unsigned Domain = ARM_MB::ISH; 2571 if (Subtarget->isMClass()) { 2572 // Only a full system barrier exists in the M-class architectures. 2573 Domain = ARM_MB::SY; 2574 } else if (Subtarget->isSwift() && Ord == Release) { 2575 // Swift happens to implement ISHST barriers in a way that's compatible with 2576 // Release semantics but weaker than ISH so we'd be fools not to use 2577 // it. Beware: other processors probably don't! 2578 Domain = ARM_MB::ISHST; 2579 } 2580 2581 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0), 2582 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32), 2583 DAG.getConstant(Domain, MVT::i32)); 2584 } 2585 2586 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG, 2587 const ARMSubtarget *Subtarget) { 2588 // ARM pre v5TE and Thumb1 does not have preload instructions. 2589 if (!(Subtarget->isThumb2() || 2590 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps()))) 2591 // Just preserve the chain. 2592 return Op.getOperand(0); 2593 2594 SDLoc dl(Op); 2595 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1; 2596 if (!isRead && 2597 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension())) 2598 // ARMv7 with MP extension has PLDW. 2599 return Op.getOperand(0); 2600 2601 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2602 if (Subtarget->isThumb()) { 2603 // Invert the bits. 2604 isRead = ~isRead & 1; 2605 isData = ~isData & 1; 2606 } 2607 2608 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0), 2609 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32), 2610 DAG.getConstant(isData, MVT::i32)); 2611 } 2612 2613 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) { 2614 MachineFunction &MF = DAG.getMachineFunction(); 2615 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>(); 2616 2617 // vastart just stores the address of the VarArgsFrameIndex slot into the 2618 // memory location argument. 2619 SDLoc dl(Op); 2620 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(); 2621 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2622 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2623 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2624 MachinePointerInfo(SV), false, false, 0); 2625 } 2626 2627 SDValue 2628 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA, 2629 SDValue &Root, SelectionDAG &DAG, 2630 SDLoc dl) const { 2631 MachineFunction &MF = DAG.getMachineFunction(); 2632 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2633 2634 const TargetRegisterClass *RC; 2635 if (AFI->isThumb1OnlyFunction()) 2636 RC = &ARM::tGPRRegClass; 2637 else 2638 RC = &ARM::GPRRegClass; 2639 2640 // Transform the arguments stored in physical registers into virtual ones. 2641 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2642 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 2643 2644 SDValue ArgValue2; 2645 if (NextVA.isMemLoc()) { 2646 MachineFrameInfo *MFI = MF.getFrameInfo(); 2647 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true); 2648 2649 // Create load node to retrieve arguments from the stack. 2650 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 2651 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN, 2652 MachinePointerInfo::getFixedStack(FI), 2653 false, false, false, 0); 2654 } else { 2655 Reg = MF.addLiveIn(NextVA.getLocReg(), RC); 2656 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32); 2657 } 2658 2659 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2); 2660 } 2661 2662 void 2663 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF, 2664 unsigned InRegsParamRecordIdx, 2665 unsigned ArgSize, 2666 unsigned &ArgRegsSize, 2667 unsigned &ArgRegsSaveSize) 2668 const { 2669 unsigned NumGPRs; 2670 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 2671 unsigned RBegin, REnd; 2672 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 2673 NumGPRs = REnd - RBegin; 2674 } else { 2675 unsigned int firstUnalloced; 2676 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs, 2677 sizeof(GPRArgRegs) / 2678 sizeof(GPRArgRegs[0])); 2679 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0; 2680 } 2681 2682 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment(); 2683 ArgRegsSize = NumGPRs * 4; 2684 2685 // If parameter is split between stack and GPRs... 2686 if (NumGPRs && Align > 4 && 2687 (ArgRegsSize < ArgSize || 2688 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) { 2689 // Add padding for part of param recovered from GPRs. For example, 2690 // if Align == 8, its last byte must be at address K*8 - 1. 2691 // We need to do it, since remained (stack) part of parameter has 2692 // stack alignment, and we need to "attach" "GPRs head" without gaps 2693 // to it: 2694 // Stack: 2695 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes... 2696 // [ [padding] [GPRs head] ] [ Tail passed via stack .... 2697 // 2698 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2699 unsigned Padding = 2700 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align); 2701 ArgRegsSaveSize = ArgRegsSize + Padding; 2702 } else 2703 // We don't need to extend regs save size for byval parameters if they 2704 // are passed via GPRs only. 2705 ArgRegsSaveSize = ArgRegsSize; 2706 } 2707 2708 // The remaining GPRs hold either the beginning of variable-argument 2709 // data, or the beginning of an aggregate passed by value (usually 2710 // byval). Either way, we allocate stack slots adjacent to the data 2711 // provided by our caller, and store the unallocated registers there. 2712 // If this is a variadic function, the va_list pointer will begin with 2713 // these values; otherwise, this reassembles a (byval) structure that 2714 // was split between registers and memory. 2715 // Return: The frame index registers were stored into. 2716 int 2717 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, 2718 SDLoc dl, SDValue &Chain, 2719 const Value *OrigArg, 2720 unsigned InRegsParamRecordIdx, 2721 unsigned OffsetFromOrigArg, 2722 unsigned ArgOffset, 2723 unsigned ArgSize, 2724 bool ForceMutable, 2725 unsigned ByValStoreOffset, 2726 unsigned TotalArgRegsSaveSize) const { 2727 2728 // Currently, two use-cases possible: 2729 // Case #1. Non-var-args function, and we meet first byval parameter. 2730 // Setup first unallocated register as first byval register; 2731 // eat all remained registers 2732 // (these two actions are performed by HandleByVal method). 2733 // Then, here, we initialize stack frame with 2734 // "store-reg" instructions. 2735 // Case #2. Var-args function, that doesn't contain byval parameters. 2736 // The same: eat all remained unallocated registers, 2737 // initialize stack frame. 2738 2739 MachineFunction &MF = DAG.getMachineFunction(); 2740 MachineFrameInfo *MFI = MF.getFrameInfo(); 2741 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2742 unsigned firstRegToSaveIndex, lastRegToSaveIndex; 2743 unsigned RBegin, REnd; 2744 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) { 2745 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd); 2746 firstRegToSaveIndex = RBegin - ARM::R0; 2747 lastRegToSaveIndex = REnd - ARM::R0; 2748 } else { 2749 firstRegToSaveIndex = CCInfo.getFirstUnallocated 2750 (GPRArgRegs, array_lengthof(GPRArgRegs)); 2751 lastRegToSaveIndex = 4; 2752 } 2753 2754 unsigned ArgRegsSize, ArgRegsSaveSize; 2755 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize, 2756 ArgRegsSize, ArgRegsSaveSize); 2757 2758 // Store any by-val regs to their spots on the stack so that they may be 2759 // loaded by deferencing the result of formal parameter pointer or va_next. 2760 // Note: once stack area for byval/varargs registers 2761 // was initialized, it can't be initialized again. 2762 if (ArgRegsSaveSize) { 2763 unsigned Padding = ArgRegsSaveSize - ArgRegsSize; 2764 2765 if (Padding) { 2766 assert(AFI->getStoredByValParamsPadding() == 0 && 2767 "The only parameter may be padded."); 2768 AFI->setStoredByValParamsPadding(Padding); 2769 } 2770 2771 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize, 2772 Padding + 2773 ByValStoreOffset - 2774 (int64_t)TotalArgRegsSaveSize, 2775 false); 2776 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy()); 2777 if (Padding) { 2778 MFI->CreateFixedObject(Padding, 2779 ArgOffset + ByValStoreOffset - 2780 (int64_t)ArgRegsSaveSize, 2781 false); 2782 } 2783 2784 SmallVector<SDValue, 4> MemOps; 2785 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex; 2786 ++firstRegToSaveIndex, ++i) { 2787 const TargetRegisterClass *RC; 2788 if (AFI->isThumb1OnlyFunction()) 2789 RC = &ARM::tGPRRegClass; 2790 else 2791 RC = &ARM::GPRRegClass; 2792 2793 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC); 2794 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 2795 SDValue Store = 2796 DAG.getStore(Val.getValue(1), dl, Val, FIN, 2797 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i), 2798 false, false, 0); 2799 MemOps.push_back(Store); 2800 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN, 2801 DAG.getConstant(4, getPointerTy())); 2802 } 2803 2804 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize()); 2805 2806 if (!MemOps.empty()) 2807 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2808 &MemOps[0], MemOps.size()); 2809 return FrameIndex; 2810 } else { 2811 if (ArgSize == 0) { 2812 // We cannot allocate a zero-byte object for the first variadic argument, 2813 // so just make up a size. 2814 ArgSize = 4; 2815 } 2816 // This will point to the next argument passed via stack. 2817 return MFI->CreateFixedObject( 2818 ArgSize, ArgOffset, !ForceMutable); 2819 } 2820 } 2821 2822 // Setup stack frame, the va_list pointer will start from. 2823 void 2824 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG, 2825 SDLoc dl, SDValue &Chain, 2826 unsigned ArgOffset, 2827 unsigned TotalArgRegsSaveSize, 2828 bool ForceMutable) const { 2829 MachineFunction &MF = DAG.getMachineFunction(); 2830 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2831 2832 // Try to store any remaining integer argument regs 2833 // to their spots on the stack so that they may be loaded by deferencing 2834 // the result of va_next. 2835 // If there is no regs to be stored, just point address after last 2836 // argument passed via stack. 2837 int FrameIndex = 2838 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(), 2839 0, ArgOffset, 0, ForceMutable, 0, TotalArgRegsSaveSize); 2840 2841 AFI->setVarArgsFrameIndex(FrameIndex); 2842 } 2843 2844 SDValue 2845 ARMTargetLowering::LowerFormalArguments(SDValue Chain, 2846 CallingConv::ID CallConv, bool isVarArg, 2847 const SmallVectorImpl<ISD::InputArg> 2848 &Ins, 2849 SDLoc dl, SelectionDAG &DAG, 2850 SmallVectorImpl<SDValue> &InVals) 2851 const { 2852 MachineFunction &MF = DAG.getMachineFunction(); 2853 MachineFrameInfo *MFI = MF.getFrameInfo(); 2854 2855 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2856 2857 // Assign locations to all of the incoming arguments. 2858 SmallVector<CCValAssign, 16> ArgLocs; 2859 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 2860 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue); 2861 CCInfo.AnalyzeFormalArguments(Ins, 2862 CCAssignFnForNode(CallConv, /* Return*/ false, 2863 isVarArg)); 2864 2865 SmallVector<SDValue, 16> ArgValues; 2866 int lastInsIndex = -1; 2867 SDValue ArgValue; 2868 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 2869 unsigned CurArgIdx = 0; 2870 2871 // Initially ArgRegsSaveSize is zero. 2872 // Then we increase this value each time we meet byval parameter. 2873 // We also increase this value in case of varargs function. 2874 AFI->setArgRegsSaveSize(0); 2875 2876 unsigned ByValStoreOffset = 0; 2877 unsigned TotalArgRegsSaveSize = 0; 2878 unsigned ArgRegsSaveSizeMaxAlign = 4; 2879 2880 // Calculate the amount of stack space that we need to allocate to store 2881 // byval and variadic arguments that are passed in registers. 2882 // We need to know this before we allocate the first byval or variadic 2883 // argument, as they will be allocated a stack slot below the CFA (Canonical 2884 // Frame Address, the stack pointer at entry to the function). 2885 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2886 CCValAssign &VA = ArgLocs[i]; 2887 if (VA.isMemLoc()) { 2888 int index = VA.getValNo(); 2889 if (index != lastInsIndex) { 2890 ISD::ArgFlagsTy Flags = Ins[index].Flags; 2891 if (Flags.isByVal()) { 2892 unsigned ExtraArgRegsSize; 2893 unsigned ExtraArgRegsSaveSize; 2894 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(), 2895 Flags.getByValSize(), 2896 ExtraArgRegsSize, ExtraArgRegsSaveSize); 2897 2898 TotalArgRegsSaveSize += ExtraArgRegsSaveSize; 2899 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign) 2900 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign(); 2901 CCInfo.nextInRegsParam(); 2902 } 2903 lastInsIndex = index; 2904 } 2905 } 2906 } 2907 CCInfo.rewindByValRegsInfo(); 2908 lastInsIndex = -1; 2909 if (isVarArg) { 2910 unsigned ExtraArgRegsSize; 2911 unsigned ExtraArgRegsSaveSize; 2912 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0, 2913 ExtraArgRegsSize, ExtraArgRegsSaveSize); 2914 TotalArgRegsSaveSize += ExtraArgRegsSaveSize; 2915 } 2916 // If the arg regs save area contains N-byte aligned values, the 2917 // bottom of it must be at least N-byte aligned. 2918 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign); 2919 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U); 2920 2921 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2922 CCValAssign &VA = ArgLocs[i]; 2923 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx); 2924 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex; 2925 // Arguments stored in registers. 2926 if (VA.isRegLoc()) { 2927 EVT RegVT = VA.getLocVT(); 2928 2929 if (VA.needsCustom()) { 2930 // f64 and vector types are split up into multiple registers or 2931 // combinations of registers and stack slots. 2932 if (VA.getLocVT() == MVT::v2f64) { 2933 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i], 2934 Chain, DAG, dl); 2935 VA = ArgLocs[++i]; // skip ahead to next loc 2936 SDValue ArgValue2; 2937 if (VA.isMemLoc()) { 2938 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true); 2939 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 2940 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN, 2941 MachinePointerInfo::getFixedStack(FI), 2942 false, false, false, 0); 2943 } else { 2944 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], 2945 Chain, DAG, dl); 2946 } 2947 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64); 2948 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 2949 ArgValue, ArgValue1, DAG.getIntPtrConstant(0)); 2950 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, 2951 ArgValue, ArgValue2, DAG.getIntPtrConstant(1)); 2952 } else 2953 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl); 2954 2955 } else { 2956 const TargetRegisterClass *RC; 2957 2958 if (RegVT == MVT::f32) 2959 RC = &ARM::SPRRegClass; 2960 else if (RegVT == MVT::f64) 2961 RC = &ARM::DPRRegClass; 2962 else if (RegVT == MVT::v2f64) 2963 RC = &ARM::QPRRegClass; 2964 else if (RegVT == MVT::i32) 2965 RC = AFI->isThumb1OnlyFunction() ? 2966 (const TargetRegisterClass*)&ARM::tGPRRegClass : 2967 (const TargetRegisterClass*)&ARM::GPRRegClass; 2968 else 2969 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 2970 2971 // Transform the arguments in physical registers into virtual ones. 2972 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2973 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 2974 } 2975 2976 // If this is an 8 or 16-bit value, it is really passed promoted 2977 // to 32 bits. Insert an assert[sz]ext to capture this, then 2978 // truncate to the right size. 2979 switch (VA.getLocInfo()) { 2980 default: llvm_unreachable("Unknown loc info!"); 2981 case CCValAssign::Full: break; 2982 case CCValAssign::BCvt: 2983 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 2984 break; 2985 case CCValAssign::SExt: 2986 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 2987 DAG.getValueType(VA.getValVT())); 2988 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 2989 break; 2990 case CCValAssign::ZExt: 2991 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 2992 DAG.getValueType(VA.getValVT())); 2993 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 2994 break; 2995 } 2996 2997 InVals.push_back(ArgValue); 2998 2999 } else { // VA.isRegLoc() 3000 3001 // sanity check 3002 assert(VA.isMemLoc()); 3003 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered"); 3004 3005 int index = ArgLocs[i].getValNo(); 3006 3007 // Some Ins[] entries become multiple ArgLoc[] entries. 3008 // Process them only once. 3009 if (index != lastInsIndex) 3010 { 3011 ISD::ArgFlagsTy Flags = Ins[index].Flags; 3012 // FIXME: For now, all byval parameter objects are marked mutable. 3013 // This can be changed with more analysis. 3014 // In case of tail call optimization mark all arguments mutable. 3015 // Since they could be overwritten by lowering of arguments in case of 3016 // a tail call. 3017 if (Flags.isByVal()) { 3018 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed(); 3019 3020 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign()); 3021 int FrameIndex = StoreByValRegs( 3022 CCInfo, DAG, dl, Chain, CurOrigArg, 3023 CurByValIndex, 3024 Ins[VA.getValNo()].PartOffset, 3025 VA.getLocMemOffset(), 3026 Flags.getByValSize(), 3027 true /*force mutable frames*/, 3028 ByValStoreOffset, 3029 TotalArgRegsSaveSize); 3030 ByValStoreOffset += Flags.getByValSize(); 3031 ByValStoreOffset = std::min(ByValStoreOffset, 16U); 3032 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy())); 3033 CCInfo.nextInRegsParam(); 3034 } else { 3035 unsigned FIOffset = VA.getLocMemOffset(); 3036 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8, 3037 FIOffset, true); 3038 3039 // Create load nodes to retrieve arguments from the stack. 3040 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 3041 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, 3042 MachinePointerInfo::getFixedStack(FI), 3043 false, false, false, 0)); 3044 } 3045 lastInsIndex = index; 3046 } 3047 } 3048 } 3049 3050 // varargs 3051 if (isVarArg) 3052 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 3053 CCInfo.getNextStackOffset(), 3054 TotalArgRegsSaveSize); 3055 3056 AFI->setArgumentStackSize(CCInfo.getNextStackOffset()); 3057 3058 return Chain; 3059 } 3060 3061 /// isFloatingPointZero - Return true if this is +0.0. 3062 static bool isFloatingPointZero(SDValue Op) { 3063 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 3064 return CFP->getValueAPF().isPosZero(); 3065 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 3066 // Maybe this has already been legalized into the constant pool? 3067 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) { 3068 SDValue WrapperOp = Op.getOperand(1).getOperand(0); 3069 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp)) 3070 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 3071 return CFP->getValueAPF().isPosZero(); 3072 } 3073 } 3074 return false; 3075 } 3076 3077 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for 3078 /// the given operands. 3079 SDValue 3080 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3081 SDValue &ARMcc, SelectionDAG &DAG, 3082 SDLoc dl) const { 3083 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 3084 unsigned C = RHSC->getZExtValue(); 3085 if (!isLegalICmpImmediate(C)) { 3086 // Constant does not fit, try adjusting it by one? 3087 switch (CC) { 3088 default: break; 3089 case ISD::SETLT: 3090 case ISD::SETGE: 3091 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) { 3092 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 3093 RHS = DAG.getConstant(C-1, MVT::i32); 3094 } 3095 break; 3096 case ISD::SETULT: 3097 case ISD::SETUGE: 3098 if (C != 0 && isLegalICmpImmediate(C-1)) { 3099 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 3100 RHS = DAG.getConstant(C-1, MVT::i32); 3101 } 3102 break; 3103 case ISD::SETLE: 3104 case ISD::SETGT: 3105 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) { 3106 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 3107 RHS = DAG.getConstant(C+1, MVT::i32); 3108 } 3109 break; 3110 case ISD::SETULE: 3111 case ISD::SETUGT: 3112 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) { 3113 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 3114 RHS = DAG.getConstant(C+1, MVT::i32); 3115 } 3116 break; 3117 } 3118 } 3119 } 3120 3121 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3122 ARMISD::NodeType CompareType; 3123 switch (CondCode) { 3124 default: 3125 CompareType = ARMISD::CMP; 3126 break; 3127 case ARMCC::EQ: 3128 case ARMCC::NE: 3129 // Uses only Z Flag 3130 CompareType = ARMISD::CMPZ; 3131 break; 3132 } 3133 ARMcc = DAG.getConstant(CondCode, MVT::i32); 3134 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS); 3135 } 3136 3137 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands. 3138 SDValue 3139 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG, 3140 SDLoc dl) const { 3141 SDValue Cmp; 3142 if (!isFloatingPointZero(RHS)) 3143 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS); 3144 else 3145 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS); 3146 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp); 3147 } 3148 3149 /// duplicateCmp - Glue values can have only one use, so this function 3150 /// duplicates a comparison node. 3151 SDValue 3152 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const { 3153 unsigned Opc = Cmp.getOpcode(); 3154 SDLoc DL(Cmp); 3155 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ) 3156 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3157 3158 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation"); 3159 Cmp = Cmp.getOperand(0); 3160 Opc = Cmp.getOpcode(); 3161 if (Opc == ARMISD::CMPFP) 3162 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1)); 3163 else { 3164 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT"); 3165 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0)); 3166 } 3167 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp); 3168 } 3169 3170 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3171 SDValue Cond = Op.getOperand(0); 3172 SDValue SelectTrue = Op.getOperand(1); 3173 SDValue SelectFalse = Op.getOperand(2); 3174 SDLoc dl(Op); 3175 3176 // Convert: 3177 // 3178 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond) 3179 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond) 3180 // 3181 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) { 3182 const ConstantSDNode *CMOVTrue = 3183 dyn_cast<ConstantSDNode>(Cond.getOperand(0)); 3184 const ConstantSDNode *CMOVFalse = 3185 dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 3186 3187 if (CMOVTrue && CMOVFalse) { 3188 unsigned CMOVTrueVal = CMOVTrue->getZExtValue(); 3189 unsigned CMOVFalseVal = CMOVFalse->getZExtValue(); 3190 3191 SDValue True; 3192 SDValue False; 3193 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) { 3194 True = SelectTrue; 3195 False = SelectFalse; 3196 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) { 3197 True = SelectFalse; 3198 False = SelectTrue; 3199 } 3200 3201 if (True.getNode() && False.getNode()) { 3202 EVT VT = Op.getValueType(); 3203 SDValue ARMcc = Cond.getOperand(2); 3204 SDValue CCR = Cond.getOperand(3); 3205 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG); 3206 assert(True.getValueType() == VT); 3207 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp); 3208 } 3209 } 3210 } 3211 3212 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the 3213 // undefined bits before doing a full-word comparison with zero. 3214 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond, 3215 DAG.getConstant(1, Cond.getValueType())); 3216 3217 return DAG.getSelectCC(dl, Cond, 3218 DAG.getConstant(0, Cond.getValueType()), 3219 SelectTrue, SelectFalse, ISD::SETNE); 3220 } 3221 3222 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) { 3223 if (CC == ISD::SETNE) 3224 return ISD::SETEQ; 3225 return ISD::getSetCCInverse(CC, true); 3226 } 3227 3228 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode, 3229 bool &swpCmpOps, bool &swpVselOps) { 3230 // Start by selecting the GE condition code for opcodes that return true for 3231 // 'equality' 3232 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE || 3233 CC == ISD::SETULE) 3234 CondCode = ARMCC::GE; 3235 3236 // and GT for opcodes that return false for 'equality'. 3237 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT || 3238 CC == ISD::SETULT) 3239 CondCode = ARMCC::GT; 3240 3241 // Since we are constrained to GE/GT, if the opcode contains 'less', we need 3242 // to swap the compare operands. 3243 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT || 3244 CC == ISD::SETULT) 3245 swpCmpOps = true; 3246 3247 // Both GT and GE are ordered comparisons, and return false for 'unordered'. 3248 // If we have an unordered opcode, we need to swap the operands to the VSEL 3249 // instruction (effectively negating the condition). 3250 // 3251 // This also has the effect of swapping which one of 'less' or 'greater' 3252 // returns true, so we also swap the compare operands. It also switches 3253 // whether we return true for 'equality', so we compensate by picking the 3254 // opposite condition code to our original choice. 3255 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE || 3256 CC == ISD::SETUGT) { 3257 swpCmpOps = !swpCmpOps; 3258 swpVselOps = !swpVselOps; 3259 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT; 3260 } 3261 3262 // 'ordered' is 'anything but unordered', so use the VS condition code and 3263 // swap the VSEL operands. 3264 if (CC == ISD::SETO) { 3265 CondCode = ARMCC::VS; 3266 swpVselOps = true; 3267 } 3268 3269 // 'unordered or not equal' is 'anything but equal', so use the EQ condition 3270 // code and swap the VSEL operands. 3271 if (CC == ISD::SETUNE) { 3272 CondCode = ARMCC::EQ; 3273 swpVselOps = true; 3274 } 3275 } 3276 3277 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 3278 EVT VT = Op.getValueType(); 3279 SDValue LHS = Op.getOperand(0); 3280 SDValue RHS = Op.getOperand(1); 3281 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 3282 SDValue TrueVal = Op.getOperand(2); 3283 SDValue FalseVal = Op.getOperand(3); 3284 SDLoc dl(Op); 3285 3286 if (LHS.getValueType() == MVT::i32) { 3287 // Try to generate VSEL on ARMv8. 3288 // The VSEL instruction can't use all the usual ARM condition 3289 // codes: it only has two bits to select the condition code, so it's 3290 // constrained to use only GE, GT, VS and EQ. 3291 // 3292 // To implement all the various ISD::SETXXX opcodes, we sometimes need to 3293 // swap the operands of the previous compare instruction (effectively 3294 // inverting the compare condition, swapping 'less' and 'greater') and 3295 // sometimes need to swap the operands to the VSEL (which inverts the 3296 // condition in the sense of firing whenever the previous condition didn't) 3297 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3298 TrueVal.getValueType() == MVT::f64)) { 3299 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3300 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE || 3301 CondCode == ARMCC::VC || CondCode == ARMCC::NE) { 3302 CC = getInverseCCForVSEL(CC); 3303 std::swap(TrueVal, FalseVal); 3304 } 3305 } 3306 3307 SDValue ARMcc; 3308 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3309 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3310 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR, 3311 Cmp); 3312 } 3313 3314 ARMCC::CondCodes CondCode, CondCode2; 3315 FPCCToARMCC(CC, CondCode, CondCode2); 3316 3317 // Try to generate VSEL on ARMv8. 3318 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 || 3319 TrueVal.getValueType() == MVT::f64)) { 3320 // We can select VMAXNM/VMINNM from a compare followed by a select with the 3321 // same operands, as follows: 3322 // c = fcmp [ogt, olt, ugt, ult] a, b 3323 // select c, a, b 3324 // We only do this in unsafe-fp-math, because signed zeros and NaNs are 3325 // handled differently than the original code sequence. 3326 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal && 3327 RHS == FalseVal) { 3328 if (CC == ISD::SETOGT || CC == ISD::SETUGT) 3329 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal); 3330 if (CC == ISD::SETOLT || CC == ISD::SETULT) 3331 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal); 3332 } 3333 3334 bool swpCmpOps = false; 3335 bool swpVselOps = false; 3336 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps); 3337 3338 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE || 3339 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) { 3340 if (swpCmpOps) 3341 std::swap(LHS, RHS); 3342 if (swpVselOps) 3343 std::swap(TrueVal, FalseVal); 3344 } 3345 } 3346 3347 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32); 3348 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3349 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3350 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, 3351 ARMcc, CCR, Cmp); 3352 if (CondCode2 != ARMCC::AL) { 3353 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32); 3354 // FIXME: Needs another CMP because flag can have but one use. 3355 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl); 3356 Result = DAG.getNode(ARMISD::CMOV, dl, VT, 3357 Result, TrueVal, ARMcc2, CCR, Cmp2); 3358 } 3359 return Result; 3360 } 3361 3362 /// canChangeToInt - Given the fp compare operand, return true if it is suitable 3363 /// to morph to an integer compare sequence. 3364 static bool canChangeToInt(SDValue Op, bool &SeenZero, 3365 const ARMSubtarget *Subtarget) { 3366 SDNode *N = Op.getNode(); 3367 if (!N->hasOneUse()) 3368 // Otherwise it requires moving the value from fp to integer registers. 3369 return false; 3370 if (!N->getNumValues()) 3371 return false; 3372 EVT VT = Op.getValueType(); 3373 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow()) 3374 // f32 case is generally profitable. f64 case only makes sense when vcmpe + 3375 // vmrs are very slow, e.g. cortex-a8. 3376 return false; 3377 3378 if (isFloatingPointZero(Op)) { 3379 SeenZero = true; 3380 return true; 3381 } 3382 return ISD::isNormalLoad(N); 3383 } 3384 3385 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) { 3386 if (isFloatingPointZero(Op)) 3387 return DAG.getConstant(0, MVT::i32); 3388 3389 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) 3390 return DAG.getLoad(MVT::i32, SDLoc(Op), 3391 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(), 3392 Ld->isVolatile(), Ld->isNonTemporal(), 3393 Ld->isInvariant(), Ld->getAlignment()); 3394 3395 llvm_unreachable("Unknown VFP cmp argument!"); 3396 } 3397 3398 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG, 3399 SDValue &RetVal1, SDValue &RetVal2) { 3400 if (isFloatingPointZero(Op)) { 3401 RetVal1 = DAG.getConstant(0, MVT::i32); 3402 RetVal2 = DAG.getConstant(0, MVT::i32); 3403 return; 3404 } 3405 3406 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) { 3407 SDValue Ptr = Ld->getBasePtr(); 3408 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op), 3409 Ld->getChain(), Ptr, 3410 Ld->getPointerInfo(), 3411 Ld->isVolatile(), Ld->isNonTemporal(), 3412 Ld->isInvariant(), Ld->getAlignment()); 3413 3414 EVT PtrType = Ptr.getValueType(); 3415 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4); 3416 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op), 3417 PtrType, Ptr, DAG.getConstant(4, PtrType)); 3418 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op), 3419 Ld->getChain(), NewPtr, 3420 Ld->getPointerInfo().getWithOffset(4), 3421 Ld->isVolatile(), Ld->isNonTemporal(), 3422 Ld->isInvariant(), NewAlign); 3423 return; 3424 } 3425 3426 llvm_unreachable("Unknown VFP cmp argument!"); 3427 } 3428 3429 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some 3430 /// f32 and even f64 comparisons to integer ones. 3431 SDValue 3432 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const { 3433 SDValue Chain = Op.getOperand(0); 3434 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3435 SDValue LHS = Op.getOperand(2); 3436 SDValue RHS = Op.getOperand(3); 3437 SDValue Dest = Op.getOperand(4); 3438 SDLoc dl(Op); 3439 3440 bool LHSSeenZero = false; 3441 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget); 3442 bool RHSSeenZero = false; 3443 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget); 3444 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) { 3445 // If unsafe fp math optimization is enabled and there are no other uses of 3446 // the CMP operands, and the condition code is EQ or NE, we can optimize it 3447 // to an integer comparison. 3448 if (CC == ISD::SETOEQ) 3449 CC = ISD::SETEQ; 3450 else if (CC == ISD::SETUNE) 3451 CC = ISD::SETNE; 3452 3453 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32); 3454 SDValue ARMcc; 3455 if (LHS.getValueType() == MVT::f32) { 3456 LHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3457 bitcastf32Toi32(LHS, DAG), Mask); 3458 RHS = DAG.getNode(ISD::AND, dl, MVT::i32, 3459 bitcastf32Toi32(RHS, DAG), Mask); 3460 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3461 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3462 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3463 Chain, Dest, ARMcc, CCR, Cmp); 3464 } 3465 3466 SDValue LHS1, LHS2; 3467 SDValue RHS1, RHS2; 3468 expandf64Toi32(LHS, DAG, LHS1, LHS2); 3469 expandf64Toi32(RHS, DAG, RHS1, RHS2); 3470 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask); 3471 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask); 3472 ARMCC::CondCodes CondCode = IntCCToARMCC(CC); 3473 ARMcc = DAG.getConstant(CondCode, MVT::i32); 3474 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3475 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest }; 3476 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7); 3477 } 3478 3479 return SDValue(); 3480 } 3481 3482 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3483 SDValue Chain = Op.getOperand(0); 3484 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3485 SDValue LHS = Op.getOperand(2); 3486 SDValue RHS = Op.getOperand(3); 3487 SDValue Dest = Op.getOperand(4); 3488 SDLoc dl(Op); 3489 3490 if (LHS.getValueType() == MVT::i32) { 3491 SDValue ARMcc; 3492 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl); 3493 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3494 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, 3495 Chain, Dest, ARMcc, CCR, Cmp); 3496 } 3497 3498 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3499 3500 if (getTargetMachine().Options.UnsafeFPMath && 3501 (CC == ISD::SETEQ || CC == ISD::SETOEQ || 3502 CC == ISD::SETNE || CC == ISD::SETUNE)) { 3503 SDValue Result = OptimizeVFPBrcond(Op, DAG); 3504 if (Result.getNode()) 3505 return Result; 3506 } 3507 3508 ARMCC::CondCodes CondCode, CondCode2; 3509 FPCCToARMCC(CC, CondCode, CondCode2); 3510 3511 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32); 3512 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl); 3513 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3514 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue); 3515 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp }; 3516 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5); 3517 if (CondCode2 != ARMCC::AL) { 3518 ARMcc = DAG.getConstant(CondCode2, MVT::i32); 3519 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) }; 3520 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5); 3521 } 3522 return Res; 3523 } 3524 3525 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { 3526 SDValue Chain = Op.getOperand(0); 3527 SDValue Table = Op.getOperand(1); 3528 SDValue Index = Op.getOperand(2); 3529 SDLoc dl(Op); 3530 3531 EVT PTy = getPointerTy(); 3532 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table); 3533 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>(); 3534 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy); 3535 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy); 3536 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId); 3537 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy)); 3538 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table); 3539 if (Subtarget->isThumb2()) { 3540 // Thumb2 uses a two-level jump. That is, it jumps into the jump table 3541 // which does another jump to the destination. This also makes it easier 3542 // to translate it to TBB / TBH later. 3543 // FIXME: This might not work if the function is extremely large. 3544 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain, 3545 Addr, Op.getOperand(2), JTI, UId); 3546 } 3547 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) { 3548 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, 3549 MachinePointerInfo::getJumpTable(), 3550 false, false, false, 0); 3551 Chain = Addr.getValue(1); 3552 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table); 3553 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId); 3554 } else { 3555 Addr = DAG.getLoad(PTy, dl, Chain, Addr, 3556 MachinePointerInfo::getJumpTable(), 3557 false, false, false, 0); 3558 Chain = Addr.getValue(1); 3559 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId); 3560 } 3561 } 3562 3563 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 3564 EVT VT = Op.getValueType(); 3565 SDLoc dl(Op); 3566 3567 if (Op.getValueType().getVectorElementType() == MVT::i32) { 3568 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32) 3569 return Op; 3570 return DAG.UnrollVectorOp(Op.getNode()); 3571 } 3572 3573 assert(Op.getOperand(0).getValueType() == MVT::v4f32 && 3574 "Invalid type for custom lowering!"); 3575 if (VT != MVT::v4i16) 3576 return DAG.UnrollVectorOp(Op.getNode()); 3577 3578 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0)); 3579 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op); 3580 } 3581 3582 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 3583 EVT VT = Op.getValueType(); 3584 if (VT.isVector()) 3585 return LowerVectorFP_TO_INT(Op, DAG); 3586 3587 SDLoc dl(Op); 3588 unsigned Opc; 3589 3590 switch (Op.getOpcode()) { 3591 default: llvm_unreachable("Invalid opcode!"); 3592 case ISD::FP_TO_SINT: 3593 Opc = ARMISD::FTOSI; 3594 break; 3595 case ISD::FP_TO_UINT: 3596 Opc = ARMISD::FTOUI; 3597 break; 3598 } 3599 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0)); 3600 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3601 } 3602 3603 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 3604 EVT VT = Op.getValueType(); 3605 SDLoc dl(Op); 3606 3607 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) { 3608 if (VT.getVectorElementType() == MVT::f32) 3609 return Op; 3610 return DAG.UnrollVectorOp(Op.getNode()); 3611 } 3612 3613 assert(Op.getOperand(0).getValueType() == MVT::v4i16 && 3614 "Invalid type for custom lowering!"); 3615 if (VT != MVT::v4f32) 3616 return DAG.UnrollVectorOp(Op.getNode()); 3617 3618 unsigned CastOpc; 3619 unsigned Opc; 3620 switch (Op.getOpcode()) { 3621 default: llvm_unreachable("Invalid opcode!"); 3622 case ISD::SINT_TO_FP: 3623 CastOpc = ISD::SIGN_EXTEND; 3624 Opc = ISD::SINT_TO_FP; 3625 break; 3626 case ISD::UINT_TO_FP: 3627 CastOpc = ISD::ZERO_EXTEND; 3628 Opc = ISD::UINT_TO_FP; 3629 break; 3630 } 3631 3632 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0)); 3633 return DAG.getNode(Opc, dl, VT, Op); 3634 } 3635 3636 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 3637 EVT VT = Op.getValueType(); 3638 if (VT.isVector()) 3639 return LowerVectorINT_TO_FP(Op, DAG); 3640 3641 SDLoc dl(Op); 3642 unsigned Opc; 3643 3644 switch (Op.getOpcode()) { 3645 default: llvm_unreachable("Invalid opcode!"); 3646 case ISD::SINT_TO_FP: 3647 Opc = ARMISD::SITOF; 3648 break; 3649 case ISD::UINT_TO_FP: 3650 Opc = ARMISD::UITOF; 3651 break; 3652 } 3653 3654 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0)); 3655 return DAG.getNode(Opc, dl, VT, Op); 3656 } 3657 3658 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 3659 // Implement fcopysign with a fabs and a conditional fneg. 3660 SDValue Tmp0 = Op.getOperand(0); 3661 SDValue Tmp1 = Op.getOperand(1); 3662 SDLoc dl(Op); 3663 EVT VT = Op.getValueType(); 3664 EVT SrcVT = Tmp1.getValueType(); 3665 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST || 3666 Tmp0.getOpcode() == ARMISD::VMOVDRR; 3667 bool UseNEON = !InGPR && Subtarget->hasNEON(); 3668 3669 if (UseNEON) { 3670 // Use VBSL to copy the sign bit. 3671 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80); 3672 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32, 3673 DAG.getTargetConstant(EncodedVal, MVT::i32)); 3674 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64; 3675 if (VT == MVT::f64) 3676 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT, 3677 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask), 3678 DAG.getConstant(32, MVT::i32)); 3679 else /*if (VT == MVT::f32)*/ 3680 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0); 3681 if (SrcVT == MVT::f32) { 3682 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1); 3683 if (VT == MVT::f64) 3684 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT, 3685 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1), 3686 DAG.getConstant(32, MVT::i32)); 3687 } else if (VT == MVT::f32) 3688 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64, 3689 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1), 3690 DAG.getConstant(32, MVT::i32)); 3691 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0); 3692 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1); 3693 3694 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff), 3695 MVT::i32); 3696 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes); 3697 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask, 3698 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes)); 3699 3700 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT, 3701 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask), 3702 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot)); 3703 if (VT == MVT::f32) { 3704 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res); 3705 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res, 3706 DAG.getConstant(0, MVT::i32)); 3707 } else { 3708 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res); 3709 } 3710 3711 return Res; 3712 } 3713 3714 // Bitcast operand 1 to i32. 3715 if (SrcVT == MVT::f64) 3716 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 3717 &Tmp1, 1).getValue(1); 3718 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1); 3719 3720 // Or in the signbit with integer operations. 3721 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32); 3722 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32); 3723 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1); 3724 if (VT == MVT::f32) { 3725 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32, 3726 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2); 3727 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 3728 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1)); 3729 } 3730 3731 // f64: Or the high part with signbit and then combine two parts. 3732 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32), 3733 &Tmp0, 1); 3734 SDValue Lo = Tmp0.getValue(0); 3735 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2); 3736 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1); 3737 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi); 3738 } 3739 3740 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{ 3741 MachineFunction &MF = DAG.getMachineFunction(); 3742 MachineFrameInfo *MFI = MF.getFrameInfo(); 3743 MFI->setReturnAddressIsTaken(true); 3744 3745 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3746 return SDValue(); 3747 3748 EVT VT = Op.getValueType(); 3749 SDLoc dl(Op); 3750 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3751 if (Depth) { 3752 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 3753 SDValue Offset = DAG.getConstant(4, MVT::i32); 3754 return DAG.getLoad(VT, dl, DAG.getEntryNode(), 3755 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset), 3756 MachinePointerInfo(), false, false, false, 0); 3757 } 3758 3759 // Return LR, which contains the return address. Mark it an implicit live-in. 3760 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32)); 3761 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT); 3762 } 3763 3764 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 3765 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 3766 MFI->setFrameAddressIsTaken(true); 3767 3768 EVT VT = Op.getValueType(); 3769 SDLoc dl(Op); // FIXME probably not meaningful 3770 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3771 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO()) 3772 ? ARM::R7 : ARM::R11; 3773 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 3774 while (Depth--) 3775 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 3776 MachinePointerInfo(), 3777 false, false, false, 0); 3778 return FrameAddr; 3779 } 3780 3781 /// ExpandBITCAST - If the target supports VFP, this function is called to 3782 /// expand a bit convert where either the source or destination type is i64 to 3783 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64 3784 /// operand type is illegal (e.g., v2f32 for a target that doesn't support 3785 /// vectors), since the legalizer won't know what to do with that. 3786 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) { 3787 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3788 SDLoc dl(N); 3789 SDValue Op = N->getOperand(0); 3790 3791 // This function is only supposed to be called for i64 types, either as the 3792 // source or destination of the bit convert. 3793 EVT SrcVT = Op.getValueType(); 3794 EVT DstVT = N->getValueType(0); 3795 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) && 3796 "ExpandBITCAST called for non-i64 type"); 3797 3798 // Turn i64->f64 into VMOVDRR. 3799 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) { 3800 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 3801 DAG.getConstant(0, MVT::i32)); 3802 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op, 3803 DAG.getConstant(1, MVT::i32)); 3804 return DAG.getNode(ISD::BITCAST, dl, DstVT, 3805 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi)); 3806 } 3807 3808 // Turn f64->i64 into VMOVRRD. 3809 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) { 3810 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl, 3811 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1); 3812 // Merge the pieces into a single i64 value. 3813 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1)); 3814 } 3815 3816 return SDValue(); 3817 } 3818 3819 /// getZeroVector - Returns a vector of specified type with all zero elements. 3820 /// Zero vectors are used to represent vector negation and in those cases 3821 /// will be implemented with the NEON VNEG instruction. However, VNEG does 3822 /// not support i64 elements, so sometimes the zero vectors will need to be 3823 /// explicitly constructed. Regardless, use a canonical VMOV to create the 3824 /// zero vector. 3825 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) { 3826 assert(VT.isVector() && "Expected a vector type"); 3827 // The canonical modified immediate encoding of a zero vector is....0! 3828 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32); 3829 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 3830 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal); 3831 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 3832 } 3833 3834 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 3835 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 3836 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, 3837 SelectionDAG &DAG) const { 3838 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 3839 EVT VT = Op.getValueType(); 3840 unsigned VTBits = VT.getSizeInBits(); 3841 SDLoc dl(Op); 3842 SDValue ShOpLo = Op.getOperand(0); 3843 SDValue ShOpHi = Op.getOperand(1); 3844 SDValue ShAmt = Op.getOperand(2); 3845 SDValue ARMcc; 3846 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 3847 3848 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 3849 3850 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 3851 DAG.getConstant(VTBits, MVT::i32), ShAmt); 3852 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 3853 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 3854 DAG.getConstant(VTBits, MVT::i32)); 3855 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 3856 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 3857 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 3858 3859 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3860 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE, 3861 ARMcc, DAG, dl); 3862 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 3863 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, 3864 CCR, Cmp); 3865 3866 SDValue Ops[2] = { Lo, Hi }; 3867 return DAG.getMergeValues(Ops, 2, dl); 3868 } 3869 3870 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 3871 /// i32 values and take a 2 x i32 value to shift plus a shift amount. 3872 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, 3873 SelectionDAG &DAG) const { 3874 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 3875 EVT VT = Op.getValueType(); 3876 unsigned VTBits = VT.getSizeInBits(); 3877 SDLoc dl(Op); 3878 SDValue ShOpLo = Op.getOperand(0); 3879 SDValue ShOpHi = Op.getOperand(1); 3880 SDValue ShAmt = Op.getOperand(2); 3881 SDValue ARMcc; 3882 3883 assert(Op.getOpcode() == ISD::SHL_PARTS); 3884 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, 3885 DAG.getConstant(VTBits, MVT::i32), ShAmt); 3886 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 3887 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt, 3888 DAG.getConstant(VTBits, MVT::i32)); 3889 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 3890 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 3891 3892 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 3893 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32); 3894 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE, 3895 ARMcc, DAG, dl); 3896 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 3897 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc, 3898 CCR, Cmp); 3899 3900 SDValue Ops[2] = { Lo, Hi }; 3901 return DAG.getMergeValues(Ops, 2, dl); 3902 } 3903 3904 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 3905 SelectionDAG &DAG) const { 3906 // The rounding mode is in bits 23:22 of the FPSCR. 3907 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 3908 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 3909 // so that the shift + and get folded into a bitfield extract. 3910 SDLoc dl(Op); 3911 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 3912 DAG.getConstant(Intrinsic::arm_get_fpscr, 3913 MVT::i32)); 3914 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR, 3915 DAG.getConstant(1U << 22, MVT::i32)); 3916 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 3917 DAG.getConstant(22, MVT::i32)); 3918 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 3919 DAG.getConstant(3, MVT::i32)); 3920 } 3921 3922 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG, 3923 const ARMSubtarget *ST) { 3924 EVT VT = N->getValueType(0); 3925 SDLoc dl(N); 3926 3927 if (!ST->hasV6T2Ops()) 3928 return SDValue(); 3929 3930 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0)); 3931 return DAG.getNode(ISD::CTLZ, dl, VT, rbit); 3932 } 3933 3934 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count 3935 /// for each 16-bit element from operand, repeated. The basic idea is to 3936 /// leverage vcnt to get the 8-bit counts, gather and add the results. 3937 /// 3938 /// Trace for v4i16: 3939 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 3940 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element) 3941 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi) 3942 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 3943 /// [b0 b1 b2 b3 b4 b5 b6 b7] 3944 /// +[b1 b0 b3 b2 b5 b4 b7 b6] 3945 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0, 3946 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits) 3947 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) { 3948 EVT VT = N->getValueType(0); 3949 SDLoc DL(N); 3950 3951 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 3952 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0)); 3953 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0); 3954 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1); 3955 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2); 3956 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3); 3957 } 3958 3959 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the 3960 /// bit-count for each 16-bit element from the operand. We need slightly 3961 /// different sequencing for v4i16 and v8i16 to stay within NEON's available 3962 /// 64/128-bit registers. 3963 /// 3964 /// Trace for v4i16: 3965 /// input = [v0 v1 v2 v3 ] (vi 16-bit element) 3966 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi) 3967 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ] 3968 /// v4i16:Extracted = [k0 k1 k2 k3 ] 3969 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) { 3970 EVT VT = N->getValueType(0); 3971 SDLoc DL(N); 3972 3973 SDValue BitCounts = getCTPOP16BitCounts(N, DAG); 3974 if (VT.is64BitVector()) { 3975 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts); 3976 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended, 3977 DAG.getIntPtrConstant(0)); 3978 } else { 3979 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, 3980 BitCounts, DAG.getIntPtrConstant(0)); 3981 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted); 3982 } 3983 } 3984 3985 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the 3986 /// bit-count for each 32-bit element from the operand. The idea here is 3987 /// to split the vector into 16-bit elements, leverage the 16-bit count 3988 /// routine, and then combine the results. 3989 /// 3990 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged): 3991 /// input = [v0 v1 ] (vi: 32-bit elements) 3992 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1]) 3993 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi) 3994 /// vrev: N0 = [k1 k0 k3 k2 ] 3995 /// [k0 k1 k2 k3 ] 3996 /// N1 =+[k1 k0 k3 k2 ] 3997 /// [k0 k2 k1 k3 ] 3998 /// N2 =+[k1 k3 k0 k2 ] 3999 /// [k0 k2 k1 k3 ] 4000 /// Extended =+[k1 k3 k0 k2 ] 4001 /// [k0 k2 ] 4002 /// Extracted=+[k1 k3 ] 4003 /// 4004 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) { 4005 EVT VT = N->getValueType(0); 4006 SDLoc DL(N); 4007 4008 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16; 4009 4010 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0)); 4011 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG); 4012 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16); 4013 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0); 4014 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1); 4015 4016 if (VT.is64BitVector()) { 4017 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2); 4018 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended, 4019 DAG.getIntPtrConstant(0)); 4020 } else { 4021 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2, 4022 DAG.getIntPtrConstant(0)); 4023 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted); 4024 } 4025 } 4026 4027 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG, 4028 const ARMSubtarget *ST) { 4029 EVT VT = N->getValueType(0); 4030 4031 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON."); 4032 assert((VT == MVT::v2i32 || VT == MVT::v4i32 || 4033 VT == MVT::v4i16 || VT == MVT::v8i16) && 4034 "Unexpected type for custom ctpop lowering"); 4035 4036 if (VT.getVectorElementType() == MVT::i32) 4037 return lowerCTPOP32BitElements(N, DAG); 4038 else 4039 return lowerCTPOP16BitElements(N, DAG); 4040 } 4041 4042 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG, 4043 const ARMSubtarget *ST) { 4044 EVT VT = N->getValueType(0); 4045 SDLoc dl(N); 4046 4047 if (!VT.isVector()) 4048 return SDValue(); 4049 4050 // Lower vector shifts on NEON to use VSHL. 4051 assert(ST->hasNEON() && "unexpected vector shift"); 4052 4053 // Left shifts translate directly to the vshiftu intrinsic. 4054 if (N->getOpcode() == ISD::SHL) 4055 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4056 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32), 4057 N->getOperand(0), N->getOperand(1)); 4058 4059 assert((N->getOpcode() == ISD::SRA || 4060 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode"); 4061 4062 // NEON uses the same intrinsics for both left and right shifts. For 4063 // right shifts, the shift amounts are negative, so negate the vector of 4064 // shift amounts. 4065 EVT ShiftVT = N->getOperand(1).getValueType(); 4066 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT, 4067 getZeroVector(ShiftVT, DAG, dl), 4068 N->getOperand(1)); 4069 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ? 4070 Intrinsic::arm_neon_vshifts : 4071 Intrinsic::arm_neon_vshiftu); 4072 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 4073 DAG.getConstant(vshiftInt, MVT::i32), 4074 N->getOperand(0), NegatedCount); 4075 } 4076 4077 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG, 4078 const ARMSubtarget *ST) { 4079 EVT VT = N->getValueType(0); 4080 SDLoc dl(N); 4081 4082 // We can get here for a node like i32 = ISD::SHL i32, i64 4083 if (VT != MVT::i64) 4084 return SDValue(); 4085 4086 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 4087 "Unknown shift to lower!"); 4088 4089 // We only lower SRA, SRL of 1 here, all others use generic lowering. 4090 if (!isa<ConstantSDNode>(N->getOperand(1)) || 4091 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1) 4092 return SDValue(); 4093 4094 // If we are in thumb mode, we don't have RRX. 4095 if (ST->isThumb1Only()) return SDValue(); 4096 4097 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr. 4098 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4099 DAG.getConstant(0, MVT::i32)); 4100 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0), 4101 DAG.getConstant(1, MVT::i32)); 4102 4103 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and 4104 // captures the result into a carry flag. 4105 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG; 4106 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1); 4107 4108 // The low part is an ARMISD::RRX operand, which shifts the carry in. 4109 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1)); 4110 4111 // Merge the pieces into a single i64 value. 4112 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 4113 } 4114 4115 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) { 4116 SDValue TmpOp0, TmpOp1; 4117 bool Invert = false; 4118 bool Swap = false; 4119 unsigned Opc = 0; 4120 4121 SDValue Op0 = Op.getOperand(0); 4122 SDValue Op1 = Op.getOperand(1); 4123 SDValue CC = Op.getOperand(2); 4124 EVT VT = Op.getValueType(); 4125 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 4126 SDLoc dl(Op); 4127 4128 if (Op.getOperand(1).getValueType().isFloatingPoint()) { 4129 switch (SetCCOpcode) { 4130 default: llvm_unreachable("Illegal FP comparison"); 4131 case ISD::SETUNE: 4132 case ISD::SETNE: Invert = true; // Fallthrough 4133 case ISD::SETOEQ: 4134 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4135 case ISD::SETOLT: 4136 case ISD::SETLT: Swap = true; // Fallthrough 4137 case ISD::SETOGT: 4138 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4139 case ISD::SETOLE: 4140 case ISD::SETLE: Swap = true; // Fallthrough 4141 case ISD::SETOGE: 4142 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4143 case ISD::SETUGE: Swap = true; // Fallthrough 4144 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break; 4145 case ISD::SETUGT: Swap = true; // Fallthrough 4146 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break; 4147 case ISD::SETUEQ: Invert = true; // Fallthrough 4148 case ISD::SETONE: 4149 // Expand this to (OLT | OGT). 4150 TmpOp0 = Op0; 4151 TmpOp1 = Op1; 4152 Opc = ISD::OR; 4153 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0); 4154 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1); 4155 break; 4156 case ISD::SETUO: Invert = true; // Fallthrough 4157 case ISD::SETO: 4158 // Expand this to (OLT | OGE). 4159 TmpOp0 = Op0; 4160 TmpOp1 = Op1; 4161 Opc = ISD::OR; 4162 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0); 4163 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1); 4164 break; 4165 } 4166 } else { 4167 // Integer comparisons. 4168 switch (SetCCOpcode) { 4169 default: llvm_unreachable("Illegal integer comparison"); 4170 case ISD::SETNE: Invert = true; 4171 case ISD::SETEQ: Opc = ARMISD::VCEQ; break; 4172 case ISD::SETLT: Swap = true; 4173 case ISD::SETGT: Opc = ARMISD::VCGT; break; 4174 case ISD::SETLE: Swap = true; 4175 case ISD::SETGE: Opc = ARMISD::VCGE; break; 4176 case ISD::SETULT: Swap = true; 4177 case ISD::SETUGT: Opc = ARMISD::VCGTU; break; 4178 case ISD::SETULE: Swap = true; 4179 case ISD::SETUGE: Opc = ARMISD::VCGEU; break; 4180 } 4181 4182 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero). 4183 if (Opc == ARMISD::VCEQ) { 4184 4185 SDValue AndOp; 4186 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4187 AndOp = Op0; 4188 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) 4189 AndOp = Op1; 4190 4191 // Ignore bitconvert. 4192 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST) 4193 AndOp = AndOp.getOperand(0); 4194 4195 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) { 4196 Opc = ARMISD::VTST; 4197 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0)); 4198 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1)); 4199 Invert = !Invert; 4200 } 4201 } 4202 } 4203 4204 if (Swap) 4205 std::swap(Op0, Op1); 4206 4207 // If one of the operands is a constant vector zero, attempt to fold the 4208 // comparison to a specialized compare-against-zero form. 4209 SDValue SingleOp; 4210 if (ISD::isBuildVectorAllZeros(Op1.getNode())) 4211 SingleOp = Op0; 4212 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) { 4213 if (Opc == ARMISD::VCGE) 4214 Opc = ARMISD::VCLEZ; 4215 else if (Opc == ARMISD::VCGT) 4216 Opc = ARMISD::VCLTZ; 4217 SingleOp = Op1; 4218 } 4219 4220 SDValue Result; 4221 if (SingleOp.getNode()) { 4222 switch (Opc) { 4223 case ARMISD::VCEQ: 4224 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break; 4225 case ARMISD::VCGE: 4226 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break; 4227 case ARMISD::VCLEZ: 4228 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break; 4229 case ARMISD::VCGT: 4230 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break; 4231 case ARMISD::VCLTZ: 4232 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break; 4233 default: 4234 Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 4235 } 4236 } else { 4237 Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 4238 } 4239 4240 if (Invert) 4241 Result = DAG.getNOT(dl, Result, VT); 4242 4243 return Result; 4244 } 4245 4246 /// isNEONModifiedImm - Check if the specified splat value corresponds to a 4247 /// valid vector constant for a NEON instruction with a "modified immediate" 4248 /// operand (e.g., VMOV). If so, return the encoded value. 4249 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef, 4250 unsigned SplatBitSize, SelectionDAG &DAG, 4251 EVT &VT, bool is128Bits, NEONModImmType type) { 4252 unsigned OpCmode, Imm; 4253 4254 // SplatBitSize is set to the smallest size that splats the vector, so a 4255 // zero vector will always have SplatBitSize == 8. However, NEON modified 4256 // immediate instructions others than VMOV do not support the 8-bit encoding 4257 // of a zero vector, and the default encoding of zero is supposed to be the 4258 // 32-bit version. 4259 if (SplatBits == 0) 4260 SplatBitSize = 32; 4261 4262 switch (SplatBitSize) { 4263 case 8: 4264 if (type != VMOVModImm) 4265 return SDValue(); 4266 // Any 1-byte value is OK. Op=0, Cmode=1110. 4267 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big"); 4268 OpCmode = 0xe; 4269 Imm = SplatBits; 4270 VT = is128Bits ? MVT::v16i8 : MVT::v8i8; 4271 break; 4272 4273 case 16: 4274 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero. 4275 VT = is128Bits ? MVT::v8i16 : MVT::v4i16; 4276 if ((SplatBits & ~0xff) == 0) { 4277 // Value = 0x00nn: Op=x, Cmode=100x. 4278 OpCmode = 0x8; 4279 Imm = SplatBits; 4280 break; 4281 } 4282 if ((SplatBits & ~0xff00) == 0) { 4283 // Value = 0xnn00: Op=x, Cmode=101x. 4284 OpCmode = 0xa; 4285 Imm = SplatBits >> 8; 4286 break; 4287 } 4288 return SDValue(); 4289 4290 case 32: 4291 // NEON's 32-bit VMOV supports splat values where: 4292 // * only one byte is nonzero, or 4293 // * the least significant byte is 0xff and the second byte is nonzero, or 4294 // * the least significant 2 bytes are 0xff and the third is nonzero. 4295 VT = is128Bits ? MVT::v4i32 : MVT::v2i32; 4296 if ((SplatBits & ~0xff) == 0) { 4297 // Value = 0x000000nn: Op=x, Cmode=000x. 4298 OpCmode = 0; 4299 Imm = SplatBits; 4300 break; 4301 } 4302 if ((SplatBits & ~0xff00) == 0) { 4303 // Value = 0x0000nn00: Op=x, Cmode=001x. 4304 OpCmode = 0x2; 4305 Imm = SplatBits >> 8; 4306 break; 4307 } 4308 if ((SplatBits & ~0xff0000) == 0) { 4309 // Value = 0x00nn0000: Op=x, Cmode=010x. 4310 OpCmode = 0x4; 4311 Imm = SplatBits >> 16; 4312 break; 4313 } 4314 if ((SplatBits & ~0xff000000) == 0) { 4315 // Value = 0xnn000000: Op=x, Cmode=011x. 4316 OpCmode = 0x6; 4317 Imm = SplatBits >> 24; 4318 break; 4319 } 4320 4321 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC 4322 if (type == OtherModImm) return SDValue(); 4323 4324 if ((SplatBits & ~0xffff) == 0 && 4325 ((SplatBits | SplatUndef) & 0xff) == 0xff) { 4326 // Value = 0x0000nnff: Op=x, Cmode=1100. 4327 OpCmode = 0xc; 4328 Imm = SplatBits >> 8; 4329 break; 4330 } 4331 4332 if ((SplatBits & ~0xffffff) == 0 && 4333 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) { 4334 // Value = 0x00nnffff: Op=x, Cmode=1101. 4335 OpCmode = 0xd; 4336 Imm = SplatBits >> 16; 4337 break; 4338 } 4339 4340 // Note: there are a few 32-bit splat values (specifically: 00ffff00, 4341 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not 4342 // VMOV.I32. A (very) minor optimization would be to replicate the value 4343 // and fall through here to test for a valid 64-bit splat. But, then the 4344 // caller would also need to check and handle the change in size. 4345 return SDValue(); 4346 4347 case 64: { 4348 if (type != VMOVModImm) 4349 return SDValue(); 4350 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff. 4351 uint64_t BitMask = 0xff; 4352 uint64_t Val = 0; 4353 unsigned ImmMask = 1; 4354 Imm = 0; 4355 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) { 4356 if (((SplatBits | SplatUndef) & BitMask) == BitMask) { 4357 Val |= BitMask; 4358 Imm |= ImmMask; 4359 } else if ((SplatBits & BitMask) != 0) { 4360 return SDValue(); 4361 } 4362 BitMask <<= 8; 4363 ImmMask <<= 1; 4364 } 4365 // Op=1, Cmode=1110. 4366 OpCmode = 0x1e; 4367 VT = is128Bits ? MVT::v2i64 : MVT::v1i64; 4368 break; 4369 } 4370 4371 default: 4372 llvm_unreachable("unexpected size for isNEONModifiedImm"); 4373 } 4374 4375 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm); 4376 return DAG.getTargetConstant(EncodedVal, MVT::i32); 4377 } 4378 4379 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG, 4380 const ARMSubtarget *ST) const { 4381 if (!ST->hasVFP3()) 4382 return SDValue(); 4383 4384 bool IsDouble = Op.getValueType() == MVT::f64; 4385 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op); 4386 4387 // Try splatting with a VMOV.f32... 4388 APFloat FPVal = CFP->getValueAPF(); 4389 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal); 4390 4391 if (ImmVal != -1) { 4392 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) { 4393 // We have code in place to select a valid ConstantFP already, no need to 4394 // do any mangling. 4395 return Op; 4396 } 4397 4398 // It's a float and we are trying to use NEON operations where 4399 // possible. Lower it to a splat followed by an extract. 4400 SDLoc DL(Op); 4401 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32); 4402 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32, 4403 NewVal); 4404 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant, 4405 DAG.getConstant(0, MVT::i32)); 4406 } 4407 4408 // The rest of our options are NEON only, make sure that's allowed before 4409 // proceeding.. 4410 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP())) 4411 return SDValue(); 4412 4413 EVT VMovVT; 4414 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue(); 4415 4416 // It wouldn't really be worth bothering for doubles except for one very 4417 // important value, which does happen to match: 0.0. So make sure we don't do 4418 // anything stupid. 4419 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32)) 4420 return SDValue(); 4421 4422 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too). 4423 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT, 4424 false, VMOVModImm); 4425 if (NewVal != SDValue()) { 4426 SDLoc DL(Op); 4427 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT, 4428 NewVal); 4429 if (IsDouble) 4430 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 4431 4432 // It's a float: cast and extract a vector element. 4433 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 4434 VecConstant); 4435 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 4436 DAG.getConstant(0, MVT::i32)); 4437 } 4438 4439 // Finally, try a VMVN.i32 4440 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT, 4441 false, VMVNModImm); 4442 if (NewVal != SDValue()) { 4443 SDLoc DL(Op); 4444 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal); 4445 4446 if (IsDouble) 4447 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant); 4448 4449 // It's a float: cast and extract a vector element. 4450 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, 4451 VecConstant); 4452 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant, 4453 DAG.getConstant(0, MVT::i32)); 4454 } 4455 4456 return SDValue(); 4457 } 4458 4459 // check if an VEXT instruction can handle the shuffle mask when the 4460 // vector sources of the shuffle are the same. 4461 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 4462 unsigned NumElts = VT.getVectorNumElements(); 4463 4464 // Assume that the first shuffle index is not UNDEF. Fail if it is. 4465 if (M[0] < 0) 4466 return false; 4467 4468 Imm = M[0]; 4469 4470 // If this is a VEXT shuffle, the immediate value is the index of the first 4471 // element. The other shuffle indices must be the successive elements after 4472 // the first one. 4473 unsigned ExpectedElt = Imm; 4474 for (unsigned i = 1; i < NumElts; ++i) { 4475 // Increment the expected index. If it wraps around, just follow it 4476 // back to index zero and keep going. 4477 ++ExpectedElt; 4478 if (ExpectedElt == NumElts) 4479 ExpectedElt = 0; 4480 4481 if (M[i] < 0) continue; // ignore UNDEF indices 4482 if (ExpectedElt != static_cast<unsigned>(M[i])) 4483 return false; 4484 } 4485 4486 return true; 4487 } 4488 4489 4490 static bool isVEXTMask(ArrayRef<int> M, EVT VT, 4491 bool &ReverseVEXT, unsigned &Imm) { 4492 unsigned NumElts = VT.getVectorNumElements(); 4493 ReverseVEXT = false; 4494 4495 // Assume that the first shuffle index is not UNDEF. Fail if it is. 4496 if (M[0] < 0) 4497 return false; 4498 4499 Imm = M[0]; 4500 4501 // If this is a VEXT shuffle, the immediate value is the index of the first 4502 // element. The other shuffle indices must be the successive elements after 4503 // the first one. 4504 unsigned ExpectedElt = Imm; 4505 for (unsigned i = 1; i < NumElts; ++i) { 4506 // Increment the expected index. If it wraps around, it may still be 4507 // a VEXT but the source vectors must be swapped. 4508 ExpectedElt += 1; 4509 if (ExpectedElt == NumElts * 2) { 4510 ExpectedElt = 0; 4511 ReverseVEXT = true; 4512 } 4513 4514 if (M[i] < 0) continue; // ignore UNDEF indices 4515 if (ExpectedElt != static_cast<unsigned>(M[i])) 4516 return false; 4517 } 4518 4519 // Adjust the index value if the source operands will be swapped. 4520 if (ReverseVEXT) 4521 Imm -= NumElts; 4522 4523 return true; 4524 } 4525 4526 /// isVREVMask - Check if a vector shuffle corresponds to a VREV 4527 /// instruction with the specified blocksize. (The order of the elements 4528 /// within each block of the vector is reversed.) 4529 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 4530 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) && 4531 "Only possible block sizes for VREV are: 16, 32, 64"); 4532 4533 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 4534 if (EltSz == 64) 4535 return false; 4536 4537 unsigned NumElts = VT.getVectorNumElements(); 4538 unsigned BlockElts = M[0] + 1; 4539 // If the first shuffle index is UNDEF, be optimistic. 4540 if (M[0] < 0) 4541 BlockElts = BlockSize / EltSz; 4542 4543 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 4544 return false; 4545 4546 for (unsigned i = 0; i < NumElts; ++i) { 4547 if (M[i] < 0) continue; // ignore UNDEF indices 4548 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts)) 4549 return false; 4550 } 4551 4552 return true; 4553 } 4554 4555 static bool isVTBLMask(ArrayRef<int> M, EVT VT) { 4556 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of 4557 // range, then 0 is placed into the resulting vector. So pretty much any mask 4558 // of 8 elements can work here. 4559 return VT == MVT::v8i8 && M.size() == 8; 4560 } 4561 4562 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 4563 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 4564 if (EltSz == 64) 4565 return false; 4566 4567 unsigned NumElts = VT.getVectorNumElements(); 4568 WhichResult = (M[0] == 0 ? 0 : 1); 4569 for (unsigned i = 0; i < NumElts; i += 2) { 4570 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) || 4571 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult)) 4572 return false; 4573 } 4574 return true; 4575 } 4576 4577 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of 4578 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 4579 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 4580 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 4581 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 4582 if (EltSz == 64) 4583 return false; 4584 4585 unsigned NumElts = VT.getVectorNumElements(); 4586 WhichResult = (M[0] == 0 ? 0 : 1); 4587 for (unsigned i = 0; i < NumElts; i += 2) { 4588 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) || 4589 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult)) 4590 return false; 4591 } 4592 return true; 4593 } 4594 4595 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 4596 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 4597 if (EltSz == 64) 4598 return false; 4599 4600 unsigned NumElts = VT.getVectorNumElements(); 4601 WhichResult = (M[0] == 0 ? 0 : 1); 4602 for (unsigned i = 0; i != NumElts; ++i) { 4603 if (M[i] < 0) continue; // ignore UNDEF indices 4604 if ((unsigned) M[i] != 2 * i + WhichResult) 4605 return false; 4606 } 4607 4608 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 4609 if (VT.is64BitVector() && EltSz == 32) 4610 return false; 4611 4612 return true; 4613 } 4614 4615 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of 4616 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 4617 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 4618 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 4619 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 4620 if (EltSz == 64) 4621 return false; 4622 4623 unsigned Half = VT.getVectorNumElements() / 2; 4624 WhichResult = (M[0] == 0 ? 0 : 1); 4625 for (unsigned j = 0; j != 2; ++j) { 4626 unsigned Idx = WhichResult; 4627 for (unsigned i = 0; i != Half; ++i) { 4628 int MIdx = M[i + j * Half]; 4629 if (MIdx >= 0 && (unsigned) MIdx != Idx) 4630 return false; 4631 Idx += 2; 4632 } 4633 } 4634 4635 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 4636 if (VT.is64BitVector() && EltSz == 32) 4637 return false; 4638 4639 return true; 4640 } 4641 4642 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 4643 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 4644 if (EltSz == 64) 4645 return false; 4646 4647 unsigned NumElts = VT.getVectorNumElements(); 4648 WhichResult = (M[0] == 0 ? 0 : 1); 4649 unsigned Idx = WhichResult * NumElts / 2; 4650 for (unsigned i = 0; i != NumElts; i += 2) { 4651 if ((M[i] >= 0 && (unsigned) M[i] != Idx) || 4652 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts)) 4653 return false; 4654 Idx += 1; 4655 } 4656 4657 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 4658 if (VT.is64BitVector() && EltSz == 32) 4659 return false; 4660 4661 return true; 4662 } 4663 4664 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of 4665 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 4666 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 4667 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){ 4668 unsigned EltSz = VT.getVectorElementType().getSizeInBits(); 4669 if (EltSz == 64) 4670 return false; 4671 4672 unsigned NumElts = VT.getVectorNumElements(); 4673 WhichResult = (M[0] == 0 ? 0 : 1); 4674 unsigned Idx = WhichResult * NumElts / 2; 4675 for (unsigned i = 0; i != NumElts; i += 2) { 4676 if ((M[i] >= 0 && (unsigned) M[i] != Idx) || 4677 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx)) 4678 return false; 4679 Idx += 1; 4680 } 4681 4682 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32. 4683 if (VT.is64BitVector() && EltSz == 32) 4684 return false; 4685 4686 return true; 4687 } 4688 4689 /// \return true if this is a reverse operation on an vector. 4690 static bool isReverseMask(ArrayRef<int> M, EVT VT) { 4691 unsigned NumElts = VT.getVectorNumElements(); 4692 // Make sure the mask has the right size. 4693 if (NumElts != M.size()) 4694 return false; 4695 4696 // Look for <15, ..., 3, -1, 1, 0>. 4697 for (unsigned i = 0; i != NumElts; ++i) 4698 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i)) 4699 return false; 4700 4701 return true; 4702 } 4703 4704 // If N is an integer constant that can be moved into a register in one 4705 // instruction, return an SDValue of such a constant (will become a MOV 4706 // instruction). Otherwise return null. 4707 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG, 4708 const ARMSubtarget *ST, SDLoc dl) { 4709 uint64_t Val; 4710 if (!isa<ConstantSDNode>(N)) 4711 return SDValue(); 4712 Val = cast<ConstantSDNode>(N)->getZExtValue(); 4713 4714 if (ST->isThumb1Only()) { 4715 if (Val <= 255 || ~Val <= 255) 4716 return DAG.getConstant(Val, MVT::i32); 4717 } else { 4718 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1) 4719 return DAG.getConstant(Val, MVT::i32); 4720 } 4721 return SDValue(); 4722 } 4723 4724 // If this is a case we can't handle, return null and let the default 4725 // expansion code take care of it. 4726 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 4727 const ARMSubtarget *ST) const { 4728 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 4729 SDLoc dl(Op); 4730 EVT VT = Op.getValueType(); 4731 4732 APInt SplatBits, SplatUndef; 4733 unsigned SplatBitSize; 4734 bool HasAnyUndefs; 4735 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 4736 if (SplatBitSize <= 64) { 4737 // Check if an immediate VMOV works. 4738 EVT VmovVT; 4739 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 4740 SplatUndef.getZExtValue(), SplatBitSize, 4741 DAG, VmovVT, VT.is128BitVector(), 4742 VMOVModImm); 4743 if (Val.getNode()) { 4744 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val); 4745 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4746 } 4747 4748 // Try an immediate VMVN. 4749 uint64_t NegatedImm = (~SplatBits).getZExtValue(); 4750 Val = isNEONModifiedImm(NegatedImm, 4751 SplatUndef.getZExtValue(), SplatBitSize, 4752 DAG, VmovVT, VT.is128BitVector(), 4753 VMVNModImm); 4754 if (Val.getNode()) { 4755 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val); 4756 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov); 4757 } 4758 4759 // Use vmov.f32 to materialize other v2f32 and v4f32 splats. 4760 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) { 4761 int ImmVal = ARM_AM::getFP32Imm(SplatBits); 4762 if (ImmVal != -1) { 4763 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32); 4764 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val); 4765 } 4766 } 4767 } 4768 } 4769 4770 // Scan through the operands to see if only one value is used. 4771 // 4772 // As an optimisation, even if more than one value is used it may be more 4773 // profitable to splat with one value then change some lanes. 4774 // 4775 // Heuristically we decide to do this if the vector has a "dominant" value, 4776 // defined as splatted to more than half of the lanes. 4777 unsigned NumElts = VT.getVectorNumElements(); 4778 bool isOnlyLowElement = true; 4779 bool usesOnlyOneValue = true; 4780 bool hasDominantValue = false; 4781 bool isConstant = true; 4782 4783 // Map of the number of times a particular SDValue appears in the 4784 // element list. 4785 DenseMap<SDValue, unsigned> ValueCounts; 4786 SDValue Value; 4787 for (unsigned i = 0; i < NumElts; ++i) { 4788 SDValue V = Op.getOperand(i); 4789 if (V.getOpcode() == ISD::UNDEF) 4790 continue; 4791 if (i > 0) 4792 isOnlyLowElement = false; 4793 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 4794 isConstant = false; 4795 4796 ValueCounts.insert(std::make_pair(V, 0)); 4797 unsigned &Count = ValueCounts[V]; 4798 4799 // Is this value dominant? (takes up more than half of the lanes) 4800 if (++Count > (NumElts / 2)) { 4801 hasDominantValue = true; 4802 Value = V; 4803 } 4804 } 4805 if (ValueCounts.size() != 1) 4806 usesOnlyOneValue = false; 4807 if (!Value.getNode() && ValueCounts.size() > 0) 4808 Value = ValueCounts.begin()->first; 4809 4810 if (ValueCounts.size() == 0) 4811 return DAG.getUNDEF(VT); 4812 4813 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR. 4814 // Keep going if we are hitting this case. 4815 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode())) 4816 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 4817 4818 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 4819 4820 // Use VDUP for non-constant splats. For f32 constant splats, reduce to 4821 // i32 and try again. 4822 if (hasDominantValue && EltSize <= 32) { 4823 if (!isConstant) { 4824 SDValue N; 4825 4826 // If we are VDUPing a value that comes directly from a vector, that will 4827 // cause an unnecessary move to and from a GPR, where instead we could 4828 // just use VDUPLANE. We can only do this if the lane being extracted 4829 // is at a constant index, as the VDUP from lane instructions only have 4830 // constant-index forms. 4831 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 4832 isa<ConstantSDNode>(Value->getOperand(1))) { 4833 // We need to create a new undef vector to use for the VDUPLANE if the 4834 // size of the vector from which we get the value is different than the 4835 // size of the vector that we need to create. We will insert the element 4836 // such that the register coalescer will remove unnecessary copies. 4837 if (VT != Value->getOperand(0).getValueType()) { 4838 ConstantSDNode *constIndex; 4839 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)); 4840 assert(constIndex && "The index is not a constant!"); 4841 unsigned index = constIndex->getAPIntValue().getLimitedValue() % 4842 VT.getVectorNumElements(); 4843 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 4844 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT), 4845 Value, DAG.getConstant(index, MVT::i32)), 4846 DAG.getConstant(index, MVT::i32)); 4847 } else 4848 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT, 4849 Value->getOperand(0), Value->getOperand(1)); 4850 } else 4851 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value); 4852 4853 if (!usesOnlyOneValue) { 4854 // The dominant value was splatted as 'N', but we now have to insert 4855 // all differing elements. 4856 for (unsigned I = 0; I < NumElts; ++I) { 4857 if (Op.getOperand(I) == Value) 4858 continue; 4859 SmallVector<SDValue, 3> Ops; 4860 Ops.push_back(N); 4861 Ops.push_back(Op.getOperand(I)); 4862 Ops.push_back(DAG.getConstant(I, MVT::i32)); 4863 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3); 4864 } 4865 } 4866 return N; 4867 } 4868 if (VT.getVectorElementType().isFloatingPoint()) { 4869 SmallVector<SDValue, 8> Ops; 4870 for (unsigned i = 0; i < NumElts; ++i) 4871 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32, 4872 Op.getOperand(i))); 4873 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 4874 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts); 4875 Val = LowerBUILD_VECTOR(Val, DAG, ST); 4876 if (Val.getNode()) 4877 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 4878 } 4879 if (usesOnlyOneValue) { 4880 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl); 4881 if (isConstant && Val.getNode()) 4882 return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 4883 } 4884 } 4885 4886 // If all elements are constants and the case above didn't get hit, fall back 4887 // to the default expansion, which will generate a load from the constant 4888 // pool. 4889 if (isConstant) 4890 return SDValue(); 4891 4892 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 4893 if (NumElts >= 4) { 4894 SDValue shuffle = ReconstructShuffle(Op, DAG); 4895 if (shuffle != SDValue()) 4896 return shuffle; 4897 } 4898 4899 // Vectors with 32- or 64-bit elements can be built by directly assigning 4900 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands 4901 // will be legalized. 4902 if (EltSize >= 32) { 4903 // Do the expansion with floating-point types, since that is what the VFP 4904 // registers are defined to use, and since i64 is not legal. 4905 EVT EltVT = EVT::getFloatingPointVT(EltSize); 4906 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 4907 SmallVector<SDValue, 8> Ops; 4908 for (unsigned i = 0; i < NumElts; ++i) 4909 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i))); 4910 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts); 4911 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 4912 } 4913 4914 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 4915 // know the default expansion would otherwise fall back on something even 4916 // worse. For a vector with one or two non-undef values, that's 4917 // scalar_to_vector for the elements followed by a shuffle (provided the 4918 // shuffle is valid for the target) and materialization element by element 4919 // on the stack followed by a load for everything else. 4920 if (!isConstant && !usesOnlyOneValue) { 4921 SDValue Vec = DAG.getUNDEF(VT); 4922 for (unsigned i = 0 ; i < NumElts; ++i) { 4923 SDValue V = Op.getOperand(i); 4924 if (V.getOpcode() == ISD::UNDEF) 4925 continue; 4926 SDValue LaneIdx = DAG.getConstant(i, MVT::i32); 4927 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 4928 } 4929 return Vec; 4930 } 4931 4932 return SDValue(); 4933 } 4934 4935 // Gather data to see if the operation can be modelled as a 4936 // shuffle in combination with VEXTs. 4937 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op, 4938 SelectionDAG &DAG) const { 4939 SDLoc dl(Op); 4940 EVT VT = Op.getValueType(); 4941 unsigned NumElts = VT.getVectorNumElements(); 4942 4943 SmallVector<SDValue, 2> SourceVecs; 4944 SmallVector<unsigned, 2> MinElts; 4945 SmallVector<unsigned, 2> MaxElts; 4946 4947 for (unsigned i = 0; i < NumElts; ++i) { 4948 SDValue V = Op.getOperand(i); 4949 if (V.getOpcode() == ISD::UNDEF) 4950 continue; 4951 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) { 4952 // A shuffle can only come from building a vector from various 4953 // elements of other vectors. 4954 return SDValue(); 4955 } else if (V.getOperand(0).getValueType().getVectorElementType() != 4956 VT.getVectorElementType()) { 4957 // This code doesn't know how to handle shuffles where the vector 4958 // element types do not match (this happens because type legalization 4959 // promotes the return type of EXTRACT_VECTOR_ELT). 4960 // FIXME: It might be appropriate to extend this code to handle 4961 // mismatched types. 4962 return SDValue(); 4963 } 4964 4965 // Record this extraction against the appropriate vector if possible... 4966 SDValue SourceVec = V.getOperand(0); 4967 // If the element number isn't a constant, we can't effectively 4968 // analyze what's going on. 4969 if (!isa<ConstantSDNode>(V.getOperand(1))) 4970 return SDValue(); 4971 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 4972 bool FoundSource = false; 4973 for (unsigned j = 0; j < SourceVecs.size(); ++j) { 4974 if (SourceVecs[j] == SourceVec) { 4975 if (MinElts[j] > EltNo) 4976 MinElts[j] = EltNo; 4977 if (MaxElts[j] < EltNo) 4978 MaxElts[j] = EltNo; 4979 FoundSource = true; 4980 break; 4981 } 4982 } 4983 4984 // Or record a new source if not... 4985 if (!FoundSource) { 4986 SourceVecs.push_back(SourceVec); 4987 MinElts.push_back(EltNo); 4988 MaxElts.push_back(EltNo); 4989 } 4990 } 4991 4992 // Currently only do something sane when at most two source vectors 4993 // involved. 4994 if (SourceVecs.size() > 2) 4995 return SDValue(); 4996 4997 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) }; 4998 int VEXTOffsets[2] = {0, 0}; 4999 5000 // This loop extracts the usage patterns of the source vectors 5001 // and prepares appropriate SDValues for a shuffle if possible. 5002 for (unsigned i = 0; i < SourceVecs.size(); ++i) { 5003 if (SourceVecs[i].getValueType() == VT) { 5004 // No VEXT necessary 5005 ShuffleSrcs[i] = SourceVecs[i]; 5006 VEXTOffsets[i] = 0; 5007 continue; 5008 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) { 5009 // It probably isn't worth padding out a smaller vector just to 5010 // break it down again in a shuffle. 5011 return SDValue(); 5012 } 5013 5014 // Since only 64-bit and 128-bit vectors are legal on ARM and 5015 // we've eliminated the other cases... 5016 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts && 5017 "unexpected vector sizes in ReconstructShuffle"); 5018 5019 if (MaxElts[i] - MinElts[i] >= NumElts) { 5020 // Span too large for a VEXT to cope 5021 return SDValue(); 5022 } 5023 5024 if (MinElts[i] >= NumElts) { 5025 // The extraction can just take the second half 5026 VEXTOffsets[i] = NumElts; 5027 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, 5028 SourceVecs[i], 5029 DAG.getIntPtrConstant(NumElts)); 5030 } else if (MaxElts[i] < NumElts) { 5031 // The extraction can just take the first half 5032 VEXTOffsets[i] = 0; 5033 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, 5034 SourceVecs[i], 5035 DAG.getIntPtrConstant(0)); 5036 } else { 5037 // An actual VEXT is needed 5038 VEXTOffsets[i] = MinElts[i]; 5039 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, 5040 SourceVecs[i], 5041 DAG.getIntPtrConstant(0)); 5042 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, 5043 SourceVecs[i], 5044 DAG.getIntPtrConstant(NumElts)); 5045 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2, 5046 DAG.getConstant(VEXTOffsets[i], MVT::i32)); 5047 } 5048 } 5049 5050 SmallVector<int, 8> Mask; 5051 5052 for (unsigned i = 0; i < NumElts; ++i) { 5053 SDValue Entry = Op.getOperand(i); 5054 if (Entry.getOpcode() == ISD::UNDEF) { 5055 Mask.push_back(-1); 5056 continue; 5057 } 5058 5059 SDValue ExtractVec = Entry.getOperand(0); 5060 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i) 5061 .getOperand(1))->getSExtValue(); 5062 if (ExtractVec == SourceVecs[0]) { 5063 Mask.push_back(ExtractElt - VEXTOffsets[0]); 5064 } else { 5065 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]); 5066 } 5067 } 5068 5069 // Final check before we try to produce nonsense... 5070 if (isShuffleMaskLegal(Mask, VT)) 5071 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1], 5072 &Mask[0]); 5073 5074 return SDValue(); 5075 } 5076 5077 /// isShuffleMaskLegal - Targets can use this to indicate that they only 5078 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 5079 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 5080 /// are assumed to be legal. 5081 bool 5082 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 5083 EVT VT) const { 5084 if (VT.getVectorNumElements() == 4 && 5085 (VT.is128BitVector() || VT.is64BitVector())) { 5086 unsigned PFIndexes[4]; 5087 for (unsigned i = 0; i != 4; ++i) { 5088 if (M[i] < 0) 5089 PFIndexes[i] = 8; 5090 else 5091 PFIndexes[i] = M[i]; 5092 } 5093 5094 // Compute the index in the perfect shuffle table. 5095 unsigned PFTableIndex = 5096 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5097 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5098 unsigned Cost = (PFEntry >> 30); 5099 5100 if (Cost <= 4) 5101 return true; 5102 } 5103 5104 bool ReverseVEXT; 5105 unsigned Imm, WhichResult; 5106 5107 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5108 return (EltSize >= 32 || 5109 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 5110 isVREVMask(M, VT, 64) || 5111 isVREVMask(M, VT, 32) || 5112 isVREVMask(M, VT, 16) || 5113 isVEXTMask(M, VT, ReverseVEXT, Imm) || 5114 isVTBLMask(M, VT) || 5115 isVTRNMask(M, VT, WhichResult) || 5116 isVUZPMask(M, VT, WhichResult) || 5117 isVZIPMask(M, VT, WhichResult) || 5118 isVTRN_v_undef_Mask(M, VT, WhichResult) || 5119 isVUZP_v_undef_Mask(M, VT, WhichResult) || 5120 isVZIP_v_undef_Mask(M, VT, WhichResult) || 5121 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT))); 5122 } 5123 5124 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5125 /// the specified operations to build the shuffle. 5126 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5127 SDValue RHS, SelectionDAG &DAG, 5128 SDLoc dl) { 5129 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5130 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 5131 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 5132 5133 enum { 5134 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5135 OP_VREV, 5136 OP_VDUP0, 5137 OP_VDUP1, 5138 OP_VDUP2, 5139 OP_VDUP3, 5140 OP_VEXT1, 5141 OP_VEXT2, 5142 OP_VEXT3, 5143 OP_VUZPL, // VUZP, left result 5144 OP_VUZPR, // VUZP, right result 5145 OP_VZIPL, // VZIP, left result 5146 OP_VZIPR, // VZIP, right result 5147 OP_VTRNL, // VTRN, left result 5148 OP_VTRNR // VTRN, right result 5149 }; 5150 5151 if (OpNum == OP_COPY) { 5152 if (LHSID == (1*9+2)*9+3) return LHS; 5153 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 5154 return RHS; 5155 } 5156 5157 SDValue OpLHS, OpRHS; 5158 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5159 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5160 EVT VT = OpLHS.getValueType(); 5161 5162 switch (OpNum) { 5163 default: llvm_unreachable("Unknown shuffle opcode!"); 5164 case OP_VREV: 5165 // VREV divides the vector in half and swaps within the half. 5166 if (VT.getVectorElementType() == MVT::i32 || 5167 VT.getVectorElementType() == MVT::f32) 5168 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS); 5169 // vrev <4 x i16> -> VREV32 5170 if (VT.getVectorElementType() == MVT::i16) 5171 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS); 5172 // vrev <4 x i8> -> VREV16 5173 assert(VT.getVectorElementType() == MVT::i8); 5174 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS); 5175 case OP_VDUP0: 5176 case OP_VDUP1: 5177 case OP_VDUP2: 5178 case OP_VDUP3: 5179 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, 5180 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32)); 5181 case OP_VEXT1: 5182 case OP_VEXT2: 5183 case OP_VEXT3: 5184 return DAG.getNode(ARMISD::VEXT, dl, VT, 5185 OpLHS, OpRHS, 5186 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32)); 5187 case OP_VUZPL: 5188 case OP_VUZPR: 5189 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 5190 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL); 5191 case OP_VZIPL: 5192 case OP_VZIPR: 5193 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 5194 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL); 5195 case OP_VTRNL: 5196 case OP_VTRNR: 5197 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 5198 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL); 5199 } 5200 } 5201 5202 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op, 5203 ArrayRef<int> ShuffleMask, 5204 SelectionDAG &DAG) { 5205 // Check to see if we can use the VTBL instruction. 5206 SDValue V1 = Op.getOperand(0); 5207 SDValue V2 = Op.getOperand(1); 5208 SDLoc DL(Op); 5209 5210 SmallVector<SDValue, 8> VTBLMask; 5211 for (ArrayRef<int>::iterator 5212 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I) 5213 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32)); 5214 5215 if (V2.getNode()->getOpcode() == ISD::UNDEF) 5216 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1, 5217 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, 5218 &VTBLMask[0], 8)); 5219 5220 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2, 5221 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, 5222 &VTBLMask[0], 8)); 5223 } 5224 5225 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op, 5226 SelectionDAG &DAG) { 5227 SDLoc DL(Op); 5228 SDValue OpLHS = Op.getOperand(0); 5229 EVT VT = OpLHS.getValueType(); 5230 5231 assert((VT == MVT::v8i16 || VT == MVT::v16i8) && 5232 "Expect an v8i16/v16i8 type"); 5233 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS); 5234 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now, 5235 // extract the first 8 bytes into the top double word and the last 8 bytes 5236 // into the bottom double word. The v8i16 case is similar. 5237 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4; 5238 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS, 5239 DAG.getConstant(ExtractNum, MVT::i32)); 5240 } 5241 5242 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) { 5243 SDValue V1 = Op.getOperand(0); 5244 SDValue V2 = Op.getOperand(1); 5245 SDLoc dl(Op); 5246 EVT VT = Op.getValueType(); 5247 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 5248 5249 // Convert shuffles that are directly supported on NEON to target-specific 5250 // DAG nodes, instead of keeping them as shuffles and matching them again 5251 // during code selection. This is more efficient and avoids the possibility 5252 // of inconsistencies between legalization and selection. 5253 // FIXME: floating-point vectors should be canonicalized to integer vectors 5254 // of the same time so that they get CSEd properly. 5255 ArrayRef<int> ShuffleMask = SVN->getMask(); 5256 5257 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5258 if (EltSize <= 32) { 5259 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) { 5260 int Lane = SVN->getSplatIndex(); 5261 // If this is undef splat, generate it via "just" vdup, if possible. 5262 if (Lane == -1) Lane = 0; 5263 5264 // Test if V1 is a SCALAR_TO_VECTOR. 5265 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5266 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 5267 } 5268 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR 5269 // (and probably will turn into a SCALAR_TO_VECTOR once legalization 5270 // reaches it). 5271 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR && 5272 !isa<ConstantSDNode>(V1.getOperand(0))) { 5273 bool IsScalarToVector = true; 5274 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) 5275 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) { 5276 IsScalarToVector = false; 5277 break; 5278 } 5279 if (IsScalarToVector) 5280 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0)); 5281 } 5282 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1, 5283 DAG.getConstant(Lane, MVT::i32)); 5284 } 5285 5286 bool ReverseVEXT; 5287 unsigned Imm; 5288 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) { 5289 if (ReverseVEXT) 5290 std::swap(V1, V2); 5291 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2, 5292 DAG.getConstant(Imm, MVT::i32)); 5293 } 5294 5295 if (isVREVMask(ShuffleMask, VT, 64)) 5296 return DAG.getNode(ARMISD::VREV64, dl, VT, V1); 5297 if (isVREVMask(ShuffleMask, VT, 32)) 5298 return DAG.getNode(ARMISD::VREV32, dl, VT, V1); 5299 if (isVREVMask(ShuffleMask, VT, 16)) 5300 return DAG.getNode(ARMISD::VREV16, dl, VT, V1); 5301 5302 if (V2->getOpcode() == ISD::UNDEF && 5303 isSingletonVEXTMask(ShuffleMask, VT, Imm)) { 5304 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1, 5305 DAG.getConstant(Imm, MVT::i32)); 5306 } 5307 5308 // Check for Neon shuffles that modify both input vectors in place. 5309 // If both results are used, i.e., if there are two shuffles with the same 5310 // source operands and with masks corresponding to both results of one of 5311 // these operations, DAG memoization will ensure that a single node is 5312 // used for both shuffles. 5313 unsigned WhichResult; 5314 if (isVTRNMask(ShuffleMask, VT, WhichResult)) 5315 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 5316 V1, V2).getValue(WhichResult); 5317 if (isVUZPMask(ShuffleMask, VT, WhichResult)) 5318 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 5319 V1, V2).getValue(WhichResult); 5320 if (isVZIPMask(ShuffleMask, VT, WhichResult)) 5321 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 5322 V1, V2).getValue(WhichResult); 5323 5324 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5325 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT), 5326 V1, V1).getValue(WhichResult); 5327 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5328 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT), 5329 V1, V1).getValue(WhichResult); 5330 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) 5331 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT), 5332 V1, V1).getValue(WhichResult); 5333 } 5334 5335 // If the shuffle is not directly supported and it has 4 elements, use 5336 // the PerfectShuffle-generated table to synthesize it from other shuffles. 5337 unsigned NumElts = VT.getVectorNumElements(); 5338 if (NumElts == 4) { 5339 unsigned PFIndexes[4]; 5340 for (unsigned i = 0; i != 4; ++i) { 5341 if (ShuffleMask[i] < 0) 5342 PFIndexes[i] = 8; 5343 else 5344 PFIndexes[i] = ShuffleMask[i]; 5345 } 5346 5347 // Compute the index in the perfect shuffle table. 5348 unsigned PFTableIndex = 5349 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 5350 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5351 unsigned Cost = (PFEntry >> 30); 5352 5353 if (Cost <= 4) 5354 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 5355 } 5356 5357 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs. 5358 if (EltSize >= 32) { 5359 // Do the expansion with floating-point types, since that is what the VFP 5360 // registers are defined to use, and since i64 is not legal. 5361 EVT EltVT = EVT::getFloatingPointVT(EltSize); 5362 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts); 5363 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1); 5364 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2); 5365 SmallVector<SDValue, 8> Ops; 5366 for (unsigned i = 0; i < NumElts; ++i) { 5367 if (ShuffleMask[i] < 0) 5368 Ops.push_back(DAG.getUNDEF(EltVT)); 5369 else 5370 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 5371 ShuffleMask[i] < (int)NumElts ? V1 : V2, 5372 DAG.getConstant(ShuffleMask[i] & (NumElts-1), 5373 MVT::i32))); 5374 } 5375 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts); 5376 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 5377 } 5378 5379 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT)) 5380 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG); 5381 5382 if (VT == MVT::v8i8) { 5383 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG); 5384 if (NewOp.getNode()) 5385 return NewOp; 5386 } 5387 5388 return SDValue(); 5389 } 5390 5391 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 5392 // INSERT_VECTOR_ELT is legal only for immediate indexes. 5393 SDValue Lane = Op.getOperand(2); 5394 if (!isa<ConstantSDNode>(Lane)) 5395 return SDValue(); 5396 5397 return Op; 5398 } 5399 5400 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) { 5401 // EXTRACT_VECTOR_ELT is legal only for immediate indexes. 5402 SDValue Lane = Op.getOperand(1); 5403 if (!isa<ConstantSDNode>(Lane)) 5404 return SDValue(); 5405 5406 SDValue Vec = Op.getOperand(0); 5407 if (Op.getValueType() == MVT::i32 && 5408 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) { 5409 SDLoc dl(Op); 5410 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane); 5411 } 5412 5413 return Op; 5414 } 5415 5416 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5417 // The only time a CONCAT_VECTORS operation can have legal types is when 5418 // two 64-bit vectors are concatenated to a 128-bit vector. 5419 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 && 5420 "unexpected CONCAT_VECTORS"); 5421 SDLoc dl(Op); 5422 SDValue Val = DAG.getUNDEF(MVT::v2f64); 5423 SDValue Op0 = Op.getOperand(0); 5424 SDValue Op1 = Op.getOperand(1); 5425 if (Op0.getOpcode() != ISD::UNDEF) 5426 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 5427 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0), 5428 DAG.getIntPtrConstant(0)); 5429 if (Op1.getOpcode() != ISD::UNDEF) 5430 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val, 5431 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1), 5432 DAG.getIntPtrConstant(1)); 5433 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val); 5434 } 5435 5436 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each 5437 /// element has been zero/sign-extended, depending on the isSigned parameter, 5438 /// from an integer type half its size. 5439 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 5440 bool isSigned) { 5441 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32. 5442 EVT VT = N->getValueType(0); 5443 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) { 5444 SDNode *BVN = N->getOperand(0).getNode(); 5445 if (BVN->getValueType(0) != MVT::v4i32 || 5446 BVN->getOpcode() != ISD::BUILD_VECTOR) 5447 return false; 5448 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0; 5449 unsigned HiElt = 1 - LoElt; 5450 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt)); 5451 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt)); 5452 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2)); 5453 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2)); 5454 if (!Lo0 || !Hi0 || !Lo1 || !Hi1) 5455 return false; 5456 if (isSigned) { 5457 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 && 5458 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32) 5459 return true; 5460 } else { 5461 if (Hi0->isNullValue() && Hi1->isNullValue()) 5462 return true; 5463 } 5464 return false; 5465 } 5466 5467 if (N->getOpcode() != ISD::BUILD_VECTOR) 5468 return false; 5469 5470 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 5471 SDNode *Elt = N->getOperand(i).getNode(); 5472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 5473 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 5474 unsigned HalfSize = EltSize / 2; 5475 if (isSigned) { 5476 if (!isIntN(HalfSize, C->getSExtValue())) 5477 return false; 5478 } else { 5479 if (!isUIntN(HalfSize, C->getZExtValue())) 5480 return false; 5481 } 5482 continue; 5483 } 5484 return false; 5485 } 5486 5487 return true; 5488 } 5489 5490 /// isSignExtended - Check if a node is a vector value that is sign-extended 5491 /// or a constant BUILD_VECTOR with sign-extended elements. 5492 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 5493 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N)) 5494 return true; 5495 if (isExtendedBUILD_VECTOR(N, DAG, true)) 5496 return true; 5497 return false; 5498 } 5499 5500 /// isZeroExtended - Check if a node is a vector value that is zero-extended 5501 /// or a constant BUILD_VECTOR with zero-extended elements. 5502 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 5503 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N)) 5504 return true; 5505 if (isExtendedBUILD_VECTOR(N, DAG, false)) 5506 return true; 5507 return false; 5508 } 5509 5510 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 5511 if (OrigVT.getSizeInBits() >= 64) 5512 return OrigVT; 5513 5514 assert(OrigVT.isSimple() && "Expecting a simple value type"); 5515 5516 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 5517 switch (OrigSimpleTy) { 5518 default: llvm_unreachable("Unexpected Vector Type"); 5519 case MVT::v2i8: 5520 case MVT::v2i16: 5521 return MVT::v2i32; 5522 case MVT::v4i8: 5523 return MVT::v4i16; 5524 } 5525 } 5526 5527 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total 5528 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL. 5529 /// We insert the required extension here to get the vector to fill a D register. 5530 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG, 5531 const EVT &OrigTy, 5532 const EVT &ExtTy, 5533 unsigned ExtOpcode) { 5534 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 5535 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 5536 // 64-bits we need to insert a new extension so that it will be 64-bits. 5537 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 5538 if (OrigTy.getSizeInBits() >= 64) 5539 return N; 5540 5541 // Must extend size to at least 64 bits to be used as an operand for VMULL. 5542 EVT NewVT = getExtensionTo64Bits(OrigTy); 5543 5544 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 5545 } 5546 5547 /// SkipLoadExtensionForVMULL - return a load of the original vector size that 5548 /// does not do any sign/zero extension. If the original vector is less 5549 /// than 64 bits, an appropriate extension will be added after the load to 5550 /// reach a total size of 64 bits. We have to add the extension separately 5551 /// because ARM does not have a sign/zero extending load for vectors. 5552 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) { 5553 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT()); 5554 5555 // The load already has the right type. 5556 if (ExtendedTy == LD->getMemoryVT()) 5557 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(), 5558 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(), 5559 LD->isNonTemporal(), LD->isInvariant(), 5560 LD->getAlignment()); 5561 5562 // We need to create a zextload/sextload. We cannot just create a load 5563 // followed by a zext/zext node because LowerMUL is also run during normal 5564 // operation legalization where we can't create illegal types. 5565 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy, 5566 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(), 5567 LD->getMemoryVT(), LD->isVolatile(), 5568 LD->isNonTemporal(), LD->getAlignment()); 5569 } 5570 5571 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND, 5572 /// extending load, or BUILD_VECTOR with extended elements, return the 5573 /// unextended value. The unextended vector should be 64 bits so that it can 5574 /// be used as an operand to a VMULL instruction. If the original vector size 5575 /// before extension is less than 64 bits we add a an extension to resize 5576 /// the vector to 64 bits. 5577 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) { 5578 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 5579 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG, 5580 N->getOperand(0)->getValueType(0), 5581 N->getValueType(0), 5582 N->getOpcode()); 5583 5584 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) 5585 return SkipLoadExtensionForVMULL(LD, DAG); 5586 5587 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will 5588 // have been legalized as a BITCAST from v4i32. 5589 if (N->getOpcode() == ISD::BITCAST) { 5590 SDNode *BVN = N->getOperand(0).getNode(); 5591 assert(BVN->getOpcode() == ISD::BUILD_VECTOR && 5592 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR"); 5593 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0; 5594 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32, 5595 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2)); 5596 } 5597 // Construct a new BUILD_VECTOR with elements truncated to half the size. 5598 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 5599 EVT VT = N->getValueType(0); 5600 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2; 5601 unsigned NumElts = VT.getVectorNumElements(); 5602 MVT TruncVT = MVT::getIntegerVT(EltSize); 5603 SmallVector<SDValue, 8> Ops; 5604 for (unsigned i = 0; i != NumElts; ++i) { 5605 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 5606 const APInt &CInt = C->getAPIntValue(); 5607 // Element types smaller than 32 bits are not legal, so use i32 elements. 5608 // The values are implicitly truncated so sext vs. zext doesn't matter. 5609 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32)); 5610 } 5611 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 5612 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts); 5613 } 5614 5615 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 5616 unsigned Opcode = N->getOpcode(); 5617 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 5618 SDNode *N0 = N->getOperand(0).getNode(); 5619 SDNode *N1 = N->getOperand(1).getNode(); 5620 return N0->hasOneUse() && N1->hasOneUse() && 5621 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 5622 } 5623 return false; 5624 } 5625 5626 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 5627 unsigned Opcode = N->getOpcode(); 5628 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 5629 SDNode *N0 = N->getOperand(0).getNode(); 5630 SDNode *N1 = N->getOperand(1).getNode(); 5631 return N0->hasOneUse() && N1->hasOneUse() && 5632 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 5633 } 5634 return false; 5635 } 5636 5637 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 5638 // Multiplications are only custom-lowered for 128-bit vectors so that 5639 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 5640 EVT VT = Op.getValueType(); 5641 assert(VT.is128BitVector() && VT.isInteger() && 5642 "unexpected type for custom-lowering ISD::MUL"); 5643 SDNode *N0 = Op.getOperand(0).getNode(); 5644 SDNode *N1 = Op.getOperand(1).getNode(); 5645 unsigned NewOpc = 0; 5646 bool isMLA = false; 5647 bool isN0SExt = isSignExtended(N0, DAG); 5648 bool isN1SExt = isSignExtended(N1, DAG); 5649 if (isN0SExt && isN1SExt) 5650 NewOpc = ARMISD::VMULLs; 5651 else { 5652 bool isN0ZExt = isZeroExtended(N0, DAG); 5653 bool isN1ZExt = isZeroExtended(N1, DAG); 5654 if (isN0ZExt && isN1ZExt) 5655 NewOpc = ARMISD::VMULLu; 5656 else if (isN1SExt || isN1ZExt) { 5657 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 5658 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 5659 if (isN1SExt && isAddSubSExt(N0, DAG)) { 5660 NewOpc = ARMISD::VMULLs; 5661 isMLA = true; 5662 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 5663 NewOpc = ARMISD::VMULLu; 5664 isMLA = true; 5665 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 5666 std::swap(N0, N1); 5667 NewOpc = ARMISD::VMULLu; 5668 isMLA = true; 5669 } 5670 } 5671 5672 if (!NewOpc) { 5673 if (VT == MVT::v2i64) 5674 // Fall through to expand this. It is not legal. 5675 return SDValue(); 5676 else 5677 // Other vector multiplications are legal. 5678 return Op; 5679 } 5680 } 5681 5682 // Legalize to a VMULL instruction. 5683 SDLoc DL(Op); 5684 SDValue Op0; 5685 SDValue Op1 = SkipExtensionForVMULL(N1, DAG); 5686 if (!isMLA) { 5687 Op0 = SkipExtensionForVMULL(N0, DAG); 5688 assert(Op0.getValueType().is64BitVector() && 5689 Op1.getValueType().is64BitVector() && 5690 "unexpected types for extended operands to VMULL"); 5691 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 5692 } 5693 5694 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during 5695 // isel lowering to take advantage of no-stall back to back vmul + vmla. 5696 // vmull q0, d4, d6 5697 // vmlal q0, d5, d6 5698 // is faster than 5699 // vaddl q0, d4, d5 5700 // vmovl q1, d6 5701 // vmul q0, q0, q1 5702 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG); 5703 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG); 5704 EVT Op1VT = Op1.getValueType(); 5705 return DAG.getNode(N0->getOpcode(), DL, VT, 5706 DAG.getNode(NewOpc, DL, VT, 5707 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 5708 DAG.getNode(NewOpc, DL, VT, 5709 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 5710 } 5711 5712 static SDValue 5713 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) { 5714 // Convert to float 5715 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo)); 5716 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo)); 5717 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X); 5718 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y); 5719 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X); 5720 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y); 5721 // Get reciprocal estimate. 5722 // float4 recip = vrecpeq_f32(yf); 5723 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 5724 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y); 5725 // Because char has a smaller range than uchar, we can actually get away 5726 // without any newton steps. This requires that we use a weird bias 5727 // of 0xb000, however (again, this has been exhaustively tested). 5728 // float4 result = as_float4(as_int4(xf*recip) + 0xb000); 5729 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y); 5730 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X); 5731 Y = DAG.getConstant(0xb000, MVT::i32); 5732 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y); 5733 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y); 5734 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X); 5735 // Convert back to short. 5736 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X); 5737 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X); 5738 return X; 5739 } 5740 5741 static SDValue 5742 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) { 5743 SDValue N2; 5744 // Convert to float. 5745 // float4 yf = vcvt_f32_s32(vmovl_s16(y)); 5746 // float4 xf = vcvt_f32_s32(vmovl_s16(x)); 5747 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0); 5748 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1); 5749 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 5750 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 5751 5752 // Use reciprocal estimate and one refinement step. 5753 // float4 recip = vrecpeq_f32(yf); 5754 // recip *= vrecpsq_f32(yf, recip); 5755 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 5756 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1); 5757 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 5758 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32), 5759 N1, N2); 5760 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 5761 // Because short has a smaller range than ushort, we can actually get away 5762 // with only a single newton step. This requires that we use a weird bias 5763 // of 89, however (again, this has been exhaustively tested). 5764 // float4 result = as_float4(as_int4(xf*recip) + 0x89); 5765 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 5766 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 5767 N1 = DAG.getConstant(0x89, MVT::i32); 5768 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1); 5769 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 5770 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 5771 // Convert back to integer and return. 5772 // return vmovn_s32(vcvt_s32_f32(result)); 5773 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 5774 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 5775 return N0; 5776 } 5777 5778 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) { 5779 EVT VT = Op.getValueType(); 5780 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 5781 "unexpected type for custom-lowering ISD::SDIV"); 5782 5783 SDLoc dl(Op); 5784 SDValue N0 = Op.getOperand(0); 5785 SDValue N1 = Op.getOperand(1); 5786 SDValue N2, N3; 5787 5788 if (VT == MVT::v8i8) { 5789 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0); 5790 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1); 5791 5792 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 5793 DAG.getIntPtrConstant(4)); 5794 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 5795 DAG.getIntPtrConstant(4)); 5796 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 5797 DAG.getIntPtrConstant(0)); 5798 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 5799 DAG.getIntPtrConstant(0)); 5800 5801 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16 5802 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16 5803 5804 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 5805 N0 = LowerCONCAT_VECTORS(N0, DAG); 5806 5807 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0); 5808 return N0; 5809 } 5810 return LowerSDIV_v4i16(N0, N1, dl, DAG); 5811 } 5812 5813 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) { 5814 EVT VT = Op.getValueType(); 5815 assert((VT == MVT::v4i16 || VT == MVT::v8i8) && 5816 "unexpected type for custom-lowering ISD::UDIV"); 5817 5818 SDLoc dl(Op); 5819 SDValue N0 = Op.getOperand(0); 5820 SDValue N1 = Op.getOperand(1); 5821 SDValue N2, N3; 5822 5823 if (VT == MVT::v8i8) { 5824 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0); 5825 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1); 5826 5827 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 5828 DAG.getIntPtrConstant(4)); 5829 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 5830 DAG.getIntPtrConstant(4)); 5831 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0, 5832 DAG.getIntPtrConstant(0)); 5833 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1, 5834 DAG.getIntPtrConstant(0)); 5835 5836 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16 5837 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16 5838 5839 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2); 5840 N0 = LowerCONCAT_VECTORS(N0, DAG); 5841 5842 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8, 5843 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32), 5844 N0); 5845 return N0; 5846 } 5847 5848 // v4i16 sdiv ... Convert to float. 5849 // float4 yf = vcvt_f32_s32(vmovl_u16(y)); 5850 // float4 xf = vcvt_f32_s32(vmovl_u16(x)); 5851 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0); 5852 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1); 5853 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0); 5854 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1); 5855 5856 // Use reciprocal estimate and two refinement steps. 5857 // float4 recip = vrecpeq_f32(yf); 5858 // recip *= vrecpsq_f32(yf, recip); 5859 // recip *= vrecpsq_f32(yf, recip); 5860 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 5861 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1); 5862 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 5863 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32), 5864 BN1, N2); 5865 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 5866 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32, 5867 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32), 5868 BN1, N2); 5869 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2); 5870 // Simply multiplying by the reciprocal estimate can leave us a few ulps 5871 // too low, so we add 2 ulps (exhaustive testing shows that this is enough, 5872 // and that it will never cause us to return an answer too large). 5873 // float4 result = as_float4(as_int4(xf*recip) + 2); 5874 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2); 5875 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0); 5876 N1 = DAG.getConstant(2, MVT::i32); 5877 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1); 5878 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1); 5879 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0); 5880 // Convert back to integer and return. 5881 // return vmovn_u32(vcvt_s32_f32(result)); 5882 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0); 5883 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0); 5884 return N0; 5885 } 5886 5887 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 5888 EVT VT = Op.getNode()->getValueType(0); 5889 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 5890 5891 unsigned Opc; 5892 bool ExtraOp = false; 5893 switch (Op.getOpcode()) { 5894 default: llvm_unreachable("Invalid code"); 5895 case ISD::ADDC: Opc = ARMISD::ADDC; break; 5896 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break; 5897 case ISD::SUBC: Opc = ARMISD::SUBC; break; 5898 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break; 5899 } 5900 5901 if (!ExtraOp) 5902 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 5903 Op.getOperand(1)); 5904 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 5905 Op.getOperand(1), Op.getOperand(2)); 5906 } 5907 5908 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 5909 assert(Subtarget->isTargetDarwin()); 5910 5911 // For iOS, we want to call an alternative entry point: __sincos_stret, 5912 // return values are passed via sret. 5913 SDLoc dl(Op); 5914 SDValue Arg = Op.getOperand(0); 5915 EVT ArgVT = Arg.getValueType(); 5916 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 5917 5918 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); 5919 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5920 5921 // Pair of floats / doubles used to pass the result. 5922 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL); 5923 5924 // Create stack object for sret. 5925 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy); 5926 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy); 5927 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 5928 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy()); 5929 5930 ArgListTy Args; 5931 ArgListEntry Entry; 5932 5933 Entry.Node = SRet; 5934 Entry.Ty = RetTy->getPointerTo(); 5935 Entry.isSExt = false; 5936 Entry.isZExt = false; 5937 Entry.isSRet = true; 5938 Args.push_back(Entry); 5939 5940 Entry.Node = Arg; 5941 Entry.Ty = ArgTy; 5942 Entry.isSExt = false; 5943 Entry.isZExt = false; 5944 Args.push_back(Entry); 5945 5946 const char *LibcallName = (ArgVT == MVT::f64) 5947 ? "__sincos_stret" : "__sincosf_stret"; 5948 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy()); 5949 5950 TargetLowering:: 5951 CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()), 5952 false, false, false, false, 0, 5953 CallingConv::C, /*isTaillCall=*/false, 5954 /*doesNotRet=*/false, /*isReturnValueUsed*/false, 5955 Callee, Args, DAG, dl); 5956 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 5957 5958 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, 5959 MachinePointerInfo(), false, false, false, 0); 5960 5961 // Address of cos field. 5962 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet, 5963 DAG.getIntPtrConstant(ArgVT.getStoreSize())); 5964 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, 5965 MachinePointerInfo(), false, false, false, 0); 5966 5967 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 5968 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, 5969 LoadSin.getValue(0), LoadCos.getValue(0)); 5970 } 5971 5972 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) { 5973 // Monotonic load/store is legal for all targets 5974 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic) 5975 return Op; 5976 5977 // Acquire/Release load/store is not legal for targets without a 5978 // dmb or equivalent available. 5979 return SDValue(); 5980 } 5981 5982 static void ReplaceREADCYCLECOUNTER(SDNode *N, 5983 SmallVectorImpl<SDValue> &Results, 5984 SelectionDAG &DAG, 5985 const ARMSubtarget *Subtarget) { 5986 SDLoc DL(N); 5987 SDValue Cycles32, OutChain; 5988 5989 if (Subtarget->hasPerfMon()) { 5990 // Under Power Management extensions, the cycle-count is: 5991 // mrc p15, #0, <Rt>, c9, c13, #0 5992 SDValue Ops[] = { N->getOperand(0), // Chain 5993 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32), 5994 DAG.getConstant(15, MVT::i32), 5995 DAG.getConstant(0, MVT::i32), 5996 DAG.getConstant(9, MVT::i32), 5997 DAG.getConstant(13, MVT::i32), 5998 DAG.getConstant(0, MVT::i32) 5999 }; 6000 6001 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, 6002 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0], 6003 array_lengthof(Ops)); 6004 OutChain = Cycles32.getValue(1); 6005 } else { 6006 // Intrinsic is defined to return 0 on unsupported platforms. Technically 6007 // there are older ARM CPUs that have implementation-specific ways of 6008 // obtaining this information (FIXME!). 6009 Cycles32 = DAG.getConstant(0, MVT::i32); 6010 OutChain = DAG.getEntryNode(); 6011 } 6012 6013 6014 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, 6015 Cycles32, DAG.getConstant(0, MVT::i32)); 6016 Results.push_back(Cycles64); 6017 Results.push_back(OutChain); 6018 } 6019 6020 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 6021 switch (Op.getOpcode()) { 6022 default: llvm_unreachable("Don't know how to custom lower this!"); 6023 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 6024 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 6025 case ISD::GlobalAddress: 6026 return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) : 6027 LowerGlobalAddressELF(Op, DAG); 6028 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 6029 case ISD::SELECT: return LowerSELECT(Op, DAG); 6030 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 6031 case ISD::BR_CC: return LowerBR_CC(Op, DAG); 6032 case ISD::BR_JT: return LowerBR_JT(Op, DAG); 6033 case ISD::VASTART: return LowerVASTART(Op, DAG); 6034 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget); 6035 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget); 6036 case ISD::SINT_TO_FP: 6037 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 6038 case ISD::FP_TO_SINT: 6039 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); 6040 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 6041 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 6042 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 6043 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG); 6044 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG); 6045 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG); 6046 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG, 6047 Subtarget); 6048 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG); 6049 case ISD::SHL: 6050 case ISD::SRL: 6051 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget); 6052 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); 6053 case ISD::SRL_PARTS: 6054 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); 6055 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget); 6056 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget); 6057 case ISD::SETCC: return LowerVSETCC(Op, DAG); 6058 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget); 6059 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget); 6060 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 6061 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 6062 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 6063 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 6064 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 6065 case ISD::MUL: return LowerMUL(Op, DAG); 6066 case ISD::SDIV: return LowerSDIV(Op, DAG); 6067 case ISD::UDIV: return LowerUDIV(Op, DAG); 6068 case ISD::ADDC: 6069 case ISD::ADDE: 6070 case ISD::SUBC: 6071 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 6072 case ISD::ATOMIC_LOAD: 6073 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG); 6074 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 6075 case ISD::SDIVREM: 6076 case ISD::UDIVREM: return LowerDivRem(Op, DAG); 6077 } 6078 } 6079 6080 /// ReplaceNodeResults - Replace the results of node with an illegal result 6081 /// type with new values built out of custom code. 6082 void ARMTargetLowering::ReplaceNodeResults(SDNode *N, 6083 SmallVectorImpl<SDValue>&Results, 6084 SelectionDAG &DAG) const { 6085 SDValue Res; 6086 switch (N->getOpcode()) { 6087 default: 6088 llvm_unreachable("Don't know how to custom expand this!"); 6089 case ISD::BITCAST: 6090 Res = ExpandBITCAST(N, DAG); 6091 break; 6092 case ISD::SRL: 6093 case ISD::SRA: 6094 Res = Expand64BitShift(N, DAG, Subtarget); 6095 break; 6096 case ISD::READCYCLECOUNTER: 6097 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget); 6098 return; 6099 } 6100 if (Res.getNode()) 6101 Results.push_back(Res); 6102 } 6103 6104 //===----------------------------------------------------------------------===// 6105 // ARM Scheduler Hooks 6106 //===----------------------------------------------------------------------===// 6107 6108 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and 6109 /// registers the function context. 6110 void ARMTargetLowering:: 6111 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB, 6112 MachineBasicBlock *DispatchBB, int FI) const { 6113 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 6114 DebugLoc dl = MI->getDebugLoc(); 6115 MachineFunction *MF = MBB->getParent(); 6116 MachineRegisterInfo *MRI = &MF->getRegInfo(); 6117 MachineConstantPool *MCP = MF->getConstantPool(); 6118 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 6119 const Function *F = MF->getFunction(); 6120 6121 bool isThumb = Subtarget->isThumb(); 6122 bool isThumb2 = Subtarget->isThumb2(); 6123 6124 unsigned PCLabelId = AFI->createPICLabelUId(); 6125 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8; 6126 ARMConstantPoolValue *CPV = 6127 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj); 6128 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4); 6129 6130 const TargetRegisterClass *TRC = isThumb ? 6131 (const TargetRegisterClass*)&ARM::tGPRRegClass : 6132 (const TargetRegisterClass*)&ARM::GPRRegClass; 6133 6134 // Grab constant pool and fixed stack memory operands. 6135 MachineMemOperand *CPMMO = 6136 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(), 6137 MachineMemOperand::MOLoad, 4, 4); 6138 6139 MachineMemOperand *FIMMOSt = 6140 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI), 6141 MachineMemOperand::MOStore, 4, 4); 6142 6143 // Load the address of the dispatch MBB into the jump buffer. 6144 if (isThumb2) { 6145 // Incoming value: jbuf 6146 // ldr.n r5, LCPI1_1 6147 // orr r5, r5, #1 6148 // add r5, pc 6149 // str r5, [$jbuf, #+4] ; &jbuf[1] 6150 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6151 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1) 6152 .addConstantPoolIndex(CPI) 6153 .addMemOperand(CPMMO)); 6154 // Set the low bit because of thumb mode. 6155 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 6156 AddDefaultCC( 6157 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2) 6158 .addReg(NewVReg1, RegState::Kill) 6159 .addImm(0x01))); 6160 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 6161 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3) 6162 .addReg(NewVReg2, RegState::Kill) 6163 .addImm(PCLabelId); 6164 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12)) 6165 .addReg(NewVReg3, RegState::Kill) 6166 .addFrameIndex(FI) 6167 .addImm(36) // &jbuf[1] :: pc 6168 .addMemOperand(FIMMOSt)); 6169 } else if (isThumb) { 6170 // Incoming value: jbuf 6171 // ldr.n r1, LCPI1_4 6172 // add r1, pc 6173 // mov r2, #1 6174 // orrs r1, r2 6175 // add r2, $jbuf, #+4 ; &jbuf[1] 6176 // str r1, [r2] 6177 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6178 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1) 6179 .addConstantPoolIndex(CPI) 6180 .addMemOperand(CPMMO)); 6181 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 6182 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2) 6183 .addReg(NewVReg1, RegState::Kill) 6184 .addImm(PCLabelId); 6185 // Set the low bit because of thumb mode. 6186 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 6187 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3) 6188 .addReg(ARM::CPSR, RegState::Define) 6189 .addImm(1)); 6190 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 6191 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4) 6192 .addReg(ARM::CPSR, RegState::Define) 6193 .addReg(NewVReg2, RegState::Kill) 6194 .addReg(NewVReg3, RegState::Kill)); 6195 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 6196 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5) 6197 .addFrameIndex(FI) 6198 .addImm(36)); // &jbuf[1] :: pc 6199 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi)) 6200 .addReg(NewVReg4, RegState::Kill) 6201 .addReg(NewVReg5, RegState::Kill) 6202 .addImm(0) 6203 .addMemOperand(FIMMOSt)); 6204 } else { 6205 // Incoming value: jbuf 6206 // ldr r1, LCPI1_1 6207 // add r1, pc, r1 6208 // str r1, [$jbuf, #+4] ; &jbuf[1] 6209 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6210 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1) 6211 .addConstantPoolIndex(CPI) 6212 .addImm(0) 6213 .addMemOperand(CPMMO)); 6214 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 6215 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2) 6216 .addReg(NewVReg1, RegState::Kill) 6217 .addImm(PCLabelId)); 6218 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12)) 6219 .addReg(NewVReg2, RegState::Kill) 6220 .addFrameIndex(FI) 6221 .addImm(36) // &jbuf[1] :: pc 6222 .addMemOperand(FIMMOSt)); 6223 } 6224 } 6225 6226 MachineBasicBlock *ARMTargetLowering:: 6227 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const { 6228 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 6229 DebugLoc dl = MI->getDebugLoc(); 6230 MachineFunction *MF = MBB->getParent(); 6231 MachineRegisterInfo *MRI = &MF->getRegInfo(); 6232 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>(); 6233 MachineFrameInfo *MFI = MF->getFrameInfo(); 6234 int FI = MFI->getFunctionContextIndex(); 6235 6236 const TargetRegisterClass *TRC = Subtarget->isThumb() ? 6237 (const TargetRegisterClass*)&ARM::tGPRRegClass : 6238 (const TargetRegisterClass*)&ARM::GPRnopcRegClass; 6239 6240 // Get a mapping of the call site numbers to all of the landing pads they're 6241 // associated with. 6242 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad; 6243 unsigned MaxCSNum = 0; 6244 MachineModuleInfo &MMI = MF->getMMI(); 6245 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; 6246 ++BB) { 6247 if (!BB->isLandingPad()) continue; 6248 6249 // FIXME: We should assert that the EH_LABEL is the first MI in the landing 6250 // pad. 6251 for (MachineBasicBlock::iterator 6252 II = BB->begin(), IE = BB->end(); II != IE; ++II) { 6253 if (!II->isEHLabel()) continue; 6254 6255 MCSymbol *Sym = II->getOperand(0).getMCSymbol(); 6256 if (!MMI.hasCallSiteLandingPad(Sym)) continue; 6257 6258 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym); 6259 for (SmallVectorImpl<unsigned>::iterator 6260 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end(); 6261 CSI != CSE; ++CSI) { 6262 CallSiteNumToLPad[*CSI].push_back(BB); 6263 MaxCSNum = std::max(MaxCSNum, *CSI); 6264 } 6265 break; 6266 } 6267 } 6268 6269 // Get an ordered list of the machine basic blocks for the jump table. 6270 std::vector<MachineBasicBlock*> LPadList; 6271 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs; 6272 LPadList.reserve(CallSiteNumToLPad.size()); 6273 for (unsigned I = 1; I <= MaxCSNum; ++I) { 6274 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I]; 6275 for (SmallVectorImpl<MachineBasicBlock*>::iterator 6276 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) { 6277 LPadList.push_back(*II); 6278 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end()); 6279 } 6280 } 6281 6282 assert(!LPadList.empty() && 6283 "No landing pad destinations for the dispatch jump table!"); 6284 6285 // Create the jump table and associated information. 6286 MachineJumpTableInfo *JTI = 6287 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline); 6288 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 6289 unsigned UId = AFI->createJumpTableUId(); 6290 Reloc::Model RelocM = getTargetMachine().getRelocationModel(); 6291 6292 // Create the MBBs for the dispatch code. 6293 6294 // Shove the dispatch's address into the return slot in the function context. 6295 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 6296 DispatchBB->setIsLandingPad(); 6297 6298 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 6299 unsigned trap_opcode; 6300 if (Subtarget->isThumb()) 6301 trap_opcode = ARM::tTRAP; 6302 else 6303 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP; 6304 6305 BuildMI(TrapBB, dl, TII->get(trap_opcode)); 6306 DispatchBB->addSuccessor(TrapBB); 6307 6308 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 6309 DispatchBB->addSuccessor(DispContBB); 6310 6311 // Insert and MBBs. 6312 MF->insert(MF->end(), DispatchBB); 6313 MF->insert(MF->end(), DispContBB); 6314 MF->insert(MF->end(), TrapBB); 6315 6316 // Insert code into the entry block that creates and registers the function 6317 // context. 6318 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI); 6319 6320 MachineMemOperand *FIMMOLd = 6321 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI), 6322 MachineMemOperand::MOLoad | 6323 MachineMemOperand::MOVolatile, 4, 4); 6324 6325 MachineInstrBuilder MIB; 6326 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup)); 6327 6328 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII); 6329 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo(); 6330 6331 // Add a register mask with no preserved registers. This results in all 6332 // registers being marked as clobbered. 6333 MIB.addRegMask(RI.getNoPreservedMask()); 6334 6335 unsigned NumLPads = LPadList.size(); 6336 if (Subtarget->isThumb2()) { 6337 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6338 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1) 6339 .addFrameIndex(FI) 6340 .addImm(4) 6341 .addMemOperand(FIMMOLd)); 6342 6343 if (NumLPads < 256) { 6344 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri)) 6345 .addReg(NewVReg1) 6346 .addImm(LPadList.size())); 6347 } else { 6348 unsigned VReg1 = MRI->createVirtualRegister(TRC); 6349 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1) 6350 .addImm(NumLPads & 0xFFFF)); 6351 6352 unsigned VReg2 = VReg1; 6353 if ((NumLPads & 0xFFFF0000) != 0) { 6354 VReg2 = MRI->createVirtualRegister(TRC); 6355 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2) 6356 .addReg(VReg1) 6357 .addImm(NumLPads >> 16)); 6358 } 6359 6360 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr)) 6361 .addReg(NewVReg1) 6362 .addReg(VReg2)); 6363 } 6364 6365 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc)) 6366 .addMBB(TrapBB) 6367 .addImm(ARMCC::HI) 6368 .addReg(ARM::CPSR); 6369 6370 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 6371 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3) 6372 .addJumpTableIndex(MJTI) 6373 .addImm(UId)); 6374 6375 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 6376 AddDefaultCC( 6377 AddDefaultPred( 6378 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4) 6379 .addReg(NewVReg3, RegState::Kill) 6380 .addReg(NewVReg1) 6381 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 6382 6383 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT)) 6384 .addReg(NewVReg4, RegState::Kill) 6385 .addReg(NewVReg1) 6386 .addJumpTableIndex(MJTI) 6387 .addImm(UId); 6388 } else if (Subtarget->isThumb()) { 6389 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6390 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1) 6391 .addFrameIndex(FI) 6392 .addImm(1) 6393 .addMemOperand(FIMMOLd)); 6394 6395 if (NumLPads < 256) { 6396 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8)) 6397 .addReg(NewVReg1) 6398 .addImm(NumLPads)); 6399 } else { 6400 MachineConstantPool *ConstantPool = MF->getConstantPool(); 6401 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 6402 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 6403 6404 // MachineConstantPool wants an explicit alignment. 6405 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty); 6406 if (Align == 0) 6407 Align = getDataLayout()->getTypeAllocSize(C->getType()); 6408 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 6409 6410 unsigned VReg1 = MRI->createVirtualRegister(TRC); 6411 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci)) 6412 .addReg(VReg1, RegState::Define) 6413 .addConstantPoolIndex(Idx)); 6414 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr)) 6415 .addReg(NewVReg1) 6416 .addReg(VReg1)); 6417 } 6418 6419 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc)) 6420 .addMBB(TrapBB) 6421 .addImm(ARMCC::HI) 6422 .addReg(ARM::CPSR); 6423 6424 unsigned NewVReg2 = MRI->createVirtualRegister(TRC); 6425 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2) 6426 .addReg(ARM::CPSR, RegState::Define) 6427 .addReg(NewVReg1) 6428 .addImm(2)); 6429 6430 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 6431 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3) 6432 .addJumpTableIndex(MJTI) 6433 .addImm(UId)); 6434 6435 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 6436 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4) 6437 .addReg(ARM::CPSR, RegState::Define) 6438 .addReg(NewVReg2, RegState::Kill) 6439 .addReg(NewVReg3)); 6440 6441 MachineMemOperand *JTMMOLd = 6442 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(), 6443 MachineMemOperand::MOLoad, 4, 4); 6444 6445 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 6446 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5) 6447 .addReg(NewVReg4, RegState::Kill) 6448 .addImm(0) 6449 .addMemOperand(JTMMOLd)); 6450 6451 unsigned NewVReg6 = NewVReg5; 6452 if (RelocM == Reloc::PIC_) { 6453 NewVReg6 = MRI->createVirtualRegister(TRC); 6454 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6) 6455 .addReg(ARM::CPSR, RegState::Define) 6456 .addReg(NewVReg5, RegState::Kill) 6457 .addReg(NewVReg3)); 6458 } 6459 6460 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr)) 6461 .addReg(NewVReg6, RegState::Kill) 6462 .addJumpTableIndex(MJTI) 6463 .addImm(UId); 6464 } else { 6465 unsigned NewVReg1 = MRI->createVirtualRegister(TRC); 6466 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1) 6467 .addFrameIndex(FI) 6468 .addImm(4) 6469 .addMemOperand(FIMMOLd)); 6470 6471 if (NumLPads < 256) { 6472 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri)) 6473 .addReg(NewVReg1) 6474 .addImm(NumLPads)); 6475 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) { 6476 unsigned VReg1 = MRI->createVirtualRegister(TRC); 6477 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1) 6478 .addImm(NumLPads & 0xFFFF)); 6479 6480 unsigned VReg2 = VReg1; 6481 if ((NumLPads & 0xFFFF0000) != 0) { 6482 VReg2 = MRI->createVirtualRegister(TRC); 6483 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2) 6484 .addReg(VReg1) 6485 .addImm(NumLPads >> 16)); 6486 } 6487 6488 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 6489 .addReg(NewVReg1) 6490 .addReg(VReg2)); 6491 } else { 6492 MachineConstantPool *ConstantPool = MF->getConstantPool(); 6493 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 6494 const Constant *C = ConstantInt::get(Int32Ty, NumLPads); 6495 6496 // MachineConstantPool wants an explicit alignment. 6497 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty); 6498 if (Align == 0) 6499 Align = getDataLayout()->getTypeAllocSize(C->getType()); 6500 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 6501 6502 unsigned VReg1 = MRI->createVirtualRegister(TRC); 6503 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp)) 6504 .addReg(VReg1, RegState::Define) 6505 .addConstantPoolIndex(Idx) 6506 .addImm(0)); 6507 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr)) 6508 .addReg(NewVReg1) 6509 .addReg(VReg1, RegState::Kill)); 6510 } 6511 6512 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc)) 6513 .addMBB(TrapBB) 6514 .addImm(ARMCC::HI) 6515 .addReg(ARM::CPSR); 6516 6517 unsigned NewVReg3 = MRI->createVirtualRegister(TRC); 6518 AddDefaultCC( 6519 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3) 6520 .addReg(NewVReg1) 6521 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2)))); 6522 unsigned NewVReg4 = MRI->createVirtualRegister(TRC); 6523 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4) 6524 .addJumpTableIndex(MJTI) 6525 .addImm(UId)); 6526 6527 MachineMemOperand *JTMMOLd = 6528 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(), 6529 MachineMemOperand::MOLoad, 4, 4); 6530 unsigned NewVReg5 = MRI->createVirtualRegister(TRC); 6531 AddDefaultPred( 6532 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5) 6533 .addReg(NewVReg3, RegState::Kill) 6534 .addReg(NewVReg4) 6535 .addImm(0) 6536 .addMemOperand(JTMMOLd)); 6537 6538 if (RelocM == Reloc::PIC_) { 6539 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd)) 6540 .addReg(NewVReg5, RegState::Kill) 6541 .addReg(NewVReg4) 6542 .addJumpTableIndex(MJTI) 6543 .addImm(UId); 6544 } else { 6545 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr)) 6546 .addReg(NewVReg5, RegState::Kill) 6547 .addJumpTableIndex(MJTI) 6548 .addImm(UId); 6549 } 6550 } 6551 6552 // Add the jump table entries as successors to the MBB. 6553 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs; 6554 for (std::vector<MachineBasicBlock*>::iterator 6555 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) { 6556 MachineBasicBlock *CurMBB = *I; 6557 if (SeenMBBs.insert(CurMBB)) 6558 DispContBB->addSuccessor(CurMBB); 6559 } 6560 6561 // N.B. the order the invoke BBs are processed in doesn't matter here. 6562 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF); 6563 SmallVector<MachineBasicBlock*, 64> MBBLPads; 6564 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator 6565 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) { 6566 MachineBasicBlock *BB = *I; 6567 6568 // Remove the landing pad successor from the invoke block and replace it 6569 // with the new dispatch block. 6570 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(), 6571 BB->succ_end()); 6572 while (!Successors.empty()) { 6573 MachineBasicBlock *SMBB = Successors.pop_back_val(); 6574 if (SMBB->isLandingPad()) { 6575 BB->removeSuccessor(SMBB); 6576 MBBLPads.push_back(SMBB); 6577 } 6578 } 6579 6580 BB->addSuccessor(DispatchBB); 6581 6582 // Find the invoke call and mark all of the callee-saved registers as 6583 // 'implicit defined' so that they're spilled. This prevents code from 6584 // moving instructions to before the EH block, where they will never be 6585 // executed. 6586 for (MachineBasicBlock::reverse_iterator 6587 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) { 6588 if (!II->isCall()) continue; 6589 6590 DenseMap<unsigned, bool> DefRegs; 6591 for (MachineInstr::mop_iterator 6592 OI = II->operands_begin(), OE = II->operands_end(); 6593 OI != OE; ++OI) { 6594 if (!OI->isReg()) continue; 6595 DefRegs[OI->getReg()] = true; 6596 } 6597 6598 MachineInstrBuilder MIB(*MF, &*II); 6599 6600 for (unsigned i = 0; SavedRegs[i] != 0; ++i) { 6601 unsigned Reg = SavedRegs[i]; 6602 if (Subtarget->isThumb2() && 6603 !ARM::tGPRRegClass.contains(Reg) && 6604 !ARM::hGPRRegClass.contains(Reg)) 6605 continue; 6606 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg)) 6607 continue; 6608 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg)) 6609 continue; 6610 if (!DefRegs[Reg]) 6611 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 6612 } 6613 6614 break; 6615 } 6616 } 6617 6618 // Mark all former landing pads as non-landing pads. The dispatch is the only 6619 // landing pad now. 6620 for (SmallVectorImpl<MachineBasicBlock*>::iterator 6621 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I) 6622 (*I)->setIsLandingPad(false); 6623 6624 // The instruction is gone now. 6625 MI->eraseFromParent(); 6626 6627 return MBB; 6628 } 6629 6630 static 6631 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) { 6632 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(), 6633 E = MBB->succ_end(); I != E; ++I) 6634 if (*I != Succ) 6635 return *I; 6636 llvm_unreachable("Expecting a BB with two successors!"); 6637 } 6638 6639 /// Return the load opcode for a given load size. If load size >= 8, 6640 /// neon opcode will be returned. 6641 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) { 6642 if (LdSize >= 8) 6643 return LdSize == 16 ? ARM::VLD1q32wb_fixed 6644 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0; 6645 if (IsThumb1) 6646 return LdSize == 4 ? ARM::tLDRi 6647 : LdSize == 2 ? ARM::tLDRHi 6648 : LdSize == 1 ? ARM::tLDRBi : 0; 6649 if (IsThumb2) 6650 return LdSize == 4 ? ARM::t2LDR_POST 6651 : LdSize == 2 ? ARM::t2LDRH_POST 6652 : LdSize == 1 ? ARM::t2LDRB_POST : 0; 6653 return LdSize == 4 ? ARM::LDR_POST_IMM 6654 : LdSize == 2 ? ARM::LDRH_POST 6655 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0; 6656 } 6657 6658 /// Return the store opcode for a given store size. If store size >= 8, 6659 /// neon opcode will be returned. 6660 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) { 6661 if (StSize >= 8) 6662 return StSize == 16 ? ARM::VST1q32wb_fixed 6663 : StSize == 8 ? ARM::VST1d32wb_fixed : 0; 6664 if (IsThumb1) 6665 return StSize == 4 ? ARM::tSTRi 6666 : StSize == 2 ? ARM::tSTRHi 6667 : StSize == 1 ? ARM::tSTRBi : 0; 6668 if (IsThumb2) 6669 return StSize == 4 ? ARM::t2STR_POST 6670 : StSize == 2 ? ARM::t2STRH_POST 6671 : StSize == 1 ? ARM::t2STRB_POST : 0; 6672 return StSize == 4 ? ARM::STR_POST_IMM 6673 : StSize == 2 ? ARM::STRH_POST 6674 : StSize == 1 ? ARM::STRB_POST_IMM : 0; 6675 } 6676 6677 /// Emit a post-increment load operation with given size. The instructions 6678 /// will be added to BB at Pos. 6679 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos, 6680 const TargetInstrInfo *TII, DebugLoc dl, 6681 unsigned LdSize, unsigned Data, unsigned AddrIn, 6682 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 6683 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2); 6684 assert(LdOpc != 0 && "Should have a load opcode"); 6685 if (LdSize >= 8) { 6686 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 6687 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 6688 .addImm(0)); 6689 } else if (IsThumb1) { 6690 // load + update AddrIn 6691 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 6692 .addReg(AddrIn).addImm(0)); 6693 MachineInstrBuilder MIB = 6694 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 6695 MIB = AddDefaultT1CC(MIB); 6696 MIB.addReg(AddrIn).addImm(LdSize); 6697 AddDefaultPred(MIB); 6698 } else if (IsThumb2) { 6699 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 6700 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 6701 .addImm(LdSize)); 6702 } else { // arm 6703 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data) 6704 .addReg(AddrOut, RegState::Define).addReg(AddrIn) 6705 .addReg(0).addImm(LdSize)); 6706 } 6707 } 6708 6709 /// Emit a post-increment store operation with given size. The instructions 6710 /// will be added to BB at Pos. 6711 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos, 6712 const TargetInstrInfo *TII, DebugLoc dl, 6713 unsigned StSize, unsigned Data, unsigned AddrIn, 6714 unsigned AddrOut, bool IsThumb1, bool IsThumb2) { 6715 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2); 6716 assert(StOpc != 0 && "Should have a store opcode"); 6717 if (StSize >= 8) { 6718 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 6719 .addReg(AddrIn).addImm(0).addReg(Data)); 6720 } else if (IsThumb1) { 6721 // store + update AddrIn 6722 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data) 6723 .addReg(AddrIn).addImm(0)); 6724 MachineInstrBuilder MIB = 6725 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut); 6726 MIB = AddDefaultT1CC(MIB); 6727 MIB.addReg(AddrIn).addImm(StSize); 6728 AddDefaultPred(MIB); 6729 } else if (IsThumb2) { 6730 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 6731 .addReg(Data).addReg(AddrIn).addImm(StSize)); 6732 } else { // arm 6733 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut) 6734 .addReg(Data).addReg(AddrIn).addReg(0) 6735 .addImm(StSize)); 6736 } 6737 } 6738 6739 MachineBasicBlock * 6740 ARMTargetLowering::EmitStructByval(MachineInstr *MI, 6741 MachineBasicBlock *BB) const { 6742 // This pseudo instruction has 3 operands: dst, src, size 6743 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold(). 6744 // Otherwise, we will generate unrolled scalar copies. 6745 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 6746 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 6747 MachineFunction::iterator It = BB; 6748 ++It; 6749 6750 unsigned dest = MI->getOperand(0).getReg(); 6751 unsigned src = MI->getOperand(1).getReg(); 6752 unsigned SizeVal = MI->getOperand(2).getImm(); 6753 unsigned Align = MI->getOperand(3).getImm(); 6754 DebugLoc dl = MI->getDebugLoc(); 6755 6756 MachineFunction *MF = BB->getParent(); 6757 MachineRegisterInfo &MRI = MF->getRegInfo(); 6758 unsigned UnitSize = 0; 6759 const TargetRegisterClass *TRC = 0; 6760 const TargetRegisterClass *VecTRC = 0; 6761 6762 bool IsThumb1 = Subtarget->isThumb1Only(); 6763 bool IsThumb2 = Subtarget->isThumb2(); 6764 6765 if (Align & 1) { 6766 UnitSize = 1; 6767 } else if (Align & 2) { 6768 UnitSize = 2; 6769 } else { 6770 // Check whether we can use NEON instructions. 6771 if (!MF->getFunction()->getAttributes(). 6772 hasAttribute(AttributeSet::FunctionIndex, 6773 Attribute::NoImplicitFloat) && 6774 Subtarget->hasNEON()) { 6775 if ((Align % 16 == 0) && SizeVal >= 16) 6776 UnitSize = 16; 6777 else if ((Align % 8 == 0) && SizeVal >= 8) 6778 UnitSize = 8; 6779 } 6780 // Can't use NEON instructions. 6781 if (UnitSize == 0) 6782 UnitSize = 4; 6783 } 6784 6785 // Select the correct opcode and register class for unit size load/store 6786 bool IsNeon = UnitSize >= 8; 6787 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass 6788 : (const TargetRegisterClass *)&ARM::GPRRegClass; 6789 if (IsNeon) 6790 VecTRC = UnitSize == 16 6791 ? (const TargetRegisterClass *)&ARM::DPairRegClass 6792 : UnitSize == 8 6793 ? (const TargetRegisterClass *)&ARM::DPRRegClass 6794 : 0; 6795 6796 unsigned BytesLeft = SizeVal % UnitSize; 6797 unsigned LoopSize = SizeVal - BytesLeft; 6798 6799 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) { 6800 // Use LDR and STR to copy. 6801 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize) 6802 // [destOut] = STR_POST(scratch, destIn, UnitSize) 6803 unsigned srcIn = src; 6804 unsigned destIn = dest; 6805 for (unsigned i = 0; i < LoopSize; i+=UnitSize) { 6806 unsigned srcOut = MRI.createVirtualRegister(TRC); 6807 unsigned destOut = MRI.createVirtualRegister(TRC); 6808 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 6809 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut, 6810 IsThumb1, IsThumb2); 6811 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut, 6812 IsThumb1, IsThumb2); 6813 srcIn = srcOut; 6814 destIn = destOut; 6815 } 6816 6817 // Handle the leftover bytes with LDRB and STRB. 6818 // [scratch, srcOut] = LDRB_POST(srcIn, 1) 6819 // [destOut] = STRB_POST(scratch, destIn, 1) 6820 for (unsigned i = 0; i < BytesLeft; i++) { 6821 unsigned srcOut = MRI.createVirtualRegister(TRC); 6822 unsigned destOut = MRI.createVirtualRegister(TRC); 6823 unsigned scratch = MRI.createVirtualRegister(TRC); 6824 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut, 6825 IsThumb1, IsThumb2); 6826 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut, 6827 IsThumb1, IsThumb2); 6828 srcIn = srcOut; 6829 destIn = destOut; 6830 } 6831 MI->eraseFromParent(); // The instruction is gone now. 6832 return BB; 6833 } 6834 6835 // Expand the pseudo op to a loop. 6836 // thisMBB: 6837 // ... 6838 // movw varEnd, # --> with thumb2 6839 // movt varEnd, # 6840 // ldrcp varEnd, idx --> without thumb2 6841 // fallthrough --> loopMBB 6842 // loopMBB: 6843 // PHI varPhi, varEnd, varLoop 6844 // PHI srcPhi, src, srcLoop 6845 // PHI destPhi, dst, destLoop 6846 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 6847 // [destLoop] = STR_POST(scratch, destPhi, UnitSize) 6848 // subs varLoop, varPhi, #UnitSize 6849 // bne loopMBB 6850 // fallthrough --> exitMBB 6851 // exitMBB: 6852 // epilogue to handle left-over bytes 6853 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 6854 // [destOut] = STRB_POST(scratch, destLoop, 1) 6855 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB); 6856 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB); 6857 MF->insert(It, loopMBB); 6858 MF->insert(It, exitMBB); 6859 6860 // Transfer the remainder of BB and its successor edges to exitMBB. 6861 exitMBB->splice(exitMBB->begin(), BB, 6862 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 6863 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 6864 6865 // Load an immediate to varEnd. 6866 unsigned varEnd = MRI.createVirtualRegister(TRC); 6867 if (IsThumb2) { 6868 unsigned Vtmp = varEnd; 6869 if ((LoopSize & 0xFFFF0000) != 0) 6870 Vtmp = MRI.createVirtualRegister(TRC); 6871 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp) 6872 .addImm(LoopSize & 0xFFFF)); 6873 6874 if ((LoopSize & 0xFFFF0000) != 0) 6875 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd) 6876 .addReg(Vtmp).addImm(LoopSize >> 16)); 6877 } else { 6878 MachineConstantPool *ConstantPool = MF->getConstantPool(); 6879 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext()); 6880 const Constant *C = ConstantInt::get(Int32Ty, LoopSize); 6881 6882 // MachineConstantPool wants an explicit alignment. 6883 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty); 6884 if (Align == 0) 6885 Align = getDataLayout()->getTypeAllocSize(C->getType()); 6886 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align); 6887 6888 if (IsThumb1) 6889 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg( 6890 varEnd, RegState::Define).addConstantPoolIndex(Idx)); 6891 else 6892 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg( 6893 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0)); 6894 } 6895 BB->addSuccessor(loopMBB); 6896 6897 // Generate the loop body: 6898 // varPhi = PHI(varLoop, varEnd) 6899 // srcPhi = PHI(srcLoop, src) 6900 // destPhi = PHI(destLoop, dst) 6901 MachineBasicBlock *entryBB = BB; 6902 BB = loopMBB; 6903 unsigned varLoop = MRI.createVirtualRegister(TRC); 6904 unsigned varPhi = MRI.createVirtualRegister(TRC); 6905 unsigned srcLoop = MRI.createVirtualRegister(TRC); 6906 unsigned srcPhi = MRI.createVirtualRegister(TRC); 6907 unsigned destLoop = MRI.createVirtualRegister(TRC); 6908 unsigned destPhi = MRI.createVirtualRegister(TRC); 6909 6910 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi) 6911 .addReg(varLoop).addMBB(loopMBB) 6912 .addReg(varEnd).addMBB(entryBB); 6913 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi) 6914 .addReg(srcLoop).addMBB(loopMBB) 6915 .addReg(src).addMBB(entryBB); 6916 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi) 6917 .addReg(destLoop).addMBB(loopMBB) 6918 .addReg(dest).addMBB(entryBB); 6919 6920 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize) 6921 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz) 6922 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC); 6923 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop, 6924 IsThumb1, IsThumb2); 6925 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop, 6926 IsThumb1, IsThumb2); 6927 6928 // Decrement loop variable by UnitSize. 6929 if (IsThumb1) { 6930 MachineInstrBuilder MIB = 6931 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop); 6932 MIB = AddDefaultT1CC(MIB); 6933 MIB.addReg(varPhi).addImm(UnitSize); 6934 AddDefaultPred(MIB); 6935 } else { 6936 MachineInstrBuilder MIB = 6937 BuildMI(*BB, BB->end(), dl, 6938 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop); 6939 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize))); 6940 MIB->getOperand(5).setReg(ARM::CPSR); 6941 MIB->getOperand(5).setIsDef(true); 6942 } 6943 BuildMI(*BB, BB->end(), dl, 6944 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc)) 6945 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR); 6946 6947 // loopMBB can loop back to loopMBB or fall through to exitMBB. 6948 BB->addSuccessor(loopMBB); 6949 BB->addSuccessor(exitMBB); 6950 6951 // Add epilogue to handle BytesLeft. 6952 BB = exitMBB; 6953 MachineInstr *StartOfExit = exitMBB->begin(); 6954 6955 // [scratch, srcOut] = LDRB_POST(srcLoop, 1) 6956 // [destOut] = STRB_POST(scratch, destLoop, 1) 6957 unsigned srcIn = srcLoop; 6958 unsigned destIn = destLoop; 6959 for (unsigned i = 0; i < BytesLeft; i++) { 6960 unsigned srcOut = MRI.createVirtualRegister(TRC); 6961 unsigned destOut = MRI.createVirtualRegister(TRC); 6962 unsigned scratch = MRI.createVirtualRegister(TRC); 6963 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut, 6964 IsThumb1, IsThumb2); 6965 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut, 6966 IsThumb1, IsThumb2); 6967 srcIn = srcOut; 6968 destIn = destOut; 6969 } 6970 6971 MI->eraseFromParent(); // The instruction is gone now. 6972 return BB; 6973 } 6974 6975 MachineBasicBlock * 6976 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 6977 MachineBasicBlock *BB) const { 6978 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 6979 DebugLoc dl = MI->getDebugLoc(); 6980 bool isThumb2 = Subtarget->isThumb2(); 6981 switch (MI->getOpcode()) { 6982 default: { 6983 MI->dump(); 6984 llvm_unreachable("Unexpected instr type to insert"); 6985 } 6986 // The Thumb2 pre-indexed stores have the same MI operands, they just 6987 // define them differently in the .td files from the isel patterns, so 6988 // they need pseudos. 6989 case ARM::t2STR_preidx: 6990 MI->setDesc(TII->get(ARM::t2STR_PRE)); 6991 return BB; 6992 case ARM::t2STRB_preidx: 6993 MI->setDesc(TII->get(ARM::t2STRB_PRE)); 6994 return BB; 6995 case ARM::t2STRH_preidx: 6996 MI->setDesc(TII->get(ARM::t2STRH_PRE)); 6997 return BB; 6998 6999 case ARM::STRi_preidx: 7000 case ARM::STRBi_preidx: { 7001 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ? 7002 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM; 7003 // Decode the offset. 7004 unsigned Offset = MI->getOperand(4).getImm(); 7005 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub; 7006 Offset = ARM_AM::getAM2Offset(Offset); 7007 if (isSub) 7008 Offset = -Offset; 7009 7010 MachineMemOperand *MMO = *MI->memoperands_begin(); 7011 BuildMI(*BB, MI, dl, TII->get(NewOpc)) 7012 .addOperand(MI->getOperand(0)) // Rn_wb 7013 .addOperand(MI->getOperand(1)) // Rt 7014 .addOperand(MI->getOperand(2)) // Rn 7015 .addImm(Offset) // offset (skip GPR==zero_reg) 7016 .addOperand(MI->getOperand(5)) // pred 7017 .addOperand(MI->getOperand(6)) 7018 .addMemOperand(MMO); 7019 MI->eraseFromParent(); 7020 return BB; 7021 } 7022 case ARM::STRr_preidx: 7023 case ARM::STRBr_preidx: 7024 case ARM::STRH_preidx: { 7025 unsigned NewOpc; 7026 switch (MI->getOpcode()) { 7027 default: llvm_unreachable("unexpected opcode!"); 7028 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break; 7029 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break; 7030 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break; 7031 } 7032 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc)); 7033 for (unsigned i = 0; i < MI->getNumOperands(); ++i) 7034 MIB.addOperand(MI->getOperand(i)); 7035 MI->eraseFromParent(); 7036 return BB; 7037 } 7038 7039 case ARM::tMOVCCr_pseudo: { 7040 // To "insert" a SELECT_CC instruction, we actually have to insert the 7041 // diamond control-flow pattern. The incoming instruction knows the 7042 // destination vreg to set, the condition code register to branch on, the 7043 // true/false values to select between, and a branch opcode to use. 7044 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7045 MachineFunction::iterator It = BB; 7046 ++It; 7047 7048 // thisMBB: 7049 // ... 7050 // TrueVal = ... 7051 // cmpTY ccX, r1, r2 7052 // bCC copy1MBB 7053 // fallthrough --> copy0MBB 7054 MachineBasicBlock *thisMBB = BB; 7055 MachineFunction *F = BB->getParent(); 7056 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 7057 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 7058 F->insert(It, copy0MBB); 7059 F->insert(It, sinkMBB); 7060 7061 // Transfer the remainder of BB and its successor edges to sinkMBB. 7062 sinkMBB->splice(sinkMBB->begin(), BB, 7063 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7064 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 7065 7066 BB->addSuccessor(copy0MBB); 7067 BB->addSuccessor(sinkMBB); 7068 7069 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB) 7070 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg()); 7071 7072 // copy0MBB: 7073 // %FalseValue = ... 7074 // # fallthrough to sinkMBB 7075 BB = copy0MBB; 7076 7077 // Update machine-CFG edges 7078 BB->addSuccessor(sinkMBB); 7079 7080 // sinkMBB: 7081 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 7082 // ... 7083 BB = sinkMBB; 7084 BuildMI(*BB, BB->begin(), dl, 7085 TII->get(ARM::PHI), MI->getOperand(0).getReg()) 7086 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 7087 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 7088 7089 MI->eraseFromParent(); // The pseudo instruction is gone now. 7090 return BB; 7091 } 7092 7093 case ARM::BCCi64: 7094 case ARM::BCCZi64: { 7095 // If there is an unconditional branch to the other successor, remove it. 7096 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7097 7098 // Compare both parts that make up the double comparison separately for 7099 // equality. 7100 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64; 7101 7102 unsigned LHS1 = MI->getOperand(1).getReg(); 7103 unsigned LHS2 = MI->getOperand(2).getReg(); 7104 if (RHSisZero) { 7105 AddDefaultPred(BuildMI(BB, dl, 7106 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 7107 .addReg(LHS1).addImm(0)); 7108 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 7109 .addReg(LHS2).addImm(0) 7110 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 7111 } else { 7112 unsigned RHS1 = MI->getOperand(3).getReg(); 7113 unsigned RHS2 = MI->getOperand(4).getReg(); 7114 AddDefaultPred(BuildMI(BB, dl, 7115 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 7116 .addReg(LHS1).addReg(RHS1)); 7117 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr)) 7118 .addReg(LHS2).addReg(RHS2) 7119 .addImm(ARMCC::EQ).addReg(ARM::CPSR); 7120 } 7121 7122 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB(); 7123 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB); 7124 if (MI->getOperand(0).getImm() == ARMCC::NE) 7125 std::swap(destMBB, exitMBB); 7126 7127 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)) 7128 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR); 7129 if (isThumb2) 7130 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB)); 7131 else 7132 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB); 7133 7134 MI->eraseFromParent(); // The pseudo instruction is gone now. 7135 return BB; 7136 } 7137 7138 case ARM::Int_eh_sjlj_setjmp: 7139 case ARM::Int_eh_sjlj_setjmp_nofp: 7140 case ARM::tInt_eh_sjlj_setjmp: 7141 case ARM::t2Int_eh_sjlj_setjmp: 7142 case ARM::t2Int_eh_sjlj_setjmp_nofp: 7143 EmitSjLjDispatchBlock(MI, BB); 7144 return BB; 7145 7146 case ARM::ABS: 7147 case ARM::t2ABS: { 7148 // To insert an ABS instruction, we have to insert the 7149 // diamond control-flow pattern. The incoming instruction knows the 7150 // source vreg to test against 0, the destination vreg to set, 7151 // the condition code register to branch on, the 7152 // true/false values to select between, and a branch opcode to use. 7153 // It transforms 7154 // V1 = ABS V0 7155 // into 7156 // V2 = MOVS V0 7157 // BCC (branch to SinkBB if V0 >= 0) 7158 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0) 7159 // SinkBB: V1 = PHI(V2, V3) 7160 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 7161 MachineFunction::iterator BBI = BB; 7162 ++BBI; 7163 MachineFunction *Fn = BB->getParent(); 7164 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB); 7165 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB); 7166 Fn->insert(BBI, RSBBB); 7167 Fn->insert(BBI, SinkBB); 7168 7169 unsigned int ABSSrcReg = MI->getOperand(1).getReg(); 7170 unsigned int ABSDstReg = MI->getOperand(0).getReg(); 7171 bool isThumb2 = Subtarget->isThumb2(); 7172 MachineRegisterInfo &MRI = Fn->getRegInfo(); 7173 // In Thumb mode S must not be specified if source register is the SP or 7174 // PC and if destination register is the SP, so restrict register class 7175 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ? 7176 (const TargetRegisterClass*)&ARM::rGPRRegClass : 7177 (const TargetRegisterClass*)&ARM::GPRRegClass); 7178 7179 // Transfer the remainder of BB and its successor edges to sinkMBB. 7180 SinkBB->splice(SinkBB->begin(), BB, 7181 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 7182 SinkBB->transferSuccessorsAndUpdatePHIs(BB); 7183 7184 BB->addSuccessor(RSBBB); 7185 BB->addSuccessor(SinkBB); 7186 7187 // fall through to SinkMBB 7188 RSBBB->addSuccessor(SinkBB); 7189 7190 // insert a cmp at the end of BB 7191 AddDefaultPred(BuildMI(BB, dl, 7192 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri)) 7193 .addReg(ABSSrcReg).addImm(0)); 7194 7195 // insert a bcc with opposite CC to ARMCC::MI at the end of BB 7196 BuildMI(BB, dl, 7197 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB) 7198 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR); 7199 7200 // insert rsbri in RSBBB 7201 // Note: BCC and rsbri will be converted into predicated rsbmi 7202 // by if-conversion pass 7203 BuildMI(*RSBBB, RSBBB->begin(), dl, 7204 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg) 7205 .addReg(ABSSrcReg, RegState::Kill) 7206 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0); 7207 7208 // insert PHI in SinkBB, 7209 // reuse ABSDstReg to not change uses of ABS instruction 7210 BuildMI(*SinkBB, SinkBB->begin(), dl, 7211 TII->get(ARM::PHI), ABSDstReg) 7212 .addReg(NewRsbDstReg).addMBB(RSBBB) 7213 .addReg(ABSSrcReg).addMBB(BB); 7214 7215 // remove ABS instruction 7216 MI->eraseFromParent(); 7217 7218 // return last added BB 7219 return SinkBB; 7220 } 7221 case ARM::COPY_STRUCT_BYVAL_I32: 7222 ++NumLoopByVals; 7223 return EmitStructByval(MI, BB); 7224 } 7225 } 7226 7227 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI, 7228 SDNode *Node) const { 7229 if (!MI->hasPostISelHook()) { 7230 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) && 7231 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'"); 7232 return; 7233 } 7234 7235 const MCInstrDesc *MCID = &MI->getDesc(); 7236 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB, 7237 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional 7238 // operand is still set to noreg. If needed, set the optional operand's 7239 // register to CPSR, and remove the redundant implicit def. 7240 // 7241 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>). 7242 7243 // Rename pseudo opcodes. 7244 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode()); 7245 if (NewOpc) { 7246 const ARMBaseInstrInfo *TII = 7247 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo()); 7248 MCID = &TII->get(NewOpc); 7249 7250 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 && 7251 "converted opcode should be the same except for cc_out"); 7252 7253 MI->setDesc(*MCID); 7254 7255 // Add the optional cc_out operand 7256 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true)); 7257 } 7258 unsigned ccOutIdx = MCID->getNumOperands() - 1; 7259 7260 // Any ARM instruction that sets the 's' bit should specify an optional 7261 // "cc_out" operand in the last operand position. 7262 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) { 7263 assert(!NewOpc && "Optional cc_out operand required"); 7264 return; 7265 } 7266 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it 7267 // since we already have an optional CPSR def. 7268 bool definesCPSR = false; 7269 bool deadCPSR = false; 7270 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands(); 7271 i != e; ++i) { 7272 const MachineOperand &MO = MI->getOperand(i); 7273 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) { 7274 definesCPSR = true; 7275 if (MO.isDead()) 7276 deadCPSR = true; 7277 MI->RemoveOperand(i); 7278 break; 7279 } 7280 } 7281 if (!definesCPSR) { 7282 assert(!NewOpc && "Optional cc_out operand required"); 7283 return; 7284 } 7285 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag"); 7286 if (deadCPSR) { 7287 assert(!MI->getOperand(ccOutIdx).getReg() && 7288 "expect uninitialized optional cc_out operand"); 7289 return; 7290 } 7291 7292 // If this instruction was defined with an optional CPSR def and its dag node 7293 // had a live implicit CPSR def, then activate the optional CPSR def. 7294 MachineOperand &MO = MI->getOperand(ccOutIdx); 7295 MO.setReg(ARM::CPSR); 7296 MO.setIsDef(true); 7297 } 7298 7299 //===----------------------------------------------------------------------===// 7300 // ARM Optimization Hooks 7301 //===----------------------------------------------------------------------===// 7302 7303 // Helper function that checks if N is a null or all ones constant. 7304 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) { 7305 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N); 7306 if (!C) 7307 return false; 7308 return AllOnes ? C->isAllOnesValue() : C->isNullValue(); 7309 } 7310 7311 // Return true if N is conditionally 0 or all ones. 7312 // Detects these expressions where cc is an i1 value: 7313 // 7314 // (select cc 0, y) [AllOnes=0] 7315 // (select cc y, 0) [AllOnes=0] 7316 // (zext cc) [AllOnes=0] 7317 // (sext cc) [AllOnes=0/1] 7318 // (select cc -1, y) [AllOnes=1] 7319 // (select cc y, -1) [AllOnes=1] 7320 // 7321 // Invert is set when N is the null/all ones constant when CC is false. 7322 // OtherOp is set to the alternative value of N. 7323 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, 7324 SDValue &CC, bool &Invert, 7325 SDValue &OtherOp, 7326 SelectionDAG &DAG) { 7327 switch (N->getOpcode()) { 7328 default: return false; 7329 case ISD::SELECT: { 7330 CC = N->getOperand(0); 7331 SDValue N1 = N->getOperand(1); 7332 SDValue N2 = N->getOperand(2); 7333 if (isZeroOrAllOnes(N1, AllOnes)) { 7334 Invert = false; 7335 OtherOp = N2; 7336 return true; 7337 } 7338 if (isZeroOrAllOnes(N2, AllOnes)) { 7339 Invert = true; 7340 OtherOp = N1; 7341 return true; 7342 } 7343 return false; 7344 } 7345 case ISD::ZERO_EXTEND: 7346 // (zext cc) can never be the all ones value. 7347 if (AllOnes) 7348 return false; 7349 // Fall through. 7350 case ISD::SIGN_EXTEND: { 7351 EVT VT = N->getValueType(0); 7352 CC = N->getOperand(0); 7353 if (CC.getValueType() != MVT::i1) 7354 return false; 7355 Invert = !AllOnes; 7356 if (AllOnes) 7357 // When looking for an AllOnes constant, N is an sext, and the 'other' 7358 // value is 0. 7359 OtherOp = DAG.getConstant(0, VT); 7360 else if (N->getOpcode() == ISD::ZERO_EXTEND) 7361 // When looking for a 0 constant, N can be zext or sext. 7362 OtherOp = DAG.getConstant(1, VT); 7363 else 7364 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT); 7365 return true; 7366 } 7367 } 7368 } 7369 7370 // Combine a constant select operand into its use: 7371 // 7372 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 7373 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 7374 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1] 7375 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 7376 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 7377 // 7378 // The transform is rejected if the select doesn't have a constant operand that 7379 // is null, or all ones when AllOnes is set. 7380 // 7381 // Also recognize sext/zext from i1: 7382 // 7383 // (add (zext cc), x) -> (select cc (add x, 1), x) 7384 // (add (sext cc), x) -> (select cc (add x, -1), x) 7385 // 7386 // These transformations eventually create predicated instructions. 7387 // 7388 // @param N The node to transform. 7389 // @param Slct The N operand that is a select. 7390 // @param OtherOp The other N operand (x above). 7391 // @param DCI Context. 7392 // @param AllOnes Require the select constant to be all ones instead of null. 7393 // @returns The new node, or SDValue() on failure. 7394 static 7395 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7396 TargetLowering::DAGCombinerInfo &DCI, 7397 bool AllOnes = false) { 7398 SelectionDAG &DAG = DCI.DAG; 7399 EVT VT = N->getValueType(0); 7400 SDValue NonConstantVal; 7401 SDValue CCOp; 7402 bool SwapSelectOps; 7403 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps, 7404 NonConstantVal, DAG)) 7405 return SDValue(); 7406 7407 // Slct is now know to be the desired identity constant when CC is true. 7408 SDValue TrueVal = OtherOp; 7409 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 7410 OtherOp, NonConstantVal); 7411 // Unless SwapSelectOps says CC should be false. 7412 if (SwapSelectOps) 7413 std::swap(TrueVal, FalseVal); 7414 7415 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7416 CCOp, TrueVal, FalseVal); 7417 } 7418 7419 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7420 static 7421 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes, 7422 TargetLowering::DAGCombinerInfo &DCI) { 7423 SDValue N0 = N->getOperand(0); 7424 SDValue N1 = N->getOperand(1); 7425 if (N0.getNode()->hasOneUse()) { 7426 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes); 7427 if (Result.getNode()) 7428 return Result; 7429 } 7430 if (N1.getNode()->hasOneUse()) { 7431 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes); 7432 if (Result.getNode()) 7433 return Result; 7434 } 7435 return SDValue(); 7436 } 7437 7438 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction 7439 // (only after legalization). 7440 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1, 7441 TargetLowering::DAGCombinerInfo &DCI, 7442 const ARMSubtarget *Subtarget) { 7443 7444 // Only perform optimization if after legalize, and if NEON is available. We 7445 // also expected both operands to be BUILD_VECTORs. 7446 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON() 7447 || N0.getOpcode() != ISD::BUILD_VECTOR 7448 || N1.getOpcode() != ISD::BUILD_VECTOR) 7449 return SDValue(); 7450 7451 // Check output type since VPADDL operand elements can only be 8, 16, or 32. 7452 EVT VT = N->getValueType(0); 7453 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64) 7454 return SDValue(); 7455 7456 // Check that the vector operands are of the right form. 7457 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR 7458 // operands, where N is the size of the formed vector. 7459 // Each EXTRACT_VECTOR should have the same input vector and odd or even 7460 // index such that we have a pair wise add pattern. 7461 7462 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing. 7463 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 7464 return SDValue(); 7465 SDValue Vec = N0->getOperand(0)->getOperand(0); 7466 SDNode *V = Vec.getNode(); 7467 unsigned nextIndex = 0; 7468 7469 // For each operands to the ADD which are BUILD_VECTORs, 7470 // check to see if each of their operands are an EXTRACT_VECTOR with 7471 // the same vector and appropriate index. 7472 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) { 7473 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT 7474 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 7475 7476 SDValue ExtVec0 = N0->getOperand(i); 7477 SDValue ExtVec1 = N1->getOperand(i); 7478 7479 // First operand is the vector, verify its the same. 7480 if (V != ExtVec0->getOperand(0).getNode() || 7481 V != ExtVec1->getOperand(0).getNode()) 7482 return SDValue(); 7483 7484 // Second is the constant, verify its correct. 7485 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1)); 7486 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1)); 7487 7488 // For the constant, we want to see all the even or all the odd. 7489 if (!C0 || !C1 || C0->getZExtValue() != nextIndex 7490 || C1->getZExtValue() != nextIndex+1) 7491 return SDValue(); 7492 7493 // Increment index. 7494 nextIndex+=2; 7495 } else 7496 return SDValue(); 7497 } 7498 7499 // Create VPADDL node. 7500 SelectionDAG &DAG = DCI.DAG; 7501 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7502 7503 // Build operand list. 7504 SmallVector<SDValue, 8> Ops; 7505 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, 7506 TLI.getPointerTy())); 7507 7508 // Input is the vector. 7509 Ops.push_back(Vec); 7510 7511 // Get widened type and narrowed type. 7512 MVT widenType; 7513 unsigned numElem = VT.getVectorNumElements(); 7514 7515 EVT inputLaneType = Vec.getValueType().getVectorElementType(); 7516 switch (inputLaneType.getSimpleVT().SimpleTy) { 7517 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break; 7518 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break; 7519 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break; 7520 default: 7521 llvm_unreachable("Invalid vector element type for padd optimization."); 7522 } 7523 7524 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), 7525 widenType, &Ops[0], Ops.size()); 7526 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE; 7527 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp); 7528 } 7529 7530 static SDValue findMUL_LOHI(SDValue V) { 7531 if (V->getOpcode() == ISD::UMUL_LOHI || 7532 V->getOpcode() == ISD::SMUL_LOHI) 7533 return V; 7534 return SDValue(); 7535 } 7536 7537 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode, 7538 TargetLowering::DAGCombinerInfo &DCI, 7539 const ARMSubtarget *Subtarget) { 7540 7541 if (Subtarget->isThumb1Only()) return SDValue(); 7542 7543 // Only perform the checks after legalize when the pattern is available. 7544 if (DCI.isBeforeLegalize()) return SDValue(); 7545 7546 // Look for multiply add opportunities. 7547 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where 7548 // each add nodes consumes a value from ISD::UMUL_LOHI and there is 7549 // a glue link from the first add to the second add. 7550 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by 7551 // a S/UMLAL instruction. 7552 // loAdd UMUL_LOHI 7553 // \ / :lo \ :hi 7554 // \ / \ [no multiline comment] 7555 // ADDC | hiAdd 7556 // \ :glue / / 7557 // \ / / 7558 // ADDE 7559 // 7560 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC"); 7561 SDValue AddcOp0 = AddcNode->getOperand(0); 7562 SDValue AddcOp1 = AddcNode->getOperand(1); 7563 7564 // Check if the two operands are from the same mul_lohi node. 7565 if (AddcOp0.getNode() == AddcOp1.getNode()) 7566 return SDValue(); 7567 7568 assert(AddcNode->getNumValues() == 2 && 7569 AddcNode->getValueType(0) == MVT::i32 && 7570 "Expect ADDC with two result values. First: i32"); 7571 7572 // Check that we have a glued ADDC node. 7573 if (AddcNode->getValueType(1) != MVT::Glue) 7574 return SDValue(); 7575 7576 // Check that the ADDC adds the low result of the S/UMUL_LOHI. 7577 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI && 7578 AddcOp0->getOpcode() != ISD::SMUL_LOHI && 7579 AddcOp1->getOpcode() != ISD::UMUL_LOHI && 7580 AddcOp1->getOpcode() != ISD::SMUL_LOHI) 7581 return SDValue(); 7582 7583 // Look for the glued ADDE. 7584 SDNode* AddeNode = AddcNode->getGluedUser(); 7585 if (AddeNode == NULL) 7586 return SDValue(); 7587 7588 // Make sure it is really an ADDE. 7589 if (AddeNode->getOpcode() != ISD::ADDE) 7590 return SDValue(); 7591 7592 assert(AddeNode->getNumOperands() == 3 && 7593 AddeNode->getOperand(2).getValueType() == MVT::Glue && 7594 "ADDE node has the wrong inputs"); 7595 7596 // Check for the triangle shape. 7597 SDValue AddeOp0 = AddeNode->getOperand(0); 7598 SDValue AddeOp1 = AddeNode->getOperand(1); 7599 7600 // Make sure that the ADDE operands are not coming from the same node. 7601 if (AddeOp0.getNode() == AddeOp1.getNode()) 7602 return SDValue(); 7603 7604 // Find the MUL_LOHI node walking up ADDE's operands. 7605 bool IsLeftOperandMUL = false; 7606 SDValue MULOp = findMUL_LOHI(AddeOp0); 7607 if (MULOp == SDValue()) 7608 MULOp = findMUL_LOHI(AddeOp1); 7609 else 7610 IsLeftOperandMUL = true; 7611 if (MULOp == SDValue()) 7612 return SDValue(); 7613 7614 // Figure out the right opcode. 7615 unsigned Opc = MULOp->getOpcode(); 7616 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL; 7617 7618 // Figure out the high and low input values to the MLAL node. 7619 SDValue* HiMul = &MULOp; 7620 SDValue* HiAdd = NULL; 7621 SDValue* LoMul = NULL; 7622 SDValue* LowAdd = NULL; 7623 7624 if (IsLeftOperandMUL) 7625 HiAdd = &AddeOp1; 7626 else 7627 HiAdd = &AddeOp0; 7628 7629 7630 if (AddcOp0->getOpcode() == Opc) { 7631 LoMul = &AddcOp0; 7632 LowAdd = &AddcOp1; 7633 } 7634 if (AddcOp1->getOpcode() == Opc) { 7635 LoMul = &AddcOp1; 7636 LowAdd = &AddcOp0; 7637 } 7638 7639 if (LoMul == NULL) 7640 return SDValue(); 7641 7642 if (LoMul->getNode() != HiMul->getNode()) 7643 return SDValue(); 7644 7645 // Create the merged node. 7646 SelectionDAG &DAG = DCI.DAG; 7647 7648 // Build operand list. 7649 SmallVector<SDValue, 8> Ops; 7650 Ops.push_back(LoMul->getOperand(0)); 7651 Ops.push_back(LoMul->getOperand(1)); 7652 Ops.push_back(*LowAdd); 7653 Ops.push_back(*HiAdd); 7654 7655 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode), 7656 DAG.getVTList(MVT::i32, MVT::i32), 7657 &Ops[0], Ops.size()); 7658 7659 // Replace the ADDs' nodes uses by the MLA node's values. 7660 SDValue HiMLALResult(MLALNode.getNode(), 1); 7661 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult); 7662 7663 SDValue LoMLALResult(MLALNode.getNode(), 0); 7664 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult); 7665 7666 // Return original node to notify the driver to stop replacing. 7667 SDValue resNode(AddcNode, 0); 7668 return resNode; 7669 } 7670 7671 /// PerformADDCCombine - Target-specific dag combine transform from 7672 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL. 7673 static SDValue PerformADDCCombine(SDNode *N, 7674 TargetLowering::DAGCombinerInfo &DCI, 7675 const ARMSubtarget *Subtarget) { 7676 7677 return AddCombineTo64bitMLAL(N, DCI, Subtarget); 7678 7679 } 7680 7681 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with 7682 /// operands N0 and N1. This is a helper for PerformADDCombine that is 7683 /// called with the default operands, and if that fails, with commuted 7684 /// operands. 7685 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1, 7686 TargetLowering::DAGCombinerInfo &DCI, 7687 const ARMSubtarget *Subtarget){ 7688 7689 // Attempt to create vpaddl for this add. 7690 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget); 7691 if (Result.getNode()) 7692 return Result; 7693 7694 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c)) 7695 if (N0.getNode()->hasOneUse()) { 7696 SDValue Result = combineSelectAndUse(N, N0, N1, DCI); 7697 if (Result.getNode()) return Result; 7698 } 7699 return SDValue(); 7700 } 7701 7702 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD. 7703 /// 7704 static SDValue PerformADDCombine(SDNode *N, 7705 TargetLowering::DAGCombinerInfo &DCI, 7706 const ARMSubtarget *Subtarget) { 7707 SDValue N0 = N->getOperand(0); 7708 SDValue N1 = N->getOperand(1); 7709 7710 // First try with the default operand order. 7711 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget); 7712 if (Result.getNode()) 7713 return Result; 7714 7715 // If that didn't work, try again with the operands commuted. 7716 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget); 7717 } 7718 7719 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB. 7720 /// 7721 static SDValue PerformSUBCombine(SDNode *N, 7722 TargetLowering::DAGCombinerInfo &DCI) { 7723 SDValue N0 = N->getOperand(0); 7724 SDValue N1 = N->getOperand(1); 7725 7726 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c)) 7727 if (N1.getNode()->hasOneUse()) { 7728 SDValue Result = combineSelectAndUse(N, N1, N0, DCI); 7729 if (Result.getNode()) return Result; 7730 } 7731 7732 return SDValue(); 7733 } 7734 7735 /// PerformVMULCombine 7736 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the 7737 /// special multiplier accumulator forwarding. 7738 /// vmul d3, d0, d2 7739 /// vmla d3, d1, d2 7740 /// is faster than 7741 /// vadd d3, d0, d1 7742 /// vmul d3, d3, d2 7743 // However, for (A + B) * (A + B), 7744 // vadd d2, d0, d1 7745 // vmul d3, d0, d2 7746 // vmla d3, d1, d2 7747 // is slower than 7748 // vadd d2, d0, d1 7749 // vmul d3, d2, d2 7750 static SDValue PerformVMULCombine(SDNode *N, 7751 TargetLowering::DAGCombinerInfo &DCI, 7752 const ARMSubtarget *Subtarget) { 7753 if (!Subtarget->hasVMLxForwarding()) 7754 return SDValue(); 7755 7756 SelectionDAG &DAG = DCI.DAG; 7757 SDValue N0 = N->getOperand(0); 7758 SDValue N1 = N->getOperand(1); 7759 unsigned Opcode = N0.getOpcode(); 7760 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 7761 Opcode != ISD::FADD && Opcode != ISD::FSUB) { 7762 Opcode = N1.getOpcode(); 7763 if (Opcode != ISD::ADD && Opcode != ISD::SUB && 7764 Opcode != ISD::FADD && Opcode != ISD::FSUB) 7765 return SDValue(); 7766 std::swap(N0, N1); 7767 } 7768 7769 if (N0 == N1) 7770 return SDValue(); 7771 7772 EVT VT = N->getValueType(0); 7773 SDLoc DL(N); 7774 SDValue N00 = N0->getOperand(0); 7775 SDValue N01 = N0->getOperand(1); 7776 return DAG.getNode(Opcode, DL, VT, 7777 DAG.getNode(ISD::MUL, DL, VT, N00, N1), 7778 DAG.getNode(ISD::MUL, DL, VT, N01, N1)); 7779 } 7780 7781 static SDValue PerformMULCombine(SDNode *N, 7782 TargetLowering::DAGCombinerInfo &DCI, 7783 const ARMSubtarget *Subtarget) { 7784 SelectionDAG &DAG = DCI.DAG; 7785 7786 if (Subtarget->isThumb1Only()) 7787 return SDValue(); 7788 7789 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 7790 return SDValue(); 7791 7792 EVT VT = N->getValueType(0); 7793 if (VT.is64BitVector() || VT.is128BitVector()) 7794 return PerformVMULCombine(N, DCI, Subtarget); 7795 if (VT != MVT::i32) 7796 return SDValue(); 7797 7798 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7799 if (!C) 7800 return SDValue(); 7801 7802 int64_t MulAmt = C->getSExtValue(); 7803 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt); 7804 7805 ShiftAmt = ShiftAmt & (32 - 1); 7806 SDValue V = N->getOperand(0); 7807 SDLoc DL(N); 7808 7809 SDValue Res; 7810 MulAmt >>= ShiftAmt; 7811 7812 if (MulAmt >= 0) { 7813 if (isPowerOf2_32(MulAmt - 1)) { 7814 // (mul x, 2^N + 1) => (add (shl x, N), x) 7815 Res = DAG.getNode(ISD::ADD, DL, VT, 7816 V, 7817 DAG.getNode(ISD::SHL, DL, VT, 7818 V, 7819 DAG.getConstant(Log2_32(MulAmt - 1), 7820 MVT::i32))); 7821 } else if (isPowerOf2_32(MulAmt + 1)) { 7822 // (mul x, 2^N - 1) => (sub (shl x, N), x) 7823 Res = DAG.getNode(ISD::SUB, DL, VT, 7824 DAG.getNode(ISD::SHL, DL, VT, 7825 V, 7826 DAG.getConstant(Log2_32(MulAmt + 1), 7827 MVT::i32)), 7828 V); 7829 } else 7830 return SDValue(); 7831 } else { 7832 uint64_t MulAmtAbs = -MulAmt; 7833 if (isPowerOf2_32(MulAmtAbs + 1)) { 7834 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 7835 Res = DAG.getNode(ISD::SUB, DL, VT, 7836 V, 7837 DAG.getNode(ISD::SHL, DL, VT, 7838 V, 7839 DAG.getConstant(Log2_32(MulAmtAbs + 1), 7840 MVT::i32))); 7841 } else if (isPowerOf2_32(MulAmtAbs - 1)) { 7842 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 7843 Res = DAG.getNode(ISD::ADD, DL, VT, 7844 V, 7845 DAG.getNode(ISD::SHL, DL, VT, 7846 V, 7847 DAG.getConstant(Log2_32(MulAmtAbs-1), 7848 MVT::i32))); 7849 Res = DAG.getNode(ISD::SUB, DL, VT, 7850 DAG.getConstant(0, MVT::i32),Res); 7851 7852 } else 7853 return SDValue(); 7854 } 7855 7856 if (ShiftAmt != 0) 7857 Res = DAG.getNode(ISD::SHL, DL, VT, 7858 Res, DAG.getConstant(ShiftAmt, MVT::i32)); 7859 7860 // Do not add new nodes to DAG combiner worklist. 7861 DCI.CombineTo(N, Res, false); 7862 return SDValue(); 7863 } 7864 7865 static SDValue PerformANDCombine(SDNode *N, 7866 TargetLowering::DAGCombinerInfo &DCI, 7867 const ARMSubtarget *Subtarget) { 7868 7869 // Attempt to use immediate-form VBIC 7870 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 7871 SDLoc dl(N); 7872 EVT VT = N->getValueType(0); 7873 SelectionDAG &DAG = DCI.DAG; 7874 7875 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 7876 return SDValue(); 7877 7878 APInt SplatBits, SplatUndef; 7879 unsigned SplatBitSize; 7880 bool HasAnyUndefs; 7881 if (BVN && 7882 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7883 if (SplatBitSize <= 64) { 7884 EVT VbicVT; 7885 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(), 7886 SplatUndef.getZExtValue(), SplatBitSize, 7887 DAG, VbicVT, VT.is128BitVector(), 7888 OtherModImm); 7889 if (Val.getNode()) { 7890 SDValue Input = 7891 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0)); 7892 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val); 7893 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic); 7894 } 7895 } 7896 } 7897 7898 if (!Subtarget->isThumb1Only()) { 7899 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) 7900 SDValue Result = combineSelectAndUseCommutative(N, true, DCI); 7901 if (Result.getNode()) 7902 return Result; 7903 } 7904 7905 return SDValue(); 7906 } 7907 7908 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR 7909 static SDValue PerformORCombine(SDNode *N, 7910 TargetLowering::DAGCombinerInfo &DCI, 7911 const ARMSubtarget *Subtarget) { 7912 // Attempt to use immediate-form VORR 7913 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1)); 7914 SDLoc dl(N); 7915 EVT VT = N->getValueType(0); 7916 SelectionDAG &DAG = DCI.DAG; 7917 7918 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 7919 return SDValue(); 7920 7921 APInt SplatBits, SplatUndef; 7922 unsigned SplatBitSize; 7923 bool HasAnyUndefs; 7924 if (BVN && Subtarget->hasNEON() && 7925 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7926 if (SplatBitSize <= 64) { 7927 EVT VorrVT; 7928 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(), 7929 SplatUndef.getZExtValue(), SplatBitSize, 7930 DAG, VorrVT, VT.is128BitVector(), 7931 OtherModImm); 7932 if (Val.getNode()) { 7933 SDValue Input = 7934 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0)); 7935 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val); 7936 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr); 7937 } 7938 } 7939 } 7940 7941 if (!Subtarget->isThumb1Only()) { 7942 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c)) 7943 SDValue Result = combineSelectAndUseCommutative(N, false, DCI); 7944 if (Result.getNode()) 7945 return Result; 7946 } 7947 7948 // The code below optimizes (or (and X, Y), Z). 7949 // The AND operand needs to have a single user to make these optimizations 7950 // profitable. 7951 SDValue N0 = N->getOperand(0); 7952 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse()) 7953 return SDValue(); 7954 SDValue N1 = N->getOperand(1); 7955 7956 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant. 7957 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() && 7958 DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 7959 APInt SplatUndef; 7960 unsigned SplatBitSize; 7961 bool HasAnyUndefs; 7962 7963 APInt SplatBits0, SplatBits1; 7964 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1)); 7965 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1)); 7966 // Ensure that the second operand of both ands are constants 7967 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize, 7968 HasAnyUndefs) && !HasAnyUndefs) { 7969 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize, 7970 HasAnyUndefs) && !HasAnyUndefs) { 7971 // Ensure that the bit width of the constants are the same and that 7972 // the splat arguments are logical inverses as per the pattern we 7973 // are trying to simplify. 7974 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() && 7975 SplatBits0 == ~SplatBits1) { 7976 // Canonicalize the vector type to make instruction selection 7977 // simpler. 7978 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32; 7979 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT, 7980 N0->getOperand(1), 7981 N0->getOperand(0), 7982 N1->getOperand(0)); 7983 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 7984 } 7985 } 7986 } 7987 } 7988 7989 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when 7990 // reasonable. 7991 7992 // BFI is only available on V6T2+ 7993 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops()) 7994 return SDValue(); 7995 7996 SDLoc DL(N); 7997 // 1) or (and A, mask), val => ARMbfi A, val, mask 7998 // iff (val & mask) == val 7999 // 8000 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 8001 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2) 8002 // && mask == ~mask2 8003 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2) 8004 // && ~mask == mask2 8005 // (i.e., copy a bitfield value into another bitfield of the same width) 8006 8007 if (VT != MVT::i32) 8008 return SDValue(); 8009 8010 SDValue N00 = N0.getOperand(0); 8011 8012 // The value and the mask need to be constants so we can verify this is 8013 // actually a bitfield set. If the mask is 0xffff, we can do better 8014 // via a movt instruction, so don't use BFI in that case. 8015 SDValue MaskOp = N0.getOperand(1); 8016 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp); 8017 if (!MaskC) 8018 return SDValue(); 8019 unsigned Mask = MaskC->getZExtValue(); 8020 if (Mask == 0xffff) 8021 return SDValue(); 8022 SDValue Res; 8023 // Case (1): or (and A, mask), val => ARMbfi A, val, mask 8024 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 8025 if (N1C) { 8026 unsigned Val = N1C->getZExtValue(); 8027 if ((Val & ~Mask) != Val) 8028 return SDValue(); 8029 8030 if (ARM::isBitFieldInvertedMask(Mask)) { 8031 Val >>= countTrailingZeros(~Mask); 8032 8033 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, 8034 DAG.getConstant(Val, MVT::i32), 8035 DAG.getConstant(Mask, MVT::i32)); 8036 8037 // Do not add new nodes to DAG combiner worklist. 8038 DCI.CombineTo(N, Res, false); 8039 return SDValue(); 8040 } 8041 } else if (N1.getOpcode() == ISD::AND) { 8042 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask 8043 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 8044 if (!N11C) 8045 return SDValue(); 8046 unsigned Mask2 = N11C->getZExtValue(); 8047 8048 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern 8049 // as is to match. 8050 if (ARM::isBitFieldInvertedMask(Mask) && 8051 (Mask == ~Mask2)) { 8052 // The pack halfword instruction works better for masks that fit it, 8053 // so use that when it's available. 8054 if (Subtarget->hasT2ExtractPack() && 8055 (Mask == 0xffff || Mask == 0xffff0000)) 8056 return SDValue(); 8057 // 2a 8058 unsigned amt = countTrailingZeros(Mask2); 8059 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0), 8060 DAG.getConstant(amt, MVT::i32)); 8061 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res, 8062 DAG.getConstant(Mask, MVT::i32)); 8063 // Do not add new nodes to DAG combiner worklist. 8064 DCI.CombineTo(N, Res, false); 8065 return SDValue(); 8066 } else if (ARM::isBitFieldInvertedMask(~Mask) && 8067 (~Mask == Mask2)) { 8068 // The pack halfword instruction works better for masks that fit it, 8069 // so use that when it's available. 8070 if (Subtarget->hasT2ExtractPack() && 8071 (Mask2 == 0xffff || Mask2 == 0xffff0000)) 8072 return SDValue(); 8073 // 2b 8074 unsigned lsb = countTrailingZeros(Mask); 8075 Res = DAG.getNode(ISD::SRL, DL, VT, N00, 8076 DAG.getConstant(lsb, MVT::i32)); 8077 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res, 8078 DAG.getConstant(Mask2, MVT::i32)); 8079 // Do not add new nodes to DAG combiner worklist. 8080 DCI.CombineTo(N, Res, false); 8081 return SDValue(); 8082 } 8083 } 8084 8085 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) && 8086 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) && 8087 ARM::isBitFieldInvertedMask(~Mask)) { 8088 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask 8089 // where lsb(mask) == #shamt and masked bits of B are known zero. 8090 SDValue ShAmt = N00.getOperand(1); 8091 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 8092 unsigned LSB = countTrailingZeros(Mask); 8093 if (ShAmtC != LSB) 8094 return SDValue(); 8095 8096 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0), 8097 DAG.getConstant(~Mask, MVT::i32)); 8098 8099 // Do not add new nodes to DAG combiner worklist. 8100 DCI.CombineTo(N, Res, false); 8101 } 8102 8103 return SDValue(); 8104 } 8105 8106 static SDValue PerformXORCombine(SDNode *N, 8107 TargetLowering::DAGCombinerInfo &DCI, 8108 const ARMSubtarget *Subtarget) { 8109 EVT VT = N->getValueType(0); 8110 SelectionDAG &DAG = DCI.DAG; 8111 8112 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8113 return SDValue(); 8114 8115 if (!Subtarget->isThumb1Only()) { 8116 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c)) 8117 SDValue Result = combineSelectAndUseCommutative(N, false, DCI); 8118 if (Result.getNode()) 8119 return Result; 8120 } 8121 8122 return SDValue(); 8123 } 8124 8125 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff 8126 /// the bits being cleared by the AND are not demanded by the BFI. 8127 static SDValue PerformBFICombine(SDNode *N, 8128 TargetLowering::DAGCombinerInfo &DCI) { 8129 SDValue N1 = N->getOperand(1); 8130 if (N1.getOpcode() == ISD::AND) { 8131 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 8132 if (!N11C) 8133 return SDValue(); 8134 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 8135 unsigned LSB = countTrailingZeros(~InvMask); 8136 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB; 8137 unsigned Mask = (1 << Width)-1; 8138 unsigned Mask2 = N11C->getZExtValue(); 8139 if ((Mask & (~Mask2)) == 0) 8140 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0), 8141 N->getOperand(0), N1.getOperand(0), 8142 N->getOperand(2)); 8143 } 8144 return SDValue(); 8145 } 8146 8147 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for 8148 /// ARMISD::VMOVRRD. 8149 static SDValue PerformVMOVRRDCombine(SDNode *N, 8150 TargetLowering::DAGCombinerInfo &DCI) { 8151 // vmovrrd(vmovdrr x, y) -> x,y 8152 SDValue InDouble = N->getOperand(0); 8153 if (InDouble.getOpcode() == ARMISD::VMOVDRR) 8154 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1)); 8155 8156 // vmovrrd(load f64) -> (load i32), (load i32) 8157 SDNode *InNode = InDouble.getNode(); 8158 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() && 8159 InNode->getValueType(0) == MVT::f64 && 8160 InNode->getOperand(1).getOpcode() == ISD::FrameIndex && 8161 !cast<LoadSDNode>(InNode)->isVolatile()) { 8162 // TODO: Should this be done for non-FrameIndex operands? 8163 LoadSDNode *LD = cast<LoadSDNode>(InNode); 8164 8165 SelectionDAG &DAG = DCI.DAG; 8166 SDLoc DL(LD); 8167 SDValue BasePtr = LD->getBasePtr(); 8168 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, 8169 LD->getPointerInfo(), LD->isVolatile(), 8170 LD->isNonTemporal(), LD->isInvariant(), 8171 LD->getAlignment()); 8172 8173 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 8174 DAG.getConstant(4, MVT::i32)); 8175 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, 8176 LD->getPointerInfo(), LD->isVolatile(), 8177 LD->isNonTemporal(), LD->isInvariant(), 8178 std::min(4U, LD->getAlignment() / 2)); 8179 8180 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1)); 8181 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2); 8182 DCI.RemoveFromWorklist(LD); 8183 DAG.DeleteNode(LD); 8184 return Result; 8185 } 8186 8187 return SDValue(); 8188 } 8189 8190 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for 8191 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands. 8192 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) { 8193 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X) 8194 SDValue Op0 = N->getOperand(0); 8195 SDValue Op1 = N->getOperand(1); 8196 if (Op0.getOpcode() == ISD::BITCAST) 8197 Op0 = Op0.getOperand(0); 8198 if (Op1.getOpcode() == ISD::BITCAST) 8199 Op1 = Op1.getOperand(0); 8200 if (Op0.getOpcode() == ARMISD::VMOVRRD && 8201 Op0.getNode() == Op1.getNode() && 8202 Op0.getResNo() == 0 && Op1.getResNo() == 1) 8203 return DAG.getNode(ISD::BITCAST, SDLoc(N), 8204 N->getValueType(0), Op0.getOperand(0)); 8205 return SDValue(); 8206 } 8207 8208 /// PerformSTORECombine - Target-specific dag combine xforms for 8209 /// ISD::STORE. 8210 static SDValue PerformSTORECombine(SDNode *N, 8211 TargetLowering::DAGCombinerInfo &DCI) { 8212 StoreSDNode *St = cast<StoreSDNode>(N); 8213 if (St->isVolatile()) 8214 return SDValue(); 8215 8216 // Optimize trunc store (of multiple scalars) to shuffle and store. First, 8217 // pack all of the elements in one place. Next, store to memory in fewer 8218 // chunks. 8219 SDValue StVal = St->getValue(); 8220 EVT VT = StVal.getValueType(); 8221 if (St->isTruncatingStore() && VT.isVector()) { 8222 SelectionDAG &DAG = DCI.DAG; 8223 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8224 EVT StVT = St->getMemoryVT(); 8225 unsigned NumElems = VT.getVectorNumElements(); 8226 assert(StVT != VT && "Cannot truncate to the same type"); 8227 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits(); 8228 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits(); 8229 8230 // From, To sizes and ElemCount must be pow of two 8231 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue(); 8232 8233 // We are going to use the original vector elt for storing. 8234 // Accumulated smaller vector elements must be a multiple of the store size. 8235 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue(); 8236 8237 unsigned SizeRatio = FromEltSz / ToEltSz; 8238 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits()); 8239 8240 // Create a type on which we perform the shuffle. 8241 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(), 8242 NumElems*SizeRatio); 8243 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 8244 8245 SDLoc DL(St); 8246 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal); 8247 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 8248 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio; 8249 8250 // Can't shuffle using an illegal type. 8251 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 8252 8253 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec, 8254 DAG.getUNDEF(WideVec.getValueType()), 8255 ShuffleVec.data()); 8256 // At this point all of the data is stored at the bottom of the 8257 // register. We now need to save it to mem. 8258 8259 // Find the largest store unit 8260 MVT StoreType = MVT::i8; 8261 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 8262 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 8263 MVT Tp = (MVT::SimpleValueType)tp; 8264 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz) 8265 StoreType = Tp; 8266 } 8267 // Didn't find a legal store type. 8268 if (!TLI.isTypeLegal(StoreType)) 8269 return SDValue(); 8270 8271 // Bitcast the original vector into a vector of store-size units 8272 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 8273 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 8274 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 8275 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff); 8276 SmallVector<SDValue, 8> Chains; 8277 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, 8278 TLI.getPointerTy()); 8279 SDValue BasePtr = St->getBasePtr(); 8280 8281 // Perform one or more big stores into memory. 8282 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits(); 8283 for (unsigned I = 0; I < E; I++) { 8284 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 8285 StoreType, ShuffWide, 8286 DAG.getIntPtrConstant(I)); 8287 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr, 8288 St->getPointerInfo(), St->isVolatile(), 8289 St->isNonTemporal(), St->getAlignment()); 8290 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 8291 Increment); 8292 Chains.push_back(Ch); 8293 } 8294 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0], 8295 Chains.size()); 8296 } 8297 8298 if (!ISD::isNormalStore(St)) 8299 return SDValue(); 8300 8301 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and 8302 // ARM stores of arguments in the same cache line. 8303 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR && 8304 StVal.getNode()->hasOneUse()) { 8305 SelectionDAG &DAG = DCI.DAG; 8306 SDLoc DL(St); 8307 SDValue BasePtr = St->getBasePtr(); 8308 SDValue NewST1 = DAG.getStore(St->getChain(), DL, 8309 StVal.getNode()->getOperand(0), BasePtr, 8310 St->getPointerInfo(), St->isVolatile(), 8311 St->isNonTemporal(), St->getAlignment()); 8312 8313 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr, 8314 DAG.getConstant(4, MVT::i32)); 8315 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1), 8316 OffsetPtr, St->getPointerInfo(), St->isVolatile(), 8317 St->isNonTemporal(), 8318 std::min(4U, St->getAlignment() / 2)); 8319 } 8320 8321 if (StVal.getValueType() != MVT::i64 || 8322 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8323 return SDValue(); 8324 8325 // Bitcast an i64 store extracted from a vector to f64. 8326 // Otherwise, the i64 value will be legalized to a pair of i32 values. 8327 SelectionDAG &DAG = DCI.DAG; 8328 SDLoc dl(StVal); 8329 SDValue IntVec = StVal.getOperand(0); 8330 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 8331 IntVec.getValueType().getVectorNumElements()); 8332 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec); 8333 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 8334 Vec, StVal.getOperand(1)); 8335 dl = SDLoc(N); 8336 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt); 8337 // Make the DAGCombiner fold the bitcasts. 8338 DCI.AddToWorklist(Vec.getNode()); 8339 DCI.AddToWorklist(ExtElt.getNode()); 8340 DCI.AddToWorklist(V.getNode()); 8341 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(), 8342 St->getPointerInfo(), St->isVolatile(), 8343 St->isNonTemporal(), St->getAlignment(), 8344 St->getTBAAInfo()); 8345 } 8346 8347 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node 8348 /// are normal, non-volatile loads. If so, it is profitable to bitcast an 8349 /// i64 vector to have f64 elements, since the value can then be loaded 8350 /// directly into a VFP register. 8351 static bool hasNormalLoadOperand(SDNode *N) { 8352 unsigned NumElts = N->getValueType(0).getVectorNumElements(); 8353 for (unsigned i = 0; i < NumElts; ++i) { 8354 SDNode *Elt = N->getOperand(i).getNode(); 8355 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile()) 8356 return true; 8357 } 8358 return false; 8359 } 8360 8361 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for 8362 /// ISD::BUILD_VECTOR. 8363 static SDValue PerformBUILD_VECTORCombine(SDNode *N, 8364 TargetLowering::DAGCombinerInfo &DCI){ 8365 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X): 8366 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value 8367 // into a pair of GPRs, which is fine when the value is used as a scalar, 8368 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD. 8369 SelectionDAG &DAG = DCI.DAG; 8370 if (N->getNumOperands() == 2) { 8371 SDValue RV = PerformVMOVDRRCombine(N, DAG); 8372 if (RV.getNode()) 8373 return RV; 8374 } 8375 8376 // Load i64 elements as f64 values so that type legalization does not split 8377 // them up into i32 values. 8378 EVT VT = N->getValueType(0); 8379 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N)) 8380 return SDValue(); 8381 SDLoc dl(N); 8382 SmallVector<SDValue, 8> Ops; 8383 unsigned NumElts = VT.getVectorNumElements(); 8384 for (unsigned i = 0; i < NumElts; ++i) { 8385 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i)); 8386 Ops.push_back(V); 8387 // Make the DAGCombiner fold the bitcast. 8388 DCI.AddToWorklist(V.getNode()); 8389 } 8390 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts); 8391 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts); 8392 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 8393 } 8394 8395 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR. 8396 static SDValue 8397 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 8398 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR. 8399 // At that time, we may have inserted bitcasts from integer to float. 8400 // If these bitcasts have survived DAGCombine, change the lowering of this 8401 // BUILD_VECTOR in something more vector friendly, i.e., that does not 8402 // force to use floating point types. 8403 8404 // Make sure we can change the type of the vector. 8405 // This is possible iff: 8406 // 1. The vector is only used in a bitcast to a integer type. I.e., 8407 // 1.1. Vector is used only once. 8408 // 1.2. Use is a bit convert to an integer type. 8409 // 2. The size of its operands are 32-bits (64-bits are not legal). 8410 EVT VT = N->getValueType(0); 8411 EVT EltVT = VT.getVectorElementType(); 8412 8413 // Check 1.1. and 2. 8414 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse()) 8415 return SDValue(); 8416 8417 // By construction, the input type must be float. 8418 assert(EltVT == MVT::f32 && "Unexpected type!"); 8419 8420 // Check 1.2. 8421 SDNode *Use = *N->use_begin(); 8422 if (Use->getOpcode() != ISD::BITCAST || 8423 Use->getValueType(0).isFloatingPoint()) 8424 return SDValue(); 8425 8426 // Check profitability. 8427 // Model is, if more than half of the relevant operands are bitcast from 8428 // i32, turn the build_vector into a sequence of insert_vector_elt. 8429 // Relevant operands are everything that is not statically 8430 // (i.e., at compile time) bitcasted. 8431 unsigned NumOfBitCastedElts = 0; 8432 unsigned NumElts = VT.getVectorNumElements(); 8433 unsigned NumOfRelevantElts = NumElts; 8434 for (unsigned Idx = 0; Idx < NumElts; ++Idx) { 8435 SDValue Elt = N->getOperand(Idx); 8436 if (Elt->getOpcode() == ISD::BITCAST) { 8437 // Assume only bit cast to i32 will go away. 8438 if (Elt->getOperand(0).getValueType() == MVT::i32) 8439 ++NumOfBitCastedElts; 8440 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt)) 8441 // Constants are statically casted, thus do not count them as 8442 // relevant operands. 8443 --NumOfRelevantElts; 8444 } 8445 8446 // Check if more than half of the elements require a non-free bitcast. 8447 if (NumOfBitCastedElts <= NumOfRelevantElts / 2) 8448 return SDValue(); 8449 8450 SelectionDAG &DAG = DCI.DAG; 8451 // Create the new vector type. 8452 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts); 8453 // Check if the type is legal. 8454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8455 if (!TLI.isTypeLegal(VecVT)) 8456 return SDValue(); 8457 8458 // Combine: 8459 // ARMISD::BUILD_VECTOR E1, E2, ..., EN. 8460 // => BITCAST INSERT_VECTOR_ELT 8461 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1), 8462 // (BITCAST EN), N. 8463 SDValue Vec = DAG.getUNDEF(VecVT); 8464 SDLoc dl(N); 8465 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) { 8466 SDValue V = N->getOperand(Idx); 8467 if (V.getOpcode() == ISD::UNDEF) 8468 continue; 8469 if (V.getOpcode() == ISD::BITCAST && 8470 V->getOperand(0).getValueType() == MVT::i32) 8471 // Fold obvious case. 8472 V = V.getOperand(0); 8473 else { 8474 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 8475 // Make the DAGCombiner fold the bitcasts. 8476 DCI.AddToWorklist(V.getNode()); 8477 } 8478 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32); 8479 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx); 8480 } 8481 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec); 8482 // Make the DAGCombiner fold the bitcasts. 8483 DCI.AddToWorklist(Vec.getNode()); 8484 return Vec; 8485 } 8486 8487 /// PerformInsertEltCombine - Target-specific dag combine xforms for 8488 /// ISD::INSERT_VECTOR_ELT. 8489 static SDValue PerformInsertEltCombine(SDNode *N, 8490 TargetLowering::DAGCombinerInfo &DCI) { 8491 // Bitcast an i64 load inserted into a vector to f64. 8492 // Otherwise, the i64 value will be legalized to a pair of i32 values. 8493 EVT VT = N->getValueType(0); 8494 SDNode *Elt = N->getOperand(1).getNode(); 8495 if (VT.getVectorElementType() != MVT::i64 || 8496 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile()) 8497 return SDValue(); 8498 8499 SelectionDAG &DAG = DCI.DAG; 8500 SDLoc dl(N); 8501 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, 8502 VT.getVectorNumElements()); 8503 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0)); 8504 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1)); 8505 // Make the DAGCombiner fold the bitcasts. 8506 DCI.AddToWorklist(Vec.getNode()); 8507 DCI.AddToWorklist(V.getNode()); 8508 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT, 8509 Vec, V, N->getOperand(2)); 8510 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt); 8511 } 8512 8513 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for 8514 /// ISD::VECTOR_SHUFFLE. 8515 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) { 8516 // The LLVM shufflevector instruction does not require the shuffle mask 8517 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does 8518 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the 8519 // operands do not match the mask length, they are extended by concatenating 8520 // them with undef vectors. That is probably the right thing for other 8521 // targets, but for NEON it is better to concatenate two double-register 8522 // size vector operands into a single quad-register size vector. Do that 8523 // transformation here: 8524 // shuffle(concat(v1, undef), concat(v2, undef)) -> 8525 // shuffle(concat(v1, v2), undef) 8526 SDValue Op0 = N->getOperand(0); 8527 SDValue Op1 = N->getOperand(1); 8528 if (Op0.getOpcode() != ISD::CONCAT_VECTORS || 8529 Op1.getOpcode() != ISD::CONCAT_VECTORS || 8530 Op0.getNumOperands() != 2 || 8531 Op1.getNumOperands() != 2) 8532 return SDValue(); 8533 SDValue Concat0Op1 = Op0.getOperand(1); 8534 SDValue Concat1Op1 = Op1.getOperand(1); 8535 if (Concat0Op1.getOpcode() != ISD::UNDEF || 8536 Concat1Op1.getOpcode() != ISD::UNDEF) 8537 return SDValue(); 8538 // Skip the transformation if any of the types are illegal. 8539 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8540 EVT VT = N->getValueType(0); 8541 if (!TLI.isTypeLegal(VT) || 8542 !TLI.isTypeLegal(Concat0Op1.getValueType()) || 8543 !TLI.isTypeLegal(Concat1Op1.getValueType())) 8544 return SDValue(); 8545 8546 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 8547 Op0.getOperand(0), Op1.getOperand(0)); 8548 // Translate the shuffle mask. 8549 SmallVector<int, 16> NewMask; 8550 unsigned NumElts = VT.getVectorNumElements(); 8551 unsigned HalfElts = NumElts/2; 8552 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 8553 for (unsigned n = 0; n < NumElts; ++n) { 8554 int MaskElt = SVN->getMaskElt(n); 8555 int NewElt = -1; 8556 if (MaskElt < (int)HalfElts) 8557 NewElt = MaskElt; 8558 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts)) 8559 NewElt = HalfElts + MaskElt - NumElts; 8560 NewMask.push_back(NewElt); 8561 } 8562 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat, 8563 DAG.getUNDEF(VT), NewMask.data()); 8564 } 8565 8566 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and 8567 /// NEON load/store intrinsics to merge base address updates. 8568 static SDValue CombineBaseUpdate(SDNode *N, 8569 TargetLowering::DAGCombinerInfo &DCI) { 8570 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 8571 return SDValue(); 8572 8573 SelectionDAG &DAG = DCI.DAG; 8574 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID || 8575 N->getOpcode() == ISD::INTRINSIC_W_CHAIN); 8576 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1); 8577 SDValue Addr = N->getOperand(AddrOpIdx); 8578 8579 // Search for a use of the address operand that is an increment. 8580 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 8581 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 8582 SDNode *User = *UI; 8583 if (User->getOpcode() != ISD::ADD || 8584 UI.getUse().getResNo() != Addr.getResNo()) 8585 continue; 8586 8587 // Check that the add is independent of the load/store. Otherwise, folding 8588 // it would create a cycle. 8589 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 8590 continue; 8591 8592 // Find the new opcode for the updating load/store. 8593 bool isLoad = true; 8594 bool isLaneOp = false; 8595 unsigned NewOpc = 0; 8596 unsigned NumVecs = 0; 8597 if (isIntrinsic) { 8598 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 8599 switch (IntNo) { 8600 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 8601 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD; 8602 NumVecs = 1; break; 8603 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD; 8604 NumVecs = 2; break; 8605 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD; 8606 NumVecs = 3; break; 8607 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD; 8608 NumVecs = 4; break; 8609 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD; 8610 NumVecs = 2; isLaneOp = true; break; 8611 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD; 8612 NumVecs = 3; isLaneOp = true; break; 8613 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD; 8614 NumVecs = 4; isLaneOp = true; break; 8615 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD; 8616 NumVecs = 1; isLoad = false; break; 8617 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD; 8618 NumVecs = 2; isLoad = false; break; 8619 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD; 8620 NumVecs = 3; isLoad = false; break; 8621 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD; 8622 NumVecs = 4; isLoad = false; break; 8623 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD; 8624 NumVecs = 2; isLoad = false; isLaneOp = true; break; 8625 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD; 8626 NumVecs = 3; isLoad = false; isLaneOp = true; break; 8627 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD; 8628 NumVecs = 4; isLoad = false; isLaneOp = true; break; 8629 } 8630 } else { 8631 isLaneOp = true; 8632 switch (N->getOpcode()) { 8633 default: llvm_unreachable("unexpected opcode for Neon base update"); 8634 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break; 8635 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break; 8636 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break; 8637 } 8638 } 8639 8640 // Find the size of memory referenced by the load/store. 8641 EVT VecTy; 8642 if (isLoad) 8643 VecTy = N->getValueType(0); 8644 else 8645 VecTy = N->getOperand(AddrOpIdx+1).getValueType(); 8646 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 8647 if (isLaneOp) 8648 NumBytes /= VecTy.getVectorNumElements(); 8649 8650 // If the increment is a constant, it must match the memory ref size. 8651 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 8652 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 8653 uint64_t IncVal = CInc->getZExtValue(); 8654 if (IncVal != NumBytes) 8655 continue; 8656 } else if (NumBytes >= 3 * 16) { 8657 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two 8658 // separate instructions that make it harder to use a non-constant update. 8659 continue; 8660 } 8661 8662 // Create the new updating load/store node. 8663 EVT Tys[6]; 8664 unsigned NumResultVecs = (isLoad ? NumVecs : 0); 8665 unsigned n; 8666 for (n = 0; n < NumResultVecs; ++n) 8667 Tys[n] = VecTy; 8668 Tys[n++] = MVT::i32; 8669 Tys[n] = MVT::Other; 8670 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2)); 8671 SmallVector<SDValue, 8> Ops; 8672 Ops.push_back(N->getOperand(0)); // incoming chain 8673 Ops.push_back(N->getOperand(AddrOpIdx)); 8674 Ops.push_back(Inc); 8675 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) { 8676 Ops.push_back(N->getOperand(i)); 8677 } 8678 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 8679 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, 8680 Ops.data(), Ops.size(), 8681 MemInt->getMemoryVT(), 8682 MemInt->getMemOperand()); 8683 8684 // Update the uses. 8685 std::vector<SDValue> NewResults; 8686 for (unsigned i = 0; i < NumResultVecs; ++i) { 8687 NewResults.push_back(SDValue(UpdN.getNode(), i)); 8688 } 8689 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain 8690 DCI.CombineTo(N, NewResults); 8691 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 8692 8693 break; 8694 } 8695 return SDValue(); 8696 } 8697 8698 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a 8699 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic 8700 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and 8701 /// return true. 8702 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 8703 SelectionDAG &DAG = DCI.DAG; 8704 EVT VT = N->getValueType(0); 8705 // vldN-dup instructions only support 64-bit vectors for N > 1. 8706 if (!VT.is64BitVector()) 8707 return false; 8708 8709 // Check if the VDUPLANE operand is a vldN-dup intrinsic. 8710 SDNode *VLD = N->getOperand(0).getNode(); 8711 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN) 8712 return false; 8713 unsigned NumVecs = 0; 8714 unsigned NewOpc = 0; 8715 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue(); 8716 if (IntNo == Intrinsic::arm_neon_vld2lane) { 8717 NumVecs = 2; 8718 NewOpc = ARMISD::VLD2DUP; 8719 } else if (IntNo == Intrinsic::arm_neon_vld3lane) { 8720 NumVecs = 3; 8721 NewOpc = ARMISD::VLD3DUP; 8722 } else if (IntNo == Intrinsic::arm_neon_vld4lane) { 8723 NumVecs = 4; 8724 NewOpc = ARMISD::VLD4DUP; 8725 } else { 8726 return false; 8727 } 8728 8729 // First check that all the vldN-lane uses are VDUPLANEs and that the lane 8730 // numbers match the load. 8731 unsigned VLDLaneNo = 8732 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue(); 8733 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 8734 UI != UE; ++UI) { 8735 // Ignore uses of the chain result. 8736 if (UI.getUse().getResNo() == NumVecs) 8737 continue; 8738 SDNode *User = *UI; 8739 if (User->getOpcode() != ARMISD::VDUPLANE || 8740 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue()) 8741 return false; 8742 } 8743 8744 // Create the vldN-dup node. 8745 EVT Tys[5]; 8746 unsigned n; 8747 for (n = 0; n < NumVecs; ++n) 8748 Tys[n] = VT; 8749 Tys[n] = MVT::Other; 8750 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1)); 8751 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) }; 8752 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD); 8753 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys, 8754 Ops, 2, VLDMemInt->getMemoryVT(), 8755 VLDMemInt->getMemOperand()); 8756 8757 // Update the uses. 8758 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end(); 8759 UI != UE; ++UI) { 8760 unsigned ResNo = UI.getUse().getResNo(); 8761 // Ignore uses of the chain result. 8762 if (ResNo == NumVecs) 8763 continue; 8764 SDNode *User = *UI; 8765 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo)); 8766 } 8767 8768 // Now the vldN-lane intrinsic is dead except for its chain result. 8769 // Update uses of the chain. 8770 std::vector<SDValue> VLDDupResults; 8771 for (unsigned n = 0; n < NumVecs; ++n) 8772 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n)); 8773 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs)); 8774 DCI.CombineTo(VLD, VLDDupResults); 8775 8776 return true; 8777 } 8778 8779 /// PerformVDUPLANECombine - Target-specific dag combine xforms for 8780 /// ARMISD::VDUPLANE. 8781 static SDValue PerformVDUPLANECombine(SDNode *N, 8782 TargetLowering::DAGCombinerInfo &DCI) { 8783 SDValue Op = N->getOperand(0); 8784 8785 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses 8786 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation. 8787 if (CombineVLDDUP(N, DCI)) 8788 return SDValue(N, 0); 8789 8790 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is 8791 // redundant. Ignore bit_converts for now; element sizes are checked below. 8792 while (Op.getOpcode() == ISD::BITCAST) 8793 Op = Op.getOperand(0); 8794 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM) 8795 return SDValue(); 8796 8797 // Make sure the VMOV element size is not bigger than the VDUPLANE elements. 8798 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits(); 8799 // The canonical VMOV for a zero vector uses a 32-bit element size. 8800 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8801 unsigned EltBits; 8802 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0) 8803 EltSize = 8; 8804 EVT VT = N->getValueType(0); 8805 if (EltSize > VT.getVectorElementType().getSizeInBits()) 8806 return SDValue(); 8807 8808 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 8809 } 8810 8811 // isConstVecPow2 - Return true if each vector element is a power of 2, all 8812 // elements are the same constant, C, and Log2(C) ranges from 1 to 32. 8813 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C) 8814 { 8815 integerPart cN; 8816 integerPart c0 = 0; 8817 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements(); 8818 I != E; I++) { 8819 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I)); 8820 if (!C) 8821 return false; 8822 8823 bool isExact; 8824 APFloat APF = C->getValueAPF(); 8825 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact) 8826 != APFloat::opOK || !isExact) 8827 return false; 8828 8829 c0 = (I == 0) ? cN : c0; 8830 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32) 8831 return false; 8832 } 8833 C = c0; 8834 return true; 8835 } 8836 8837 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD) 8838 /// can replace combinations of VMUL and VCVT (floating-point to integer) 8839 /// when the VMUL has a constant operand that is a power of 2. 8840 /// 8841 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 8842 /// vmul.f32 d16, d17, d16 8843 /// vcvt.s32.f32 d16, d16 8844 /// becomes: 8845 /// vcvt.s32.f32 d16, d16, #3 8846 static SDValue PerformVCVTCombine(SDNode *N, 8847 TargetLowering::DAGCombinerInfo &DCI, 8848 const ARMSubtarget *Subtarget) { 8849 SelectionDAG &DAG = DCI.DAG; 8850 SDValue Op = N->getOperand(0); 8851 8852 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() || 8853 Op.getOpcode() != ISD::FMUL) 8854 return SDValue(); 8855 8856 uint64_t C; 8857 SDValue N0 = Op->getOperand(0); 8858 SDValue ConstVec = Op->getOperand(1); 8859 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT; 8860 8861 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR || 8862 !isConstVecPow2(ConstVec, isSigned, C)) 8863 return SDValue(); 8864 8865 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 8866 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 8867 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) { 8868 // These instructions only exist converting from f32 to i32. We can handle 8869 // smaller integers by generating an extra truncate, but larger ones would 8870 // be lossy. 8871 return SDValue(); 8872 } 8873 8874 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs : 8875 Intrinsic::arm_neon_vcvtfp2fxu; 8876 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 8877 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), 8878 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 8879 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0, 8880 DAG.getConstant(Log2_64(C), MVT::i32)); 8881 8882 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits()) 8883 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv); 8884 8885 return FixConv; 8886 } 8887 8888 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD) 8889 /// can replace combinations of VCVT (integer to floating-point) and VDIV 8890 /// when the VDIV has a constant operand that is a power of 2. 8891 /// 8892 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>): 8893 /// vcvt.f32.s32 d16, d16 8894 /// vdiv.f32 d16, d17, d16 8895 /// becomes: 8896 /// vcvt.f32.s32 d16, d16, #3 8897 static SDValue PerformVDIVCombine(SDNode *N, 8898 TargetLowering::DAGCombinerInfo &DCI, 8899 const ARMSubtarget *Subtarget) { 8900 SelectionDAG &DAG = DCI.DAG; 8901 SDValue Op = N->getOperand(0); 8902 unsigned OpOpcode = Op.getNode()->getOpcode(); 8903 8904 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() || 8905 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP)) 8906 return SDValue(); 8907 8908 uint64_t C; 8909 SDValue ConstVec = N->getOperand(1); 8910 bool isSigned = OpOpcode == ISD::SINT_TO_FP; 8911 8912 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR || 8913 !isConstVecPow2(ConstVec, isSigned, C)) 8914 return SDValue(); 8915 8916 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 8917 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 8918 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) { 8919 // These instructions only exist converting from i32 to f32. We can handle 8920 // smaller integers by generating an extra extend, but larger ones would 8921 // be lossy. 8922 return SDValue(); 8923 } 8924 8925 SDValue ConvInput = Op.getOperand(0); 8926 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 8927 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits()) 8928 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8929 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, 8930 ConvInput); 8931 8932 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp : 8933 Intrinsic::arm_neon_vcvtfxu2fp; 8934 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), 8935 Op.getValueType(), 8936 DAG.getConstant(IntrinsicOpcode, MVT::i32), 8937 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32)); 8938 } 8939 8940 /// Getvshiftimm - Check if this is a valid build_vector for the immediate 8941 /// operand of a vector shift operation, where all the elements of the 8942 /// build_vector must have the same constant integer value. 8943 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 8944 // Ignore bit_converts. 8945 while (Op.getOpcode() == ISD::BITCAST) 8946 Op = Op.getOperand(0); 8947 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8948 APInt SplatBits, SplatUndef; 8949 unsigned SplatBitSize; 8950 bool HasAnyUndefs; 8951 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 8952 HasAnyUndefs, ElementBits) || 8953 SplatBitSize > ElementBits) 8954 return false; 8955 Cnt = SplatBits.getSExtValue(); 8956 return true; 8957 } 8958 8959 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 8960 /// operand of a vector shift left operation. That value must be in the range: 8961 /// 0 <= Value < ElementBits for a left shift; or 8962 /// 0 <= Value <= ElementBits for a long left shift. 8963 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 8964 assert(VT.isVector() && "vector shift count is not a vector type"); 8965 unsigned ElementBits = VT.getVectorElementType().getSizeInBits(); 8966 if (! getVShiftImm(Op, ElementBits, Cnt)) 8967 return false; 8968 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits); 8969 } 8970 8971 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 8972 /// operand of a vector shift right operation. For a shift opcode, the value 8973 /// is positive, but for an intrinsic the value count must be negative. The 8974 /// absolute value must be in the range: 8975 /// 1 <= |Value| <= ElementBits for a right shift; or 8976 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift. 8977 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic, 8978 int64_t &Cnt) { 8979 assert(VT.isVector() && "vector shift count is not a vector type"); 8980 unsigned ElementBits = VT.getVectorElementType().getSizeInBits(); 8981 if (! getVShiftImm(Op, ElementBits, Cnt)) 8982 return false; 8983 if (isIntrinsic) 8984 Cnt = -Cnt; 8985 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits)); 8986 } 8987 8988 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics. 8989 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) { 8990 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 8991 switch (IntNo) { 8992 default: 8993 // Don't do anything for most intrinsics. 8994 break; 8995 8996 // Vector shifts: check for immediate versions and lower them. 8997 // Note: This is done during DAG combining instead of DAG legalizing because 8998 // the build_vectors for 64-bit vector element shift counts are generally 8999 // not legal, and it is hard to see their values after they get legalized to 9000 // loads from a constant pool. 9001 case Intrinsic::arm_neon_vshifts: 9002 case Intrinsic::arm_neon_vshiftu: 9003 case Intrinsic::arm_neon_vrshifts: 9004 case Intrinsic::arm_neon_vrshiftu: 9005 case Intrinsic::arm_neon_vrshiftn: 9006 case Intrinsic::arm_neon_vqshifts: 9007 case Intrinsic::arm_neon_vqshiftu: 9008 case Intrinsic::arm_neon_vqshiftsu: 9009 case Intrinsic::arm_neon_vqshiftns: 9010 case Intrinsic::arm_neon_vqshiftnu: 9011 case Intrinsic::arm_neon_vqshiftnsu: 9012 case Intrinsic::arm_neon_vqrshiftns: 9013 case Intrinsic::arm_neon_vqrshiftnu: 9014 case Intrinsic::arm_neon_vqrshiftnsu: { 9015 EVT VT = N->getOperand(1).getValueType(); 9016 int64_t Cnt; 9017 unsigned VShiftOpc = 0; 9018 9019 switch (IntNo) { 9020 case Intrinsic::arm_neon_vshifts: 9021 case Intrinsic::arm_neon_vshiftu: 9022 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) { 9023 VShiftOpc = ARMISD::VSHL; 9024 break; 9025 } 9026 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) { 9027 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? 9028 ARMISD::VSHRs : ARMISD::VSHRu); 9029 break; 9030 } 9031 return SDValue(); 9032 9033 case Intrinsic::arm_neon_vrshifts: 9034 case Intrinsic::arm_neon_vrshiftu: 9035 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) 9036 break; 9037 return SDValue(); 9038 9039 case Intrinsic::arm_neon_vqshifts: 9040 case Intrinsic::arm_neon_vqshiftu: 9041 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 9042 break; 9043 return SDValue(); 9044 9045 case Intrinsic::arm_neon_vqshiftsu: 9046 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) 9047 break; 9048 llvm_unreachable("invalid shift count for vqshlu intrinsic"); 9049 9050 case Intrinsic::arm_neon_vrshiftn: 9051 case Intrinsic::arm_neon_vqshiftns: 9052 case Intrinsic::arm_neon_vqshiftnu: 9053 case Intrinsic::arm_neon_vqshiftnsu: 9054 case Intrinsic::arm_neon_vqrshiftns: 9055 case Intrinsic::arm_neon_vqrshiftnu: 9056 case Intrinsic::arm_neon_vqrshiftnsu: 9057 // Narrowing shifts require an immediate right shift. 9058 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt)) 9059 break; 9060 llvm_unreachable("invalid shift count for narrowing vector shift " 9061 "intrinsic"); 9062 9063 default: 9064 llvm_unreachable("unhandled vector shift"); 9065 } 9066 9067 switch (IntNo) { 9068 case Intrinsic::arm_neon_vshifts: 9069 case Intrinsic::arm_neon_vshiftu: 9070 // Opcode already set above. 9071 break; 9072 case Intrinsic::arm_neon_vrshifts: 9073 VShiftOpc = ARMISD::VRSHRs; break; 9074 case Intrinsic::arm_neon_vrshiftu: 9075 VShiftOpc = ARMISD::VRSHRu; break; 9076 case Intrinsic::arm_neon_vrshiftn: 9077 VShiftOpc = ARMISD::VRSHRN; break; 9078 case Intrinsic::arm_neon_vqshifts: 9079 VShiftOpc = ARMISD::VQSHLs; break; 9080 case Intrinsic::arm_neon_vqshiftu: 9081 VShiftOpc = ARMISD::VQSHLu; break; 9082 case Intrinsic::arm_neon_vqshiftsu: 9083 VShiftOpc = ARMISD::VQSHLsu; break; 9084 case Intrinsic::arm_neon_vqshiftns: 9085 VShiftOpc = ARMISD::VQSHRNs; break; 9086 case Intrinsic::arm_neon_vqshiftnu: 9087 VShiftOpc = ARMISD::VQSHRNu; break; 9088 case Intrinsic::arm_neon_vqshiftnsu: 9089 VShiftOpc = ARMISD::VQSHRNsu; break; 9090 case Intrinsic::arm_neon_vqrshiftns: 9091 VShiftOpc = ARMISD::VQRSHRNs; break; 9092 case Intrinsic::arm_neon_vqrshiftnu: 9093 VShiftOpc = ARMISD::VQRSHRNu; break; 9094 case Intrinsic::arm_neon_vqrshiftnsu: 9095 VShiftOpc = ARMISD::VQRSHRNsu; break; 9096 } 9097 9098 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0), 9099 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32)); 9100 } 9101 9102 case Intrinsic::arm_neon_vshiftins: { 9103 EVT VT = N->getOperand(1).getValueType(); 9104 int64_t Cnt; 9105 unsigned VShiftOpc = 0; 9106 9107 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt)) 9108 VShiftOpc = ARMISD::VSLI; 9109 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt)) 9110 VShiftOpc = ARMISD::VSRI; 9111 else { 9112 llvm_unreachable("invalid shift count for vsli/vsri intrinsic"); 9113 } 9114 9115 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0), 9116 N->getOperand(1), N->getOperand(2), 9117 DAG.getConstant(Cnt, MVT::i32)); 9118 } 9119 9120 case Intrinsic::arm_neon_vqrshifts: 9121 case Intrinsic::arm_neon_vqrshiftu: 9122 // No immediate versions of these to check for. 9123 break; 9124 } 9125 9126 return SDValue(); 9127 } 9128 9129 /// PerformShiftCombine - Checks for immediate versions of vector shifts and 9130 /// lowers them. As with the vector shift intrinsics, this is done during DAG 9131 /// combining instead of DAG legalizing because the build_vectors for 64-bit 9132 /// vector element shift counts are generally not legal, and it is hard to see 9133 /// their values after they get legalized to loads from a constant pool. 9134 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG, 9135 const ARMSubtarget *ST) { 9136 EVT VT = N->getValueType(0); 9137 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) { 9138 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high 9139 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16. 9140 SDValue N1 = N->getOperand(1); 9141 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 9142 SDValue N0 = N->getOperand(0); 9143 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP && 9144 DAG.MaskedValueIsZero(N0.getOperand(0), 9145 APInt::getHighBitsSet(32, 16))) 9146 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1); 9147 } 9148 } 9149 9150 // Nothing to be done for scalar shifts. 9151 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9152 if (!VT.isVector() || !TLI.isTypeLegal(VT)) 9153 return SDValue(); 9154 9155 assert(ST->hasNEON() && "unexpected vector shift"); 9156 int64_t Cnt; 9157 9158 switch (N->getOpcode()) { 9159 default: llvm_unreachable("unexpected shift opcode"); 9160 9161 case ISD::SHL: 9162 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) 9163 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0), 9164 DAG.getConstant(Cnt, MVT::i32)); 9165 break; 9166 9167 case ISD::SRA: 9168 case ISD::SRL: 9169 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) { 9170 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ? 9171 ARMISD::VSHRs : ARMISD::VSHRu); 9172 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0), 9173 DAG.getConstant(Cnt, MVT::i32)); 9174 } 9175 } 9176 return SDValue(); 9177 } 9178 9179 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND, 9180 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND. 9181 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG, 9182 const ARMSubtarget *ST) { 9183 SDValue N0 = N->getOperand(0); 9184 9185 // Check for sign- and zero-extensions of vector extract operations of 8- 9186 // and 16-bit vector elements. NEON supports these directly. They are 9187 // handled during DAG combining because type legalization will promote them 9188 // to 32-bit types and it is messy to recognize the operations after that. 9189 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9190 SDValue Vec = N0.getOperand(0); 9191 SDValue Lane = N0.getOperand(1); 9192 EVT VT = N->getValueType(0); 9193 EVT EltVT = N0.getValueType(); 9194 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9195 9196 if (VT == MVT::i32 && 9197 (EltVT == MVT::i8 || EltVT == MVT::i16) && 9198 TLI.isTypeLegal(Vec.getValueType()) && 9199 isa<ConstantSDNode>(Lane)) { 9200 9201 unsigned Opc = 0; 9202 switch (N->getOpcode()) { 9203 default: llvm_unreachable("unexpected opcode"); 9204 case ISD::SIGN_EXTEND: 9205 Opc = ARMISD::VGETLANEs; 9206 break; 9207 case ISD::ZERO_EXTEND: 9208 case ISD::ANY_EXTEND: 9209 Opc = ARMISD::VGETLANEu; 9210 break; 9211 } 9212 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane); 9213 } 9214 } 9215 9216 return SDValue(); 9217 } 9218 9219 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC 9220 /// to match f32 max/min patterns to use NEON vmax/vmin instructions. 9221 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG, 9222 const ARMSubtarget *ST) { 9223 // If the target supports NEON, try to use vmax/vmin instructions for f32 9224 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set, 9225 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is 9226 // a NaN; only do the transformation when it matches that behavior. 9227 9228 // For now only do this when using NEON for FP operations; if using VFP, it 9229 // is not obvious that the benefit outweighs the cost of switching to the 9230 // NEON pipeline. 9231 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() || 9232 N->getValueType(0) != MVT::f32) 9233 return SDValue(); 9234 9235 SDValue CondLHS = N->getOperand(0); 9236 SDValue CondRHS = N->getOperand(1); 9237 SDValue LHS = N->getOperand(2); 9238 SDValue RHS = N->getOperand(3); 9239 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get(); 9240 9241 unsigned Opcode = 0; 9242 bool IsReversed; 9243 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) { 9244 IsReversed = false; // x CC y ? x : y 9245 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) { 9246 IsReversed = true ; // x CC y ? y : x 9247 } else { 9248 return SDValue(); 9249 } 9250 9251 bool IsUnordered; 9252 switch (CC) { 9253 default: break; 9254 case ISD::SETOLT: 9255 case ISD::SETOLE: 9256 case ISD::SETLT: 9257 case ISD::SETLE: 9258 case ISD::SETULT: 9259 case ISD::SETULE: 9260 // If LHS is NaN, an ordered comparison will be false and the result will 9261 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS 9262 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN. 9263 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE); 9264 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS)) 9265 break; 9266 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin 9267 // will return -0, so vmin can only be used for unsafe math or if one of 9268 // the operands is known to be nonzero. 9269 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) && 9270 !DAG.getTarget().Options.UnsafeFPMath && 9271 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 9272 break; 9273 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN; 9274 break; 9275 9276 case ISD::SETOGT: 9277 case ISD::SETOGE: 9278 case ISD::SETGT: 9279 case ISD::SETGE: 9280 case ISD::SETUGT: 9281 case ISD::SETUGE: 9282 // If LHS is NaN, an ordered comparison will be false and the result will 9283 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS 9284 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN. 9285 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE); 9286 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS)) 9287 break; 9288 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax 9289 // will return +0, so vmax can only be used for unsafe math or if one of 9290 // the operands is known to be nonzero. 9291 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) && 9292 !DAG.getTarget().Options.UnsafeFPMath && 9293 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 9294 break; 9295 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX; 9296 break; 9297 } 9298 9299 if (!Opcode) 9300 return SDValue(); 9301 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS); 9302 } 9303 9304 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV. 9305 SDValue 9306 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const { 9307 SDValue Cmp = N->getOperand(4); 9308 if (Cmp.getOpcode() != ARMISD::CMPZ) 9309 // Only looking at EQ and NE cases. 9310 return SDValue(); 9311 9312 EVT VT = N->getValueType(0); 9313 SDLoc dl(N); 9314 SDValue LHS = Cmp.getOperand(0); 9315 SDValue RHS = Cmp.getOperand(1); 9316 SDValue FalseVal = N->getOperand(0); 9317 SDValue TrueVal = N->getOperand(1); 9318 SDValue ARMcc = N->getOperand(2); 9319 ARMCC::CondCodes CC = 9320 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue(); 9321 9322 // Simplify 9323 // mov r1, r0 9324 // cmp r1, x 9325 // mov r0, y 9326 // moveq r0, x 9327 // to 9328 // cmp r0, x 9329 // movne r0, y 9330 // 9331 // mov r1, r0 9332 // cmp r1, x 9333 // mov r0, x 9334 // movne r0, y 9335 // to 9336 // cmp r0, x 9337 // movne r0, y 9338 /// FIXME: Turn this into a target neutral optimization? 9339 SDValue Res; 9340 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) { 9341 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, 9342 N->getOperand(3), Cmp); 9343 } else if (CC == ARMCC::EQ && TrueVal == RHS) { 9344 SDValue ARMcc; 9345 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl); 9346 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, 9347 N->getOperand(3), NewCmp); 9348 } 9349 9350 if (Res.getNode()) { 9351 APInt KnownZero, KnownOne; 9352 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne); 9353 // Capture demanded bits information that would be otherwise lost. 9354 if (KnownZero == 0xfffffffe) 9355 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 9356 DAG.getValueType(MVT::i1)); 9357 else if (KnownZero == 0xffffff00) 9358 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 9359 DAG.getValueType(MVT::i8)); 9360 else if (KnownZero == 0xffff0000) 9361 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res, 9362 DAG.getValueType(MVT::i16)); 9363 } 9364 9365 return Res; 9366 } 9367 9368 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N, 9369 DAGCombinerInfo &DCI) const { 9370 switch (N->getOpcode()) { 9371 default: break; 9372 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget); 9373 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget); 9374 case ISD::SUB: return PerformSUBCombine(N, DCI); 9375 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget); 9376 case ISD::OR: return PerformORCombine(N, DCI, Subtarget); 9377 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget); 9378 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget); 9379 case ARMISD::BFI: return PerformBFICombine(N, DCI); 9380 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI); 9381 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG); 9382 case ISD::STORE: return PerformSTORECombine(N, DCI); 9383 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI); 9384 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI); 9385 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG); 9386 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI); 9387 case ISD::FP_TO_SINT: 9388 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget); 9389 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget); 9390 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG); 9391 case ISD::SHL: 9392 case ISD::SRA: 9393 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget); 9394 case ISD::SIGN_EXTEND: 9395 case ISD::ZERO_EXTEND: 9396 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget); 9397 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget); 9398 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG); 9399 case ARMISD::VLD2DUP: 9400 case ARMISD::VLD3DUP: 9401 case ARMISD::VLD4DUP: 9402 return CombineBaseUpdate(N, DCI); 9403 case ARMISD::BUILD_VECTOR: 9404 return PerformARMBUILD_VECTORCombine(N, DCI); 9405 case ISD::INTRINSIC_VOID: 9406 case ISD::INTRINSIC_W_CHAIN: 9407 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 9408 case Intrinsic::arm_neon_vld1: 9409 case Intrinsic::arm_neon_vld2: 9410 case Intrinsic::arm_neon_vld3: 9411 case Intrinsic::arm_neon_vld4: 9412 case Intrinsic::arm_neon_vld2lane: 9413 case Intrinsic::arm_neon_vld3lane: 9414 case Intrinsic::arm_neon_vld4lane: 9415 case Intrinsic::arm_neon_vst1: 9416 case Intrinsic::arm_neon_vst2: 9417 case Intrinsic::arm_neon_vst3: 9418 case Intrinsic::arm_neon_vst4: 9419 case Intrinsic::arm_neon_vst2lane: 9420 case Intrinsic::arm_neon_vst3lane: 9421 case Intrinsic::arm_neon_vst4lane: 9422 return CombineBaseUpdate(N, DCI); 9423 default: break; 9424 } 9425 break; 9426 } 9427 return SDValue(); 9428 } 9429 9430 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc, 9431 EVT VT) const { 9432 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE); 9433 } 9434 9435 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned, 9436 bool *Fast) const { 9437 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus 9438 bool AllowsUnaligned = Subtarget->allowsUnalignedMem(); 9439 9440 switch (VT.getSimpleVT().SimpleTy) { 9441 default: 9442 return false; 9443 case MVT::i8: 9444 case MVT::i16: 9445 case MVT::i32: { 9446 // Unaligned access can use (for example) LRDB, LRDH, LDR 9447 if (AllowsUnaligned) { 9448 if (Fast) 9449 *Fast = Subtarget->hasV7Ops(); 9450 return true; 9451 } 9452 return false; 9453 } 9454 case MVT::f64: 9455 case MVT::v2f64: { 9456 // For any little-endian targets with neon, we can support unaligned ld/st 9457 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8. 9458 // A big-endian target may also explicitly support unaligned accesses 9459 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) { 9460 if (Fast) 9461 *Fast = true; 9462 return true; 9463 } 9464 return false; 9465 } 9466 } 9467 } 9468 9469 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 9470 unsigned AlignCheck) { 9471 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 9472 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 9473 } 9474 9475 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size, 9476 unsigned DstAlign, unsigned SrcAlign, 9477 bool IsMemset, bool ZeroMemset, 9478 bool MemcpyStrSrc, 9479 MachineFunction &MF) const { 9480 const Function *F = MF.getFunction(); 9481 9482 // See if we can use NEON instructions for this... 9483 if ((!IsMemset || ZeroMemset) && 9484 Subtarget->hasNEON() && 9485 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 9486 Attribute::NoImplicitFloat)) { 9487 bool Fast; 9488 if (Size >= 16 && 9489 (memOpAlign(SrcAlign, DstAlign, 16) || 9490 (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) { 9491 return MVT::v2f64; 9492 } else if (Size >= 8 && 9493 (memOpAlign(SrcAlign, DstAlign, 8) || 9494 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) { 9495 return MVT::f64; 9496 } 9497 } 9498 9499 // Lowering to i32/i16 if the size permits. 9500 if (Size >= 4) 9501 return MVT::i32; 9502 else if (Size >= 2) 9503 return MVT::i16; 9504 9505 // Let the target-independent logic figure it out. 9506 return MVT::Other; 9507 } 9508 9509 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 9510 if (Val.getOpcode() != ISD::LOAD) 9511 return false; 9512 9513 EVT VT1 = Val.getValueType(); 9514 if (!VT1.isSimple() || !VT1.isInteger() || 9515 !VT2.isSimple() || !VT2.isInteger()) 9516 return false; 9517 9518 switch (VT1.getSimpleVT().SimpleTy) { 9519 default: break; 9520 case MVT::i1: 9521 case MVT::i8: 9522 case MVT::i16: 9523 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits. 9524 return true; 9525 } 9526 9527 return false; 9528 } 9529 9530 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 9531 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 9532 return false; 9533 9534 if (!isTypeLegal(EVT::getEVT(Ty1))) 9535 return false; 9536 9537 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 9538 9539 // Assuming the caller doesn't have a zeroext or signext return parameter, 9540 // truncation all the way down to i1 is valid. 9541 return true; 9542 } 9543 9544 9545 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) { 9546 if (V < 0) 9547 return false; 9548 9549 unsigned Scale = 1; 9550 switch (VT.getSimpleVT().SimpleTy) { 9551 default: return false; 9552 case MVT::i1: 9553 case MVT::i8: 9554 // Scale == 1; 9555 break; 9556 case MVT::i16: 9557 // Scale == 2; 9558 Scale = 2; 9559 break; 9560 case MVT::i32: 9561 // Scale == 4; 9562 Scale = 4; 9563 break; 9564 } 9565 9566 if ((V & (Scale - 1)) != 0) 9567 return false; 9568 V /= Scale; 9569 return V == (V & ((1LL << 5) - 1)); 9570 } 9571 9572 static bool isLegalT2AddressImmediate(int64_t V, EVT VT, 9573 const ARMSubtarget *Subtarget) { 9574 bool isNeg = false; 9575 if (V < 0) { 9576 isNeg = true; 9577 V = - V; 9578 } 9579 9580 switch (VT.getSimpleVT().SimpleTy) { 9581 default: return false; 9582 case MVT::i1: 9583 case MVT::i8: 9584 case MVT::i16: 9585 case MVT::i32: 9586 // + imm12 or - imm8 9587 if (isNeg) 9588 return V == (V & ((1LL << 8) - 1)); 9589 return V == (V & ((1LL << 12) - 1)); 9590 case MVT::f32: 9591 case MVT::f64: 9592 // Same as ARM mode. FIXME: NEON? 9593 if (!Subtarget->hasVFP2()) 9594 return false; 9595 if ((V & 3) != 0) 9596 return false; 9597 V >>= 2; 9598 return V == (V & ((1LL << 8) - 1)); 9599 } 9600 } 9601 9602 /// isLegalAddressImmediate - Return true if the integer value can be used 9603 /// as the offset of the target addressing mode for load / store of the 9604 /// given type. 9605 static bool isLegalAddressImmediate(int64_t V, EVT VT, 9606 const ARMSubtarget *Subtarget) { 9607 if (V == 0) 9608 return true; 9609 9610 if (!VT.isSimple()) 9611 return false; 9612 9613 if (Subtarget->isThumb1Only()) 9614 return isLegalT1AddressImmediate(V, VT); 9615 else if (Subtarget->isThumb2()) 9616 return isLegalT2AddressImmediate(V, VT, Subtarget); 9617 9618 // ARM mode. 9619 if (V < 0) 9620 V = - V; 9621 switch (VT.getSimpleVT().SimpleTy) { 9622 default: return false; 9623 case MVT::i1: 9624 case MVT::i8: 9625 case MVT::i32: 9626 // +- imm12 9627 return V == (V & ((1LL << 12) - 1)); 9628 case MVT::i16: 9629 // +- imm8 9630 return V == (V & ((1LL << 8) - 1)); 9631 case MVT::f32: 9632 case MVT::f64: 9633 if (!Subtarget->hasVFP2()) // FIXME: NEON? 9634 return false; 9635 if ((V & 3) != 0) 9636 return false; 9637 V >>= 2; 9638 return V == (V & ((1LL << 8) - 1)); 9639 } 9640 } 9641 9642 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM, 9643 EVT VT) const { 9644 int Scale = AM.Scale; 9645 if (Scale < 0) 9646 return false; 9647 9648 switch (VT.getSimpleVT().SimpleTy) { 9649 default: return false; 9650 case MVT::i1: 9651 case MVT::i8: 9652 case MVT::i16: 9653 case MVT::i32: 9654 if (Scale == 1) 9655 return true; 9656 // r + r << imm 9657 Scale = Scale & ~1; 9658 return Scale == 2 || Scale == 4 || Scale == 8; 9659 case MVT::i64: 9660 // r + r 9661 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 9662 return true; 9663 return false; 9664 case MVT::isVoid: 9665 // Note, we allow "void" uses (basically, uses that aren't loads or 9666 // stores), because arm allows folding a scale into many arithmetic 9667 // operations. This should be made more precise and revisited later. 9668 9669 // Allow r << imm, but the imm has to be a multiple of two. 9670 if (Scale & 1) return false; 9671 return isPowerOf2_32(Scale); 9672 } 9673 } 9674 9675 /// isLegalAddressingMode - Return true if the addressing mode represented 9676 /// by AM is legal for this target, for a load/store of the specified type. 9677 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM, 9678 Type *Ty) const { 9679 EVT VT = getValueType(Ty, true); 9680 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget)) 9681 return false; 9682 9683 // Can never fold addr of global into load/store. 9684 if (AM.BaseGV) 9685 return false; 9686 9687 switch (AM.Scale) { 9688 case 0: // no scale reg, must be "r+i" or "r", or "i". 9689 break; 9690 case 1: 9691 if (Subtarget->isThumb1Only()) 9692 return false; 9693 // FALL THROUGH. 9694 default: 9695 // ARM doesn't support any R+R*scale+imm addr modes. 9696 if (AM.BaseOffs) 9697 return false; 9698 9699 if (!VT.isSimple()) 9700 return false; 9701 9702 if (Subtarget->isThumb2()) 9703 return isLegalT2ScaledAddressingMode(AM, VT); 9704 9705 int Scale = AM.Scale; 9706 switch (VT.getSimpleVT().SimpleTy) { 9707 default: return false; 9708 case MVT::i1: 9709 case MVT::i8: 9710 case MVT::i32: 9711 if (Scale < 0) Scale = -Scale; 9712 if (Scale == 1) 9713 return true; 9714 // r + r << imm 9715 return isPowerOf2_32(Scale & ~1); 9716 case MVT::i16: 9717 case MVT::i64: 9718 // r + r 9719 if (((unsigned)AM.HasBaseReg + Scale) <= 2) 9720 return true; 9721 return false; 9722 9723 case MVT::isVoid: 9724 // Note, we allow "void" uses (basically, uses that aren't loads or 9725 // stores), because arm allows folding a scale into many arithmetic 9726 // operations. This should be made more precise and revisited later. 9727 9728 // Allow r << imm, but the imm has to be a multiple of two. 9729 if (Scale & 1) return false; 9730 return isPowerOf2_32(Scale); 9731 } 9732 } 9733 return true; 9734 } 9735 9736 /// isLegalICmpImmediate - Return true if the specified immediate is legal 9737 /// icmp immediate, that is the target has icmp instructions which can compare 9738 /// a register against the immediate without having to materialize the 9739 /// immediate into a register. 9740 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 9741 // Thumb2 and ARM modes can use cmn for negative immediates. 9742 if (!Subtarget->isThumb()) 9743 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1; 9744 if (Subtarget->isThumb2()) 9745 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1; 9746 // Thumb1 doesn't have cmn, and only 8-bit immediates. 9747 return Imm >= 0 && Imm <= 255; 9748 } 9749 9750 /// isLegalAddImmediate - Return true if the specified immediate is a legal add 9751 /// *or sub* immediate, that is the target has add or sub instructions which can 9752 /// add a register with the immediate without having to materialize the 9753 /// immediate into a register. 9754 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const { 9755 // Same encoding for add/sub, just flip the sign. 9756 int64_t AbsImm = llvm::abs64(Imm); 9757 if (!Subtarget->isThumb()) 9758 return ARM_AM::getSOImmVal(AbsImm) != -1; 9759 if (Subtarget->isThumb2()) 9760 return ARM_AM::getT2SOImmVal(AbsImm) != -1; 9761 // Thumb1 only has 8-bit unsigned immediate. 9762 return AbsImm >= 0 && AbsImm <= 255; 9763 } 9764 9765 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT, 9766 bool isSEXTLoad, SDValue &Base, 9767 SDValue &Offset, bool &isInc, 9768 SelectionDAG &DAG) { 9769 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 9770 return false; 9771 9772 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) { 9773 // AddressingMode 3 9774 Base = Ptr->getOperand(0); 9775 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 9776 int RHSC = (int)RHS->getZExtValue(); 9777 if (RHSC < 0 && RHSC > -256) { 9778 assert(Ptr->getOpcode() == ISD::ADD); 9779 isInc = false; 9780 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0)); 9781 return true; 9782 } 9783 } 9784 isInc = (Ptr->getOpcode() == ISD::ADD); 9785 Offset = Ptr->getOperand(1); 9786 return true; 9787 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) { 9788 // AddressingMode 2 9789 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 9790 int RHSC = (int)RHS->getZExtValue(); 9791 if (RHSC < 0 && RHSC > -0x1000) { 9792 assert(Ptr->getOpcode() == ISD::ADD); 9793 isInc = false; 9794 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0)); 9795 Base = Ptr->getOperand(0); 9796 return true; 9797 } 9798 } 9799 9800 if (Ptr->getOpcode() == ISD::ADD) { 9801 isInc = true; 9802 ARM_AM::ShiftOpc ShOpcVal= 9803 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode()); 9804 if (ShOpcVal != ARM_AM::no_shift) { 9805 Base = Ptr->getOperand(1); 9806 Offset = Ptr->getOperand(0); 9807 } else { 9808 Base = Ptr->getOperand(0); 9809 Offset = Ptr->getOperand(1); 9810 } 9811 return true; 9812 } 9813 9814 isInc = (Ptr->getOpcode() == ISD::ADD); 9815 Base = Ptr->getOperand(0); 9816 Offset = Ptr->getOperand(1); 9817 return true; 9818 } 9819 9820 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store. 9821 return false; 9822 } 9823 9824 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT, 9825 bool isSEXTLoad, SDValue &Base, 9826 SDValue &Offset, bool &isInc, 9827 SelectionDAG &DAG) { 9828 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB) 9829 return false; 9830 9831 Base = Ptr->getOperand(0); 9832 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) { 9833 int RHSC = (int)RHS->getZExtValue(); 9834 if (RHSC < 0 && RHSC > -0x100) { // 8 bits. 9835 assert(Ptr->getOpcode() == ISD::ADD); 9836 isInc = false; 9837 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0)); 9838 return true; 9839 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero. 9840 isInc = Ptr->getOpcode() == ISD::ADD; 9841 Offset = DAG.getConstant(RHSC, RHS->getValueType(0)); 9842 return true; 9843 } 9844 } 9845 9846 return false; 9847 } 9848 9849 /// getPreIndexedAddressParts - returns true by value, base pointer and 9850 /// offset pointer and addressing mode by reference if the node's address 9851 /// can be legally represented as pre-indexed load / store address. 9852 bool 9853 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 9854 SDValue &Offset, 9855 ISD::MemIndexedMode &AM, 9856 SelectionDAG &DAG) const { 9857 if (Subtarget->isThumb1Only()) 9858 return false; 9859 9860 EVT VT; 9861 SDValue Ptr; 9862 bool isSEXTLoad = false; 9863 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9864 Ptr = LD->getBasePtr(); 9865 VT = LD->getMemoryVT(); 9866 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 9867 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9868 Ptr = ST->getBasePtr(); 9869 VT = ST->getMemoryVT(); 9870 } else 9871 return false; 9872 9873 bool isInc; 9874 bool isLegal = false; 9875 if (Subtarget->isThumb2()) 9876 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 9877 Offset, isInc, DAG); 9878 else 9879 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, 9880 Offset, isInc, DAG); 9881 if (!isLegal) 9882 return false; 9883 9884 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC; 9885 return true; 9886 } 9887 9888 /// getPostIndexedAddressParts - returns true by value, base pointer and 9889 /// offset pointer and addressing mode by reference if this node can be 9890 /// combined with a load / store to form a post-indexed load / store. 9891 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op, 9892 SDValue &Base, 9893 SDValue &Offset, 9894 ISD::MemIndexedMode &AM, 9895 SelectionDAG &DAG) const { 9896 if (Subtarget->isThumb1Only()) 9897 return false; 9898 9899 EVT VT; 9900 SDValue Ptr; 9901 bool isSEXTLoad = false; 9902 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9903 VT = LD->getMemoryVT(); 9904 Ptr = LD->getBasePtr(); 9905 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD; 9906 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9907 VT = ST->getMemoryVT(); 9908 Ptr = ST->getBasePtr(); 9909 } else 9910 return false; 9911 9912 bool isInc; 9913 bool isLegal = false; 9914 if (Subtarget->isThumb2()) 9915 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 9916 isInc, DAG); 9917 else 9918 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset, 9919 isInc, DAG); 9920 if (!isLegal) 9921 return false; 9922 9923 if (Ptr != Base) { 9924 // Swap base ptr and offset to catch more post-index load / store when 9925 // it's legal. In Thumb2 mode, offset must be an immediate. 9926 if (Ptr == Offset && Op->getOpcode() == ISD::ADD && 9927 !Subtarget->isThumb2()) 9928 std::swap(Base, Offset); 9929 9930 // Post-indexed load / store update the base pointer. 9931 if (Ptr != Base) 9932 return false; 9933 } 9934 9935 AM = isInc ? ISD::POST_INC : ISD::POST_DEC; 9936 return true; 9937 } 9938 9939 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 9940 APInt &KnownZero, 9941 APInt &KnownOne, 9942 const SelectionDAG &DAG, 9943 unsigned Depth) const { 9944 unsigned BitWidth = KnownOne.getBitWidth(); 9945 KnownZero = KnownOne = APInt(BitWidth, 0); 9946 switch (Op.getOpcode()) { 9947 default: break; 9948 case ARMISD::ADDC: 9949 case ARMISD::ADDE: 9950 case ARMISD::SUBC: 9951 case ARMISD::SUBE: 9952 // These nodes' second result is a boolean 9953 if (Op.getResNo() == 0) 9954 break; 9955 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 9956 break; 9957 case ARMISD::CMOV: { 9958 // Bits are known zero/one if known on the LHS and RHS. 9959 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 9960 if (KnownZero == 0 && KnownOne == 0) return; 9961 9962 APInt KnownZeroRHS, KnownOneRHS; 9963 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1); 9964 KnownZero &= KnownZeroRHS; 9965 KnownOne &= KnownOneRHS; 9966 return; 9967 } 9968 case ISD::INTRINSIC_W_CHAIN: { 9969 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 9970 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 9971 switch (IntID) { 9972 default: return; 9973 case Intrinsic::arm_ldaex: 9974 case Intrinsic::arm_ldrex: { 9975 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 9976 unsigned MemBits = VT.getScalarType().getSizeInBits(); 9977 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 9978 return; 9979 } 9980 } 9981 } 9982 } 9983 } 9984 9985 //===----------------------------------------------------------------------===// 9986 // ARM Inline Assembly Support 9987 //===----------------------------------------------------------------------===// 9988 9989 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const { 9990 // Looking for "rev" which is V6+. 9991 if (!Subtarget->hasV6Ops()) 9992 return false; 9993 9994 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 9995 std::string AsmStr = IA->getAsmString(); 9996 SmallVector<StringRef, 4> AsmPieces; 9997 SplitString(AsmStr, AsmPieces, ";\n"); 9998 9999 switch (AsmPieces.size()) { 10000 default: return false; 10001 case 1: 10002 AsmStr = AsmPieces[0]; 10003 AsmPieces.clear(); 10004 SplitString(AsmStr, AsmPieces, " \t,"); 10005 10006 // rev $0, $1 10007 if (AsmPieces.size() == 3 && 10008 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" && 10009 IA->getConstraintString().compare(0, 4, "=l,l") == 0) { 10010 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 10011 if (Ty && Ty->getBitWidth() == 32) 10012 return IntrinsicLowering::LowerToByteSwap(CI); 10013 } 10014 break; 10015 } 10016 10017 return false; 10018 } 10019 10020 /// getConstraintType - Given a constraint letter, return the type of 10021 /// constraint it is for this target. 10022 ARMTargetLowering::ConstraintType 10023 ARMTargetLowering::getConstraintType(const std::string &Constraint) const { 10024 if (Constraint.size() == 1) { 10025 switch (Constraint[0]) { 10026 default: break; 10027 case 'l': return C_RegisterClass; 10028 case 'w': return C_RegisterClass; 10029 case 'h': return C_RegisterClass; 10030 case 'x': return C_RegisterClass; 10031 case 't': return C_RegisterClass; 10032 case 'j': return C_Other; // Constant for movw. 10033 // An address with a single base register. Due to the way we 10034 // currently handle addresses it is the same as an 'r' memory constraint. 10035 case 'Q': return C_Memory; 10036 } 10037 } else if (Constraint.size() == 2) { 10038 switch (Constraint[0]) { 10039 default: break; 10040 // All 'U+' constraints are addresses. 10041 case 'U': return C_Memory; 10042 } 10043 } 10044 return TargetLowering::getConstraintType(Constraint); 10045 } 10046 10047 /// Examine constraint type and operand type and determine a weight value. 10048 /// This object must already have been set up with the operand type 10049 /// and the current alternative constraint selected. 10050 TargetLowering::ConstraintWeight 10051 ARMTargetLowering::getSingleConstraintMatchWeight( 10052 AsmOperandInfo &info, const char *constraint) const { 10053 ConstraintWeight weight = CW_Invalid; 10054 Value *CallOperandVal = info.CallOperandVal; 10055 // If we don't have a value, we can't do a match, 10056 // but allow it at the lowest weight. 10057 if (CallOperandVal == NULL) 10058 return CW_Default; 10059 Type *type = CallOperandVal->getType(); 10060 // Look at the constraint type. 10061 switch (*constraint) { 10062 default: 10063 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 10064 break; 10065 case 'l': 10066 if (type->isIntegerTy()) { 10067 if (Subtarget->isThumb()) 10068 weight = CW_SpecificReg; 10069 else 10070 weight = CW_Register; 10071 } 10072 break; 10073 case 'w': 10074 if (type->isFloatingPointTy()) 10075 weight = CW_Register; 10076 break; 10077 } 10078 return weight; 10079 } 10080 10081 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair; 10082 RCPair 10083 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 10084 MVT VT) const { 10085 if (Constraint.size() == 1) { 10086 // GCC ARM Constraint Letters 10087 switch (Constraint[0]) { 10088 case 'l': // Low regs or general regs. 10089 if (Subtarget->isThumb()) 10090 return RCPair(0U, &ARM::tGPRRegClass); 10091 return RCPair(0U, &ARM::GPRRegClass); 10092 case 'h': // High regs or no regs. 10093 if (Subtarget->isThumb()) 10094 return RCPair(0U, &ARM::hGPRRegClass); 10095 break; 10096 case 'r': 10097 return RCPair(0U, &ARM::GPRRegClass); 10098 case 'w': 10099 if (VT == MVT::Other) 10100 break; 10101 if (VT == MVT::f32) 10102 return RCPair(0U, &ARM::SPRRegClass); 10103 if (VT.getSizeInBits() == 64) 10104 return RCPair(0U, &ARM::DPRRegClass); 10105 if (VT.getSizeInBits() == 128) 10106 return RCPair(0U, &ARM::QPRRegClass); 10107 break; 10108 case 'x': 10109 if (VT == MVT::Other) 10110 break; 10111 if (VT == MVT::f32) 10112 return RCPair(0U, &ARM::SPR_8RegClass); 10113 if (VT.getSizeInBits() == 64) 10114 return RCPair(0U, &ARM::DPR_8RegClass); 10115 if (VT.getSizeInBits() == 128) 10116 return RCPair(0U, &ARM::QPR_8RegClass); 10117 break; 10118 case 't': 10119 if (VT == MVT::f32) 10120 return RCPair(0U, &ARM::SPRRegClass); 10121 break; 10122 } 10123 } 10124 if (StringRef("{cc}").equals_lower(Constraint)) 10125 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass); 10126 10127 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 10128 } 10129 10130 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 10131 /// vector. If it is invalid, don't add anything to Ops. 10132 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 10133 std::string &Constraint, 10134 std::vector<SDValue>&Ops, 10135 SelectionDAG &DAG) const { 10136 SDValue Result(0, 0); 10137 10138 // Currently only support length 1 constraints. 10139 if (Constraint.length() != 1) return; 10140 10141 char ConstraintLetter = Constraint[0]; 10142 switch (ConstraintLetter) { 10143 default: break; 10144 case 'j': 10145 case 'I': case 'J': case 'K': case 'L': 10146 case 'M': case 'N': case 'O': 10147 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 10148 if (!C) 10149 return; 10150 10151 int64_t CVal64 = C->getSExtValue(); 10152 int CVal = (int) CVal64; 10153 // None of these constraints allow values larger than 32 bits. Check 10154 // that the value fits in an int. 10155 if (CVal != CVal64) 10156 return; 10157 10158 switch (ConstraintLetter) { 10159 case 'j': 10160 // Constant suitable for movw, must be between 0 and 10161 // 65535. 10162 if (Subtarget->hasV6T2Ops()) 10163 if (CVal >= 0 && CVal <= 65535) 10164 break; 10165 return; 10166 case 'I': 10167 if (Subtarget->isThumb1Only()) { 10168 // This must be a constant between 0 and 255, for ADD 10169 // immediates. 10170 if (CVal >= 0 && CVal <= 255) 10171 break; 10172 } else if (Subtarget->isThumb2()) { 10173 // A constant that can be used as an immediate value in a 10174 // data-processing instruction. 10175 if (ARM_AM::getT2SOImmVal(CVal) != -1) 10176 break; 10177 } else { 10178 // A constant that can be used as an immediate value in a 10179 // data-processing instruction. 10180 if (ARM_AM::getSOImmVal(CVal) != -1) 10181 break; 10182 } 10183 return; 10184 10185 case 'J': 10186 if (Subtarget->isThumb()) { // FIXME thumb2 10187 // This must be a constant between -255 and -1, for negated ADD 10188 // immediates. This can be used in GCC with an "n" modifier that 10189 // prints the negated value, for use with SUB instructions. It is 10190 // not useful otherwise but is implemented for compatibility. 10191 if (CVal >= -255 && CVal <= -1) 10192 break; 10193 } else { 10194 // This must be a constant between -4095 and 4095. It is not clear 10195 // what this constraint is intended for. Implemented for 10196 // compatibility with GCC. 10197 if (CVal >= -4095 && CVal <= 4095) 10198 break; 10199 } 10200 return; 10201 10202 case 'K': 10203 if (Subtarget->isThumb1Only()) { 10204 // A 32-bit value where only one byte has a nonzero value. Exclude 10205 // zero to match GCC. This constraint is used by GCC internally for 10206 // constants that can be loaded with a move/shift combination. 10207 // It is not useful otherwise but is implemented for compatibility. 10208 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal)) 10209 break; 10210 } else if (Subtarget->isThumb2()) { 10211 // A constant whose bitwise inverse can be used as an immediate 10212 // value in a data-processing instruction. This can be used in GCC 10213 // with a "B" modifier that prints the inverted value, for use with 10214 // BIC and MVN instructions. It is not useful otherwise but is 10215 // implemented for compatibility. 10216 if (ARM_AM::getT2SOImmVal(~CVal) != -1) 10217 break; 10218 } else { 10219 // A constant whose bitwise inverse can be used as an immediate 10220 // value in a data-processing instruction. This can be used in GCC 10221 // with a "B" modifier that prints the inverted value, for use with 10222 // BIC and MVN instructions. It is not useful otherwise but is 10223 // implemented for compatibility. 10224 if (ARM_AM::getSOImmVal(~CVal) != -1) 10225 break; 10226 } 10227 return; 10228 10229 case 'L': 10230 if (Subtarget->isThumb1Only()) { 10231 // This must be a constant between -7 and 7, 10232 // for 3-operand ADD/SUB immediate instructions. 10233 if (CVal >= -7 && CVal < 7) 10234 break; 10235 } else if (Subtarget->isThumb2()) { 10236 // A constant whose negation can be used as an immediate value in a 10237 // data-processing instruction. This can be used in GCC with an "n" 10238 // modifier that prints the negated value, for use with SUB 10239 // instructions. It is not useful otherwise but is implemented for 10240 // compatibility. 10241 if (ARM_AM::getT2SOImmVal(-CVal) != -1) 10242 break; 10243 } else { 10244 // A constant whose negation can be used as an immediate value in a 10245 // data-processing instruction. This can be used in GCC with an "n" 10246 // modifier that prints the negated value, for use with SUB 10247 // instructions. It is not useful otherwise but is implemented for 10248 // compatibility. 10249 if (ARM_AM::getSOImmVal(-CVal) != -1) 10250 break; 10251 } 10252 return; 10253 10254 case 'M': 10255 if (Subtarget->isThumb()) { // FIXME thumb2 10256 // This must be a multiple of 4 between 0 and 1020, for 10257 // ADD sp + immediate. 10258 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0)) 10259 break; 10260 } else { 10261 // A power of two or a constant between 0 and 32. This is used in 10262 // GCC for the shift amount on shifted register operands, but it is 10263 // useful in general for any shift amounts. 10264 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0)) 10265 break; 10266 } 10267 return; 10268 10269 case 'N': 10270 if (Subtarget->isThumb()) { // FIXME thumb2 10271 // This must be a constant between 0 and 31, for shift amounts. 10272 if (CVal >= 0 && CVal <= 31) 10273 break; 10274 } 10275 return; 10276 10277 case 'O': 10278 if (Subtarget->isThumb()) { // FIXME thumb2 10279 // This must be a multiple of 4 between -508 and 508, for 10280 // ADD/SUB sp = sp + immediate. 10281 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0)) 10282 break; 10283 } 10284 return; 10285 } 10286 Result = DAG.getTargetConstant(CVal, Op.getValueType()); 10287 break; 10288 } 10289 10290 if (Result.getNode()) { 10291 Ops.push_back(Result); 10292 return; 10293 } 10294 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 10295 } 10296 10297 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const { 10298 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only"); 10299 unsigned Opcode = Op->getOpcode(); 10300 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) && 10301 "Invalid opcode for Div/Rem lowering"); 10302 bool isSigned = (Opcode == ISD::SDIVREM); 10303 EVT VT = Op->getValueType(0); 10304 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 10305 10306 RTLIB::Libcall LC; 10307 switch (VT.getSimpleVT().SimpleTy) { 10308 default: llvm_unreachable("Unexpected request for libcall!"); 10309 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 10310 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 10311 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 10312 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 10313 } 10314 10315 SDValue InChain = DAG.getEntryNode(); 10316 10317 TargetLowering::ArgListTy Args; 10318 TargetLowering::ArgListEntry Entry; 10319 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) { 10320 EVT ArgVT = Op->getOperand(i).getValueType(); 10321 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 10322 Entry.Node = Op->getOperand(i); 10323 Entry.Ty = ArgTy; 10324 Entry.isSExt = isSigned; 10325 Entry.isZExt = !isSigned; 10326 Args.push_back(Entry); 10327 } 10328 10329 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 10330 getPointerTy()); 10331 10332 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL); 10333 10334 SDLoc dl(Op); 10335 TargetLowering:: 10336 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true, 10337 0, getLibcallCallingConv(LC), /*isTailCall=*/false, 10338 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true, 10339 Callee, Args, DAG, dl); 10340 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI); 10341 10342 return CallInfo.first; 10343 } 10344 10345 bool 10346 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 10347 // The ARM target isn't yet aware of offsets. 10348 return false; 10349 } 10350 10351 bool ARM::isBitFieldInvertedMask(unsigned v) { 10352 if (v == 0xffffffff) 10353 return false; 10354 10355 // there can be 1's on either or both "outsides", all the "inside" 10356 // bits must be 0's 10357 unsigned TO = CountTrailingOnes_32(v); 10358 unsigned LO = CountLeadingOnes_32(v); 10359 v = (v >> TO) << TO; 10360 v = (v << LO) >> LO; 10361 return v == 0; 10362 } 10363 10364 /// isFPImmLegal - Returns true if the target can instruction select the 10365 /// specified FP immediate natively. If false, the legalizer will 10366 /// materialize the FP immediate as a load from a constant pool. 10367 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 10368 if (!Subtarget->hasVFP3()) 10369 return false; 10370 if (VT == MVT::f32) 10371 return ARM_AM::getFP32Imm(Imm) != -1; 10372 if (VT == MVT::f64) 10373 return ARM_AM::getFP64Imm(Imm) != -1; 10374 return false; 10375 } 10376 10377 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 10378 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 10379 /// specified in the intrinsic calls. 10380 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 10381 const CallInst &I, 10382 unsigned Intrinsic) const { 10383 switch (Intrinsic) { 10384 case Intrinsic::arm_neon_vld1: 10385 case Intrinsic::arm_neon_vld2: 10386 case Intrinsic::arm_neon_vld3: 10387 case Intrinsic::arm_neon_vld4: 10388 case Intrinsic::arm_neon_vld2lane: 10389 case Intrinsic::arm_neon_vld3lane: 10390 case Intrinsic::arm_neon_vld4lane: { 10391 Info.opc = ISD::INTRINSIC_W_CHAIN; 10392 // Conservatively set memVT to the entire set of vectors loaded. 10393 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8; 10394 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 10395 Info.ptrVal = I.getArgOperand(0); 10396 Info.offset = 0; 10397 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 10398 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 10399 Info.vol = false; // volatile loads with NEON intrinsics not supported 10400 Info.readMem = true; 10401 Info.writeMem = false; 10402 return true; 10403 } 10404 case Intrinsic::arm_neon_vst1: 10405 case Intrinsic::arm_neon_vst2: 10406 case Intrinsic::arm_neon_vst3: 10407 case Intrinsic::arm_neon_vst4: 10408 case Intrinsic::arm_neon_vst2lane: 10409 case Intrinsic::arm_neon_vst3lane: 10410 case Intrinsic::arm_neon_vst4lane: { 10411 Info.opc = ISD::INTRINSIC_VOID; 10412 // Conservatively set memVT to the entire set of vectors stored. 10413 unsigned NumElts = 0; 10414 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 10415 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 10416 if (!ArgTy->isVectorTy()) 10417 break; 10418 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8; 10419 } 10420 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 10421 Info.ptrVal = I.getArgOperand(0); 10422 Info.offset = 0; 10423 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1); 10424 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue(); 10425 Info.vol = false; // volatile stores with NEON intrinsics not supported 10426 Info.readMem = false; 10427 Info.writeMem = true; 10428 return true; 10429 } 10430 case Intrinsic::arm_ldaex: 10431 case Intrinsic::arm_ldrex: { 10432 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 10433 Info.opc = ISD::INTRINSIC_W_CHAIN; 10434 Info.memVT = MVT::getVT(PtrTy->getElementType()); 10435 Info.ptrVal = I.getArgOperand(0); 10436 Info.offset = 0; 10437 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType()); 10438 Info.vol = true; 10439 Info.readMem = true; 10440 Info.writeMem = false; 10441 return true; 10442 } 10443 case Intrinsic::arm_stlex: 10444 case Intrinsic::arm_strex: { 10445 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 10446 Info.opc = ISD::INTRINSIC_W_CHAIN; 10447 Info.memVT = MVT::getVT(PtrTy->getElementType()); 10448 Info.ptrVal = I.getArgOperand(1); 10449 Info.offset = 0; 10450 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType()); 10451 Info.vol = true; 10452 Info.readMem = false; 10453 Info.writeMem = true; 10454 return true; 10455 } 10456 case Intrinsic::arm_stlexd: 10457 case Intrinsic::arm_strexd: { 10458 Info.opc = ISD::INTRINSIC_W_CHAIN; 10459 Info.memVT = MVT::i64; 10460 Info.ptrVal = I.getArgOperand(2); 10461 Info.offset = 0; 10462 Info.align = 8; 10463 Info.vol = true; 10464 Info.readMem = false; 10465 Info.writeMem = true; 10466 return true; 10467 } 10468 case Intrinsic::arm_ldaexd: 10469 case Intrinsic::arm_ldrexd: { 10470 Info.opc = ISD::INTRINSIC_W_CHAIN; 10471 Info.memVT = MVT::i64; 10472 Info.ptrVal = I.getArgOperand(0); 10473 Info.offset = 0; 10474 Info.align = 8; 10475 Info.vol = true; 10476 Info.readMem = true; 10477 Info.writeMem = false; 10478 return true; 10479 } 10480 default: 10481 break; 10482 } 10483 10484 return false; 10485 } 10486 10487 /// \brief Returns true if it is beneficial to convert a load of a constant 10488 /// to just the constant itself. 10489 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 10490 Type *Ty) const { 10491 assert(Ty->isIntegerTy()); 10492 10493 unsigned Bits = Ty->getPrimitiveSizeInBits(); 10494 if (Bits == 0 || Bits > 32) 10495 return false; 10496 return true; 10497 } 10498 10499 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const { 10500 // Loads and stores less than 64-bits are already atomic; ones above that 10501 // are doomed anyway, so defer to the default libcall and blame the OS when 10502 // things go wrong: 10503 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 10504 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64; 10505 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) 10506 return LI->getType()->getPrimitiveSizeInBits() == 64; 10507 10508 // For the real atomic operations, we have ldrex/strex up to 64 bits. 10509 return Inst->getType()->getPrimitiveSizeInBits() <= 64; 10510 } 10511 10512 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 10513 AtomicOrdering Ord) const { 10514 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10515 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 10516 bool IsAcquire = 10517 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent; 10518 10519 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd 10520 // intrinsic must return {i32, i32} and we have to recombine them into a 10521 // single i64 here. 10522 if (ValTy->getPrimitiveSizeInBits() == 64) { 10523 Intrinsic::ID Int = 10524 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd; 10525 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int); 10526 10527 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10528 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi"); 10529 10530 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 10531 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 10532 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 10533 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 10534 return Builder.CreateOr( 10535 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64"); 10536 } 10537 10538 Type *Tys[] = { Addr->getType() }; 10539 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex; 10540 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys); 10541 10542 return Builder.CreateTruncOrBitCast( 10543 Builder.CreateCall(Ldrex, Addr), 10544 cast<PointerType>(Addr->getType())->getElementType()); 10545 } 10546 10547 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, 10548 Value *Addr, 10549 AtomicOrdering Ord) const { 10550 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10551 bool IsRelease = 10552 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent; 10553 10554 // Since the intrinsics must have legal type, the i64 intrinsics take two 10555 // parameters: "i32, i32". We must marshal Val into the appropriate form 10556 // before the call. 10557 if (Val->getType()->getPrimitiveSizeInBits() == 64) { 10558 Intrinsic::ID Int = 10559 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd; 10560 Function *Strex = Intrinsic::getDeclaration(M, Int); 10561 Type *Int32Ty = Type::getInt32Ty(M->getContext()); 10562 10563 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo"); 10564 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi"); 10565 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10566 return Builder.CreateCall3(Strex, Lo, Hi, Addr); 10567 } 10568 10569 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex; 10570 Type *Tys[] = { Addr->getType() }; 10571 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys); 10572 10573 return Builder.CreateCall2( 10574 Strex, Builder.CreateZExtOrBitCast( 10575 Val, Strex->getFunctionType()->getParamType(0)), 10576 Addr); 10577 } 10578