1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.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/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "arm-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
64 ARMInterworking("arm-interworking", cl::Hidden,
65 cl::desc("Enable / disable ARM interworking (for debugging only)"),
69 class ARMCCState : public CCState {
71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
74 : CCState(CC, isVarArg, MF, locs, C) {
75 assert(((PC == Call) || (PC == Prologue)) &&
76 "ARMCCState users must specify whether their context is call"
77 "or prologue generation.");
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85 ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89 MVT PromotedBitwiseVT) {
90 if (VT != PromotedLdStVT) {
91 setOperationAction(ISD::LOAD, VT, Promote);
92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94 setOperationAction(ISD::STORE, VT, Promote);
95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98 MVT ElemTy = VT.getVectorElementType();
99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100 setOperationAction(ISD::SETCC, VT, Custom);
101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103 if (ElemTy == MVT::i32) {
104 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118 setOperationAction(ISD::SELECT, VT, Expand);
119 setOperationAction(ISD::SELECT_CC, VT, Expand);
120 setOperationAction(ISD::VSELECT, VT, Expand);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122 if (VT.isInteger()) {
123 setOperationAction(ISD::SHL, VT, Custom);
124 setOperationAction(ISD::SRA, VT, Custom);
125 setOperationAction(ISD::SRL, VT, Custom);
128 // Promote all bit-wise operations.
129 if (VT.isInteger() && VT != PromotedBitwiseVT) {
130 setOperationAction(ISD::AND, VT, Promote);
131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132 setOperationAction(ISD::OR, VT, Promote);
133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::XOR, VT, Promote);
135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138 // Neon does not support vector divide/remainder operations.
139 setOperationAction(ISD::SDIV, VT, Expand);
140 setOperationAction(ISD::UDIV, VT, Expand);
141 setOperationAction(ISD::FDIV, VT, Expand);
142 setOperationAction(ISD::SREM, VT, Expand);
143 setOperationAction(ISD::UREM, VT, Expand);
144 setOperationAction(ISD::FREM, VT, Expand);
146 if (VT.isInteger()) {
147 setOperationAction(ISD::SABSDIFF, VT, Legal);
148 setOperationAction(ISD::UABSDIFF, VT, Legal);
150 if (!VT.isFloatingPoint() &&
151 VT != MVT::v2i64 && VT != MVT::v1i64)
152 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
153 setOperationAction(Opcode, VT, Legal);
157 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::DPRRegClass);
159 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
162 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
163 addRegisterClass(VT, &ARM::DPairRegClass);
164 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
168 const ARMSubtarget &STI)
169 : TargetLowering(TM), Subtarget(&STI) {
170 RegInfo = Subtarget->getRegisterInfo();
171 Itins = Subtarget->getInstrItineraryData();
173 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
175 if (Subtarget->isTargetMachO()) {
176 // Uses VFP for Thumb libfuncs if available.
177 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
179 static const struct {
180 const RTLIB::Libcall Op;
181 const char * const Name;
182 const ISD::CondCode Cond;
184 // Single-precision floating-point arithmetic.
185 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
186 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
187 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
188 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
190 // Double-precision floating-point arithmetic.
191 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
192 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
193 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
194 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
196 // Single-precision comparisons.
197 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
198 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
199 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
200 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
201 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
202 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
203 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
204 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
206 // Double-precision comparisons.
207 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
208 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
209 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
210 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
211 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
212 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
213 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
214 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
216 // Floating-point to integer conversions.
217 // i64 conversions are done via library routines even when generating VFP
218 // instructions, so use the same ones.
219 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
220 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
221 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
222 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
224 // Conversions between floating types.
225 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
226 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
228 // Integer to floating-point conversions.
229 // i64 conversions are done via library routines even when generating VFP
230 // instructions, so use the same ones.
231 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
232 // e.g., __floatunsidf vs. __floatunssidfvfp.
233 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
234 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
235 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
236 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
239 for (const auto &LC : LibraryCalls) {
240 setLibcallName(LC.Op, LC.Name);
241 if (LC.Cond != ISD::SETCC_INVALID)
242 setCmpLibcallCC(LC.Op, LC.Cond);
247 // These libcalls are not available in 32-bit.
248 setLibcallName(RTLIB::SHL_I128, nullptr);
249 setLibcallName(RTLIB::SRL_I128, nullptr);
250 setLibcallName(RTLIB::SRA_I128, nullptr);
252 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
253 !Subtarget->isTargetWindows()) {
254 static const struct {
255 const RTLIB::Libcall Op;
256 const char * const Name;
257 const CallingConv::ID CC;
258 const ISD::CondCode Cond;
260 // Double-precision floating-point arithmetic helper functions
261 // RTABI chapter 4.1.2, Table 2
262 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267 // Double-precision floating-point comparison helper functions
268 // RTABI chapter 4.1.2, Table 3
269 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
270 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
271 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
272 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
273 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
274 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
276 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
278 // Single-precision floating-point arithmetic helper functions
279 // RTABI chapter 4.1.2, Table 4
280 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285 // Single-precision floating-point comparison helper functions
286 // RTABI chapter 4.1.2, Table 5
287 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
288 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
289 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
290 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
291 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
292 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
294 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
296 // Floating-point to integer conversions.
297 // RTABI chapter 4.1.2, Table 6
298 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 // Conversions between floating types.
308 // RTABI chapter 4.1.2, Table 7
309 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 // Integer to floating-point conversions.
314 // RTABI chapter 4.1.2, Table 8
315 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 // Long long helper functions
325 // RTABI chapter 4.2, Table 9
326 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 // Integer division functions
332 // RTABI chapter 4.3.1
333 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 // RTABI chapter 4.3.4
344 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 for (const auto &LC : LibraryCalls) {
350 setLibcallName(LC.Op, LC.Name);
351 setLibcallCallingConv(LC.Op, LC.CC);
352 if (LC.Cond != ISD::SETCC_INVALID)
353 setCmpLibcallCC(LC.Op, LC.Cond);
357 if (Subtarget->isTargetWindows()) {
358 static const struct {
359 const RTLIB::Libcall Op;
360 const char * const Name;
361 const CallingConv::ID CC;
363 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
364 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
366 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
373 for (const auto &LC : LibraryCalls) {
374 setLibcallName(LC.Op, LC.Name);
375 setLibcallCallingConv(LC.Op, LC.CC);
379 // Use divmod compiler-rt calls for iOS 5.0 and later.
380 if (Subtarget->getTargetTriple().isiOS() &&
381 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
386 // The half <-> float conversion functions are always soft-float, but are
387 // needed for some targets which use a hard-float calling convention by
389 if (Subtarget->isAAPCS_ABI()) {
390 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
399 if (Subtarget->isThumb1Only())
400 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
402 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
403 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
404 !Subtarget->isThumb1Only()) {
405 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
406 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
409 for (MVT VT : MVT::vector_valuetypes()) {
410 for (MVT InnerVT : MVT::vector_valuetypes()) {
411 setTruncStoreAction(VT, InnerVT, Expand);
412 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
413 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
414 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
417 setOperationAction(ISD::MULHS, VT, Expand);
418 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419 setOperationAction(ISD::MULHU, VT, Expand);
420 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
422 setOperationAction(ISD::BSWAP, VT, Expand);
425 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
428 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
429 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
431 if (Subtarget->hasNEON()) {
432 addDRTypeForNEON(MVT::v2f32);
433 addDRTypeForNEON(MVT::v8i8);
434 addDRTypeForNEON(MVT::v4i16);
435 addDRTypeForNEON(MVT::v2i32);
436 addDRTypeForNEON(MVT::v1i64);
438 addQRTypeForNEON(MVT::v4f32);
439 addQRTypeForNEON(MVT::v2f64);
440 addQRTypeForNEON(MVT::v16i8);
441 addQRTypeForNEON(MVT::v8i16);
442 addQRTypeForNEON(MVT::v4i32);
443 addQRTypeForNEON(MVT::v2i64);
445 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
446 // neither Neon nor VFP support any arithmetic operations on it.
447 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
448 // supported for v4f32.
449 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
450 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
451 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
452 // FIXME: Code duplication: FDIV and FREM are expanded always, see
453 // ARMTargetLowering::addTypeForNEON method for details.
454 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
455 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
456 // FIXME: Create unittest.
457 // In another words, find a way when "copysign" appears in DAG with vector
459 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
460 // FIXME: Code duplication: SETCC has custom operation action, see
461 // ARMTargetLowering::addTypeForNEON method for details.
462 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
463 // FIXME: Create unittest for FNEG and for FABS.
464 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
465 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
466 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
467 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
468 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
469 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
470 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
471 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
472 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
473 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
474 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
475 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
476 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
477 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
478 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
479 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
480 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
481 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
482 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
484 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
485 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
486 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
487 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
488 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
489 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
490 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
491 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
492 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
493 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
494 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
495 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
496 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
497 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
498 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
500 // Mark v2f32 intrinsics.
501 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
502 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
503 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
504 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
505 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
506 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
507 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
508 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
509 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
510 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
511 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
512 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
513 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
514 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
515 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
517 // Neon does not support some operations on v1i64 and v2i64 types.
518 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
519 // Custom handling for some quad-vector types to detect VMULL.
520 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
522 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
523 // Custom handling for some vector types to avoid expensive expansions
524 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
525 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
526 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
527 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
528 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
529 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
530 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
531 // a destination type that is wider than the source, and nor does
532 // it have a FP_TO_[SU]INT instruction with a narrower destination than
534 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
535 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
536 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
537 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
539 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
540 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
542 // NEON does not have single instruction CTPOP for vectors with element
543 // types wider than 8-bits. However, custom lowering can leverage the
544 // v8i8/v16i8 vcnt instruction.
545 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
546 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
547 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
548 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
550 // NEON does not have single instruction CTTZ for vectors.
551 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
552 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
553 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
554 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
556 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
557 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
558 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
559 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
561 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
563 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
564 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
566 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
567 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
568 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
569 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
571 // NEON only has FMA instructions as of VFP4.
572 if (!Subtarget->hasVFP4()) {
573 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
574 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
577 setTargetDAGCombine(ISD::INTRINSIC_VOID);
578 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
579 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
580 setTargetDAGCombine(ISD::SHL);
581 setTargetDAGCombine(ISD::SRL);
582 setTargetDAGCombine(ISD::SRA);
583 setTargetDAGCombine(ISD::SIGN_EXTEND);
584 setTargetDAGCombine(ISD::ZERO_EXTEND);
585 setTargetDAGCombine(ISD::ANY_EXTEND);
586 setTargetDAGCombine(ISD::BUILD_VECTOR);
587 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
588 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
589 setTargetDAGCombine(ISD::STORE);
590 setTargetDAGCombine(ISD::FP_TO_SINT);
591 setTargetDAGCombine(ISD::FP_TO_UINT);
592 setTargetDAGCombine(ISD::FDIV);
593 setTargetDAGCombine(ISD::LOAD);
595 // It is legal to extload from v4i8 to v4i16 or v4i32.
596 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
598 for (MVT VT : MVT::integer_vector_valuetypes()) {
599 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
600 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
601 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
606 // ARM and Thumb2 support UMLAL/SMLAL.
607 if (!Subtarget->isThumb1Only())
608 setTargetDAGCombine(ISD::ADDC);
610 if (Subtarget->isFPOnlySP()) {
611 // When targeting a floating-point unit with only single-precision
612 // operations, f64 is legal for the few double-precision instructions which
613 // are present However, no double-precision operations other than moves,
614 // loads and stores are provided by the hardware.
615 setOperationAction(ISD::FADD, MVT::f64, Expand);
616 setOperationAction(ISD::FSUB, MVT::f64, Expand);
617 setOperationAction(ISD::FMUL, MVT::f64, Expand);
618 setOperationAction(ISD::FMA, MVT::f64, Expand);
619 setOperationAction(ISD::FDIV, MVT::f64, Expand);
620 setOperationAction(ISD::FREM, MVT::f64, Expand);
621 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
622 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
623 setOperationAction(ISD::FNEG, MVT::f64, Expand);
624 setOperationAction(ISD::FABS, MVT::f64, Expand);
625 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
626 setOperationAction(ISD::FSIN, MVT::f64, Expand);
627 setOperationAction(ISD::FCOS, MVT::f64, Expand);
628 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
629 setOperationAction(ISD::FPOW, MVT::f64, Expand);
630 setOperationAction(ISD::FLOG, MVT::f64, Expand);
631 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
632 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
633 setOperationAction(ISD::FEXP, MVT::f64, Expand);
634 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
635 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
636 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
637 setOperationAction(ISD::FRINT, MVT::f64, Expand);
638 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
639 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
640 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
641 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
642 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
643 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
644 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
645 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
646 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
647 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
650 computeRegisterProperties(Subtarget->getRegisterInfo());
652 // ARM does not have floating-point extending loads.
653 for (MVT VT : MVT::fp_valuetypes()) {
654 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
655 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
658 // ... or truncating stores
659 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
660 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
661 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
663 // ARM does not have i1 sign extending load.
664 for (MVT VT : MVT::integer_valuetypes())
665 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
667 // ARM supports all 4 flavors of integer indexed load / store.
668 if (!Subtarget->isThumb1Only()) {
669 for (unsigned im = (unsigned)ISD::PRE_INC;
670 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
671 setIndexedLoadAction(im, MVT::i1, Legal);
672 setIndexedLoadAction(im, MVT::i8, Legal);
673 setIndexedLoadAction(im, MVT::i16, Legal);
674 setIndexedLoadAction(im, MVT::i32, Legal);
675 setIndexedStoreAction(im, MVT::i1, Legal);
676 setIndexedStoreAction(im, MVT::i8, Legal);
677 setIndexedStoreAction(im, MVT::i16, Legal);
678 setIndexedStoreAction(im, MVT::i32, Legal);
682 setOperationAction(ISD::SADDO, MVT::i32, Custom);
683 setOperationAction(ISD::UADDO, MVT::i32, Custom);
684 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
685 setOperationAction(ISD::USUBO, MVT::i32, Custom);
687 // i64 operation support.
688 setOperationAction(ISD::MUL, MVT::i64, Expand);
689 setOperationAction(ISD::MULHU, MVT::i32, Expand);
690 if (Subtarget->isThumb1Only()) {
691 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
692 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
694 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
695 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
696 setOperationAction(ISD::MULHS, MVT::i32, Expand);
698 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
699 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
700 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
701 setOperationAction(ISD::SRL, MVT::i64, Custom);
702 setOperationAction(ISD::SRA, MVT::i64, Custom);
704 if (!Subtarget->isThumb1Only()) {
705 // FIXME: We should do this for Thumb1 as well.
706 setOperationAction(ISD::ADDC, MVT::i32, Custom);
707 setOperationAction(ISD::ADDE, MVT::i32, Custom);
708 setOperationAction(ISD::SUBC, MVT::i32, Custom);
709 setOperationAction(ISD::SUBE, MVT::i32, Custom);
712 // ARM does not have ROTL.
713 setOperationAction(ISD::ROTL, MVT::i32, Expand);
714 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
715 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
716 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
717 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
719 // These just redirect to CTTZ and CTLZ on ARM.
720 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
721 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
723 // @llvm.readcyclecounter requires the Performance Monitors extension.
724 // Default to the 0 expansion on unsupported platforms.
725 // FIXME: Technically there are older ARM CPUs that have
726 // implementation-specific ways of obtaining this information.
727 if (Subtarget->hasPerfMon())
728 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
730 // Only ARMv6 has BSWAP.
731 if (!Subtarget->hasV6Ops())
732 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
734 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
735 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
736 // These are expanded into libcalls if the cpu doesn't have HW divider.
737 setOperationAction(ISD::SDIV, MVT::i32, Expand);
738 setOperationAction(ISD::UDIV, MVT::i32, Expand);
741 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
742 setOperationAction(ISD::SDIV, MVT::i32, Custom);
743 setOperationAction(ISD::UDIV, MVT::i32, Custom);
745 setOperationAction(ISD::SDIV, MVT::i64, Custom);
746 setOperationAction(ISD::UDIV, MVT::i64, Custom);
749 setOperationAction(ISD::SREM, MVT::i32, Expand);
750 setOperationAction(ISD::UREM, MVT::i32, Expand);
751 // Register based DivRem for AEABI (RTABI 4.2)
752 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
753 setOperationAction(ISD::SREM, MVT::i64, Custom);
754 setOperationAction(ISD::UREM, MVT::i64, Custom);
756 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
757 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
758 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
759 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
760 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
761 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
762 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
763 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
765 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
766 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
767 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
768 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
769 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
770 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
771 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
772 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
774 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
775 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
777 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
778 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
781 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
782 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
783 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
784 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
785 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
787 setOperationAction(ISD::TRAP, MVT::Other, Legal);
789 // Use the default implementation.
790 setOperationAction(ISD::VASTART, MVT::Other, Custom);
791 setOperationAction(ISD::VAARG, MVT::Other, Expand);
792 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
793 setOperationAction(ISD::VAEND, MVT::Other, Expand);
794 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
795 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
797 if (!Subtarget->isTargetMachO()) {
798 // Non-MachO platforms may return values in these registers via the
799 // personality function.
800 setExceptionPointerRegister(ARM::R0);
801 setExceptionSelectorRegister(ARM::R1);
804 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
805 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
807 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
809 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
810 // the default expansion. If we are targeting a single threaded system,
811 // then set them all for expand so we can lower them later into their
813 if (TM.Options.ThreadModel == ThreadModel::Single)
814 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
815 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
816 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
817 // to ldrex/strex loops already.
818 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
820 // On v8, we have particularly efficient implementations of atomic fences
821 // if they can be combined with nearby atomic loads and stores.
822 if (!Subtarget->hasV8Ops()) {
823 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
824 setInsertFencesForAtomic(true);
827 // If there's anything we can use as a barrier, go through custom lowering
829 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
830 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
832 // Set them all for expansion, which will force libcalls.
833 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
834 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
835 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
836 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
837 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
838 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
839 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
840 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
841 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
842 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
843 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
844 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
845 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
846 // Unordered/Monotonic case.
847 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
848 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
851 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
853 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
854 if (!Subtarget->hasV6Ops()) {
855 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
856 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
858 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
860 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
861 !Subtarget->isThumb1Only()) {
862 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
863 // iff target supports vfp2.
864 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
865 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
868 // We want to custom lower some of our intrinsics.
869 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
870 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
871 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
872 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
873 if (Subtarget->isTargetDarwin())
874 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
876 setOperationAction(ISD::SETCC, MVT::i32, Expand);
877 setOperationAction(ISD::SETCC, MVT::f32, Expand);
878 setOperationAction(ISD::SETCC, MVT::f64, Expand);
879 setOperationAction(ISD::SELECT, MVT::i32, Custom);
880 setOperationAction(ISD::SELECT, MVT::f32, Custom);
881 setOperationAction(ISD::SELECT, MVT::f64, Custom);
882 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
883 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
884 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
886 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
887 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
888 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
889 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
890 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
892 // We don't support sin/cos/fmod/copysign/pow
893 setOperationAction(ISD::FSIN, MVT::f64, Expand);
894 setOperationAction(ISD::FSIN, MVT::f32, Expand);
895 setOperationAction(ISD::FCOS, MVT::f32, Expand);
896 setOperationAction(ISD::FCOS, MVT::f64, Expand);
897 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
898 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
899 setOperationAction(ISD::FREM, MVT::f64, Expand);
900 setOperationAction(ISD::FREM, MVT::f32, Expand);
901 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
902 !Subtarget->isThumb1Only()) {
903 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
904 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
906 setOperationAction(ISD::FPOW, MVT::f64, Expand);
907 setOperationAction(ISD::FPOW, MVT::f32, Expand);
909 if (!Subtarget->hasVFP4()) {
910 setOperationAction(ISD::FMA, MVT::f64, Expand);
911 setOperationAction(ISD::FMA, MVT::f32, Expand);
914 // Various VFP goodness
915 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
916 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
917 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
918 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
919 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
922 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
923 if (!Subtarget->hasFP16()) {
924 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
925 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
929 // Combine sin / cos into one node or libcall if possible.
930 if (Subtarget->hasSinCos()) {
931 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
932 setLibcallName(RTLIB::SINCOS_F64, "sincos");
933 if (Subtarget->getTargetTriple().isiOS()) {
934 // For iOS, we don't want to the normal expansion of a libcall to
935 // sincos. We want to issue a libcall to __sincos_stret.
936 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
937 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
941 // FP-ARMv8 implements a lot of rounding-like FP operations.
942 if (Subtarget->hasFPARMv8()) {
943 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
944 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
945 setOperationAction(ISD::FROUND, MVT::f32, Legal);
946 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
947 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
948 setOperationAction(ISD::FRINT, MVT::f32, Legal);
949 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
950 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
951 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
952 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
953 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
954 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
956 if (!Subtarget->isFPOnlySP()) {
957 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
958 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
959 setOperationAction(ISD::FROUND, MVT::f64, Legal);
960 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
961 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
962 setOperationAction(ISD::FRINT, MVT::f64, Legal);
963 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
964 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
968 if (Subtarget->hasNEON()) {
969 // vmin and vmax aren't available in a scalar form, so we use
970 // a NEON instruction with an undef lane instead.
971 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
972 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
973 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
974 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
975 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
976 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
979 // We have target-specific dag combine patterns for the following nodes:
980 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
981 setTargetDAGCombine(ISD::ADD);
982 setTargetDAGCombine(ISD::SUB);
983 setTargetDAGCombine(ISD::MUL);
984 setTargetDAGCombine(ISD::AND);
985 setTargetDAGCombine(ISD::OR);
986 setTargetDAGCombine(ISD::XOR);
988 if (Subtarget->hasV6Ops())
989 setTargetDAGCombine(ISD::SRL);
991 setStackPointerRegisterToSaveRestore(ARM::SP);
993 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
994 !Subtarget->hasVFP2())
995 setSchedulingPreference(Sched::RegPressure);
997 setSchedulingPreference(Sched::Hybrid);
999 //// temporary - rewrite interface to use type
1000 MaxStoresPerMemset = 8;
1001 MaxStoresPerMemsetOptSize = 4;
1002 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1003 MaxStoresPerMemcpyOptSize = 2;
1004 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1005 MaxStoresPerMemmoveOptSize = 2;
1007 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1008 // are at least 4 bytes aligned.
1009 setMinStackArgumentAlignment(4);
1011 // Prefer likely predicted branches to selects on out-of-order cores.
1012 PredictableSelectIsExpensive = Subtarget->isLikeA9();
1014 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1017 bool ARMTargetLowering::useSoftFloat() const {
1018 return Subtarget->useSoftFloat();
1021 // FIXME: It might make sense to define the representative register class as the
1022 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1023 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1024 // SPR's representative would be DPR_VFP2. This should work well if register
1025 // pressure tracking were modified such that a register use would increment the
1026 // pressure of the register class's representative and all of it's super
1027 // classes' representatives transitively. We have not implemented this because
1028 // of the difficulty prior to coalescing of modeling operand register classes
1029 // due to the common occurrence of cross class copies and subregister insertions
1031 std::pair<const TargetRegisterClass *, uint8_t>
1032 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1034 const TargetRegisterClass *RRC = nullptr;
1036 switch (VT.SimpleTy) {
1038 return TargetLowering::findRepresentativeClass(TRI, VT);
1039 // Use DPR as representative register class for all floating point
1040 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1041 // the cost is 1 for both f32 and f64.
1042 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1043 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1044 RRC = &ARM::DPRRegClass;
1045 // When NEON is used for SP, only half of the register file is available
1046 // because operations that define both SP and DP results will be constrained
1047 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1048 // coalescing by double-counting the SP regs. See the FIXME above.
1049 if (Subtarget->useNEONForSinglePrecisionFP())
1052 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1053 case MVT::v4f32: case MVT::v2f64:
1054 RRC = &ARM::DPRRegClass;
1058 RRC = &ARM::DPRRegClass;
1062 RRC = &ARM::DPRRegClass;
1066 return std::make_pair(RRC, Cost);
1069 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1070 switch ((ARMISD::NodeType)Opcode) {
1071 case ARMISD::FIRST_NUMBER: break;
1072 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1073 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1074 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1075 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1076 case ARMISD::CALL: return "ARMISD::CALL";
1077 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1078 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1079 case ARMISD::tCALL: return "ARMISD::tCALL";
1080 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1081 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1082 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1083 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1084 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1085 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1086 case ARMISD::CMP: return "ARMISD::CMP";
1087 case ARMISD::CMN: return "ARMISD::CMN";
1088 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1089 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1090 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1091 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1092 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1094 case ARMISD::CMOV: return "ARMISD::CMOV";
1096 case ARMISD::RBIT: return "ARMISD::RBIT";
1098 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1099 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1100 case ARMISD::RRX: return "ARMISD::RRX";
1102 case ARMISD::ADDC: return "ARMISD::ADDC";
1103 case ARMISD::ADDE: return "ARMISD::ADDE";
1104 case ARMISD::SUBC: return "ARMISD::SUBC";
1105 case ARMISD::SUBE: return "ARMISD::SUBE";
1107 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1108 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1110 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1111 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1112 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1114 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1116 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1118 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1120 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1122 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1124 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1125 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1127 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1128 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1129 case ARMISD::VCGE: return "ARMISD::VCGE";
1130 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1131 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1132 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1133 case ARMISD::VCGT: return "ARMISD::VCGT";
1134 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1135 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1136 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1137 case ARMISD::VTST: return "ARMISD::VTST";
1139 case ARMISD::VSHL: return "ARMISD::VSHL";
1140 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1141 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1142 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1143 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1144 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1145 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1146 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1147 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1148 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1149 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1150 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1151 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1152 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1153 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1154 case ARMISD::VSLI: return "ARMISD::VSLI";
1155 case ARMISD::VSRI: return "ARMISD::VSRI";
1156 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1157 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1158 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1159 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1160 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1161 case ARMISD::VDUP: return "ARMISD::VDUP";
1162 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1163 case ARMISD::VEXT: return "ARMISD::VEXT";
1164 case ARMISD::VREV64: return "ARMISD::VREV64";
1165 case ARMISD::VREV32: return "ARMISD::VREV32";
1166 case ARMISD::VREV16: return "ARMISD::VREV16";
1167 case ARMISD::VZIP: return "ARMISD::VZIP";
1168 case ARMISD::VUZP: return "ARMISD::VUZP";
1169 case ARMISD::VTRN: return "ARMISD::VTRN";
1170 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1171 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1172 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1173 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1174 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1175 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1176 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1177 case ARMISD::BFI: return "ARMISD::BFI";
1178 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1179 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1180 case ARMISD::VBSL: return "ARMISD::VBSL";
1181 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1182 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1183 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1184 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1185 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1186 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1187 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1188 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1189 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1190 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1191 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1192 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1193 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1194 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1195 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1196 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1197 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1198 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1199 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1200 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1201 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1206 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1209 return getPointerTy(DL);
1210 return VT.changeVectorElementTypeToInteger();
1213 /// getRegClassFor - Return the register class that should be used for the
1214 /// specified value type.
1215 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1216 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1217 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1218 // load / store 4 to 8 consecutive D registers.
1219 if (Subtarget->hasNEON()) {
1220 if (VT == MVT::v4i64)
1221 return &ARM::QQPRRegClass;
1222 if (VT == MVT::v8i64)
1223 return &ARM::QQQQPRRegClass;
1225 return TargetLowering::getRegClassFor(VT);
1228 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1229 // source/dest is aligned and the copy size is large enough. We therefore want
1230 // to align such objects passed to memory intrinsics.
1231 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1232 unsigned &PrefAlign) const {
1233 if (!isa<MemIntrinsic>(CI))
1236 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1237 // cycle faster than 4-byte aligned LDM.
1238 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1242 // Create a fast isel object.
1244 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1245 const TargetLibraryInfo *libInfo) const {
1246 return ARM::createFastISel(funcInfo, libInfo);
1249 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1250 unsigned NumVals = N->getNumValues();
1252 return Sched::RegPressure;
1254 for (unsigned i = 0; i != NumVals; ++i) {
1255 EVT VT = N->getValueType(i);
1256 if (VT == MVT::Glue || VT == MVT::Other)
1258 if (VT.isFloatingPoint() || VT.isVector())
1262 if (!N->isMachineOpcode())
1263 return Sched::RegPressure;
1265 // Load are scheduled for latency even if there instruction itinerary
1266 // is not available.
1267 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1268 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1270 if (MCID.getNumDefs() == 0)
1271 return Sched::RegPressure;
1272 if (!Itins->isEmpty() &&
1273 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1276 return Sched::RegPressure;
1279 //===----------------------------------------------------------------------===//
1281 //===----------------------------------------------------------------------===//
1283 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1284 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1286 default: llvm_unreachable("Unknown condition code!");
1287 case ISD::SETNE: return ARMCC::NE;
1288 case ISD::SETEQ: return ARMCC::EQ;
1289 case ISD::SETGT: return ARMCC::GT;
1290 case ISD::SETGE: return ARMCC::GE;
1291 case ISD::SETLT: return ARMCC::LT;
1292 case ISD::SETLE: return ARMCC::LE;
1293 case ISD::SETUGT: return ARMCC::HI;
1294 case ISD::SETUGE: return ARMCC::HS;
1295 case ISD::SETULT: return ARMCC::LO;
1296 case ISD::SETULE: return ARMCC::LS;
1300 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1301 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1302 ARMCC::CondCodes &CondCode2) {
1303 CondCode2 = ARMCC::AL;
1305 default: llvm_unreachable("Unknown FP condition!");
1307 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1309 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1311 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1312 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1313 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1314 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1315 case ISD::SETO: CondCode = ARMCC::VC; break;
1316 case ISD::SETUO: CondCode = ARMCC::VS; break;
1317 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1318 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1319 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1321 case ISD::SETULT: CondCode = ARMCC::LT; break;
1323 case ISD::SETULE: CondCode = ARMCC::LE; break;
1325 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1329 //===----------------------------------------------------------------------===//
1330 // Calling Convention Implementation
1331 //===----------------------------------------------------------------------===//
1333 #include "ARMGenCallingConv.inc"
1335 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1336 /// account presence of floating point hardware and calling convention
1337 /// limitations, such as support for variadic functions.
1339 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1340 bool isVarArg) const {
1343 llvm_unreachable("Unsupported calling convention");
1344 case CallingConv::ARM_AAPCS:
1345 case CallingConv::ARM_APCS:
1346 case CallingConv::GHC:
1348 case CallingConv::ARM_AAPCS_VFP:
1349 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1350 case CallingConv::C:
1351 if (!Subtarget->isAAPCS_ABI())
1352 return CallingConv::ARM_APCS;
1353 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1354 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1356 return CallingConv::ARM_AAPCS_VFP;
1358 return CallingConv::ARM_AAPCS;
1359 case CallingConv::Fast:
1360 if (!Subtarget->isAAPCS_ABI()) {
1361 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1362 return CallingConv::Fast;
1363 return CallingConv::ARM_APCS;
1364 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1365 return CallingConv::ARM_AAPCS_VFP;
1367 return CallingConv::ARM_AAPCS;
1371 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1372 /// CallingConvention.
1373 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1375 bool isVarArg) const {
1376 switch (getEffectiveCallingConv(CC, isVarArg)) {
1378 llvm_unreachable("Unsupported calling convention");
1379 case CallingConv::ARM_APCS:
1380 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1381 case CallingConv::ARM_AAPCS:
1382 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1383 case CallingConv::ARM_AAPCS_VFP:
1384 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1385 case CallingConv::Fast:
1386 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1387 case CallingConv::GHC:
1388 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1392 /// LowerCallResult - Lower the result values of a call into the
1393 /// appropriate copies out of appropriate physical registers.
1395 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1396 CallingConv::ID CallConv, bool isVarArg,
1397 const SmallVectorImpl<ISD::InputArg> &Ins,
1398 SDLoc dl, SelectionDAG &DAG,
1399 SmallVectorImpl<SDValue> &InVals,
1400 bool isThisReturn, SDValue ThisVal) const {
1402 // Assign locations to each value returned by this call.
1403 SmallVector<CCValAssign, 16> RVLocs;
1404 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1405 *DAG.getContext(), Call);
1406 CCInfo.AnalyzeCallResult(Ins,
1407 CCAssignFnForNode(CallConv, /* Return*/ true,
1410 // Copy all of the result registers out of their specified physreg.
1411 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1412 CCValAssign VA = RVLocs[i];
1414 // Pass 'this' value directly from the argument to return value, to avoid
1415 // reg unit interference
1416 if (i == 0 && isThisReturn) {
1417 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1418 "unexpected return calling convention register assignment");
1419 InVals.push_back(ThisVal);
1424 if (VA.needsCustom()) {
1425 // Handle f64 or half of a v2f64.
1426 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1428 Chain = Lo.getValue(1);
1429 InFlag = Lo.getValue(2);
1430 VA = RVLocs[++i]; // skip ahead to next loc
1431 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1433 Chain = Hi.getValue(1);
1434 InFlag = Hi.getValue(2);
1435 if (!Subtarget->isLittle())
1437 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1439 if (VA.getLocVT() == MVT::v2f64) {
1440 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1441 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1442 DAG.getConstant(0, dl, MVT::i32));
1444 VA = RVLocs[++i]; // skip ahead to next loc
1445 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1446 Chain = Lo.getValue(1);
1447 InFlag = Lo.getValue(2);
1448 VA = RVLocs[++i]; // skip ahead to next loc
1449 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1450 Chain = Hi.getValue(1);
1451 InFlag = Hi.getValue(2);
1452 if (!Subtarget->isLittle())
1454 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1455 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1456 DAG.getConstant(1, dl, MVT::i32));
1459 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1461 Chain = Val.getValue(1);
1462 InFlag = Val.getValue(2);
1465 switch (VA.getLocInfo()) {
1466 default: llvm_unreachable("Unknown loc info!");
1467 case CCValAssign::Full: break;
1468 case CCValAssign::BCvt:
1469 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1473 InVals.push_back(Val);
1479 /// LowerMemOpCallTo - Store the argument to the stack.
1481 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1482 SDValue StackPtr, SDValue Arg,
1483 SDLoc dl, SelectionDAG &DAG,
1484 const CCValAssign &VA,
1485 ISD::ArgFlagsTy Flags) const {
1486 unsigned LocMemOffset = VA.getLocMemOffset();
1487 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1488 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1490 return DAG.getStore(
1491 Chain, dl, Arg, PtrOff,
1492 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1496 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1497 SDValue Chain, SDValue &Arg,
1498 RegsToPassVector &RegsToPass,
1499 CCValAssign &VA, CCValAssign &NextVA,
1501 SmallVectorImpl<SDValue> &MemOpChains,
1502 ISD::ArgFlagsTy Flags) const {
1504 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1505 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1506 unsigned id = Subtarget->isLittle() ? 0 : 1;
1507 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1509 if (NextVA.isRegLoc())
1510 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1512 assert(NextVA.isMemLoc());
1513 if (!StackPtr.getNode())
1514 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1515 getPointerTy(DAG.getDataLayout()));
1517 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1523 /// LowerCall - Lowering a call into a callseq_start <-
1524 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1527 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1528 SmallVectorImpl<SDValue> &InVals) const {
1529 SelectionDAG &DAG = CLI.DAG;
1531 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1532 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1533 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1534 SDValue Chain = CLI.Chain;
1535 SDValue Callee = CLI.Callee;
1536 bool &isTailCall = CLI.IsTailCall;
1537 CallingConv::ID CallConv = CLI.CallConv;
1538 bool doesNotRet = CLI.DoesNotReturn;
1539 bool isVarArg = CLI.IsVarArg;
1541 MachineFunction &MF = DAG.getMachineFunction();
1542 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1543 bool isThisReturn = false;
1544 bool isSibCall = false;
1545 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1547 // Disable tail calls if they're not supported.
1548 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1552 // Check if it's really possible to do a tail call.
1553 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1554 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1555 Outs, OutVals, Ins, DAG);
1556 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1557 report_fatal_error("failed to perform tail call elimination on a call "
1558 "site marked musttail");
1559 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1560 // detected sibcalls.
1567 // Analyze operands of the call, assigning locations to each operand.
1568 SmallVector<CCValAssign, 16> ArgLocs;
1569 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1570 *DAG.getContext(), Call);
1571 CCInfo.AnalyzeCallOperands(Outs,
1572 CCAssignFnForNode(CallConv, /* Return*/ false,
1575 // Get a count of how many bytes are to be pushed on the stack.
1576 unsigned NumBytes = CCInfo.getNextStackOffset();
1578 // For tail calls, memory operands are available in our caller's stack.
1582 // Adjust the stack pointer for the new arguments...
1583 // These operations are automatically eliminated by the prolog/epilog pass
1585 Chain = DAG.getCALLSEQ_START(Chain,
1586 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1589 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1591 RegsToPassVector RegsToPass;
1592 SmallVector<SDValue, 8> MemOpChains;
1594 // Walk the register/memloc assignments, inserting copies/loads. In the case
1595 // of tail call optimization, arguments are handled later.
1596 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1598 ++i, ++realArgIdx) {
1599 CCValAssign &VA = ArgLocs[i];
1600 SDValue Arg = OutVals[realArgIdx];
1601 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1602 bool isByVal = Flags.isByVal();
1604 // Promote the value if needed.
1605 switch (VA.getLocInfo()) {
1606 default: llvm_unreachable("Unknown loc info!");
1607 case CCValAssign::Full: break;
1608 case CCValAssign::SExt:
1609 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1611 case CCValAssign::ZExt:
1612 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1614 case CCValAssign::AExt:
1615 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1617 case CCValAssign::BCvt:
1618 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1622 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1623 if (VA.needsCustom()) {
1624 if (VA.getLocVT() == MVT::v2f64) {
1625 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1626 DAG.getConstant(0, dl, MVT::i32));
1627 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1628 DAG.getConstant(1, dl, MVT::i32));
1630 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1631 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1633 VA = ArgLocs[++i]; // skip ahead to next loc
1634 if (VA.isRegLoc()) {
1635 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1636 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1638 assert(VA.isMemLoc());
1640 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1641 dl, DAG, VA, Flags));
1644 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1645 StackPtr, MemOpChains, Flags);
1647 } else if (VA.isRegLoc()) {
1648 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1649 assert(VA.getLocVT() == MVT::i32 &&
1650 "unexpected calling convention register assignment");
1651 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1652 "unexpected use of 'returned'");
1653 isThisReturn = true;
1655 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1656 } else if (isByVal) {
1657 assert(VA.isMemLoc());
1658 unsigned offset = 0;
1660 // True if this byval aggregate will be split between registers
1662 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1663 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1665 if (CurByValIdx < ByValArgsCount) {
1667 unsigned RegBegin, RegEnd;
1668 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1671 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1673 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1674 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1675 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1676 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1677 MachinePointerInfo(),
1678 false, false, false,
1679 DAG.InferPtrAlignment(AddArg));
1680 MemOpChains.push_back(Load.getValue(1));
1681 RegsToPass.push_back(std::make_pair(j, Load));
1684 // If parameter size outsides register area, "offset" value
1685 // helps us to calculate stack slot for remained part properly.
1686 offset = RegEnd - RegBegin;
1688 CCInfo.nextInRegsParam();
1691 if (Flags.getByValSize() > 4*offset) {
1692 auto PtrVT = getPointerTy(DAG.getDataLayout());
1693 unsigned LocMemOffset = VA.getLocMemOffset();
1694 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1695 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1696 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1697 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1698 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1700 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1703 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1704 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1705 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1708 } else if (!isSibCall) {
1709 assert(VA.isMemLoc());
1711 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1712 dl, DAG, VA, Flags));
1716 if (!MemOpChains.empty())
1717 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1719 // Build a sequence of copy-to-reg nodes chained together with token chain
1720 // and flag operands which copy the outgoing args into the appropriate regs.
1722 // Tail call byval lowering might overwrite argument registers so in case of
1723 // tail call optimization the copies to registers are lowered later.
1725 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1726 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1727 RegsToPass[i].second, InFlag);
1728 InFlag = Chain.getValue(1);
1731 // For tail calls lower the arguments to the 'real' stack slot.
1733 // Force all the incoming stack arguments to be loaded from the stack
1734 // before any new outgoing arguments are stored to the stack, because the
1735 // outgoing stack slots may alias the incoming argument stack slots, and
1736 // the alias isn't otherwise explicit. This is slightly more conservative
1737 // than necessary, because it means that each store effectively depends
1738 // on every argument instead of just those arguments it would clobber.
1740 // Do not flag preceding copytoreg stuff together with the following stuff.
1742 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1743 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1744 RegsToPass[i].second, InFlag);
1745 InFlag = Chain.getValue(1);
1750 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1751 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1752 // node so that legalize doesn't hack it.
1753 bool isDirect = false;
1754 bool isARMFunc = false;
1755 bool isLocalARMFunc = false;
1756 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1757 auto PtrVt = getPointerTy(DAG.getDataLayout());
1759 if (Subtarget->genLongCalls()) {
1760 assert((Subtarget->isTargetWindows() ||
1761 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1762 "long-calls with non-static relocation model!");
1763 // Handle a global address or an external symbol. If it's not one of
1764 // those, the target's already in a register, so we don't need to do
1766 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1767 const GlobalValue *GV = G->getGlobal();
1768 // Create a constant pool entry for the callee address
1769 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1770 ARMConstantPoolValue *CPV =
1771 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1773 // Get the address of the callee into a register
1774 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1775 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1776 Callee = DAG.getLoad(
1777 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1778 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1780 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1781 const char *Sym = S->getSymbol();
1783 // Create a constant pool entry for the callee address
1784 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1785 ARMConstantPoolValue *CPV =
1786 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1787 ARMPCLabelIndex, 0);
1788 // Get the address of the callee into a register
1789 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1790 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1791 Callee = DAG.getLoad(
1792 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1793 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1796 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1797 const GlobalValue *GV = G->getGlobal();
1799 bool isDef = GV->isStrongDefinitionForLinker();
1800 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1801 getTargetMachine().getRelocationModel() != Reloc::Static;
1802 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1803 // ARM call to a local ARM function is predicable.
1804 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1805 // tBX takes a register source operand.
1806 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1807 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1808 Callee = DAG.getNode(
1809 ARMISD::WrapperPIC, dl, PtrVt,
1810 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1811 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1812 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1813 false, false, true, 0);
1814 } else if (Subtarget->isTargetCOFF()) {
1815 assert(Subtarget->isTargetWindows() &&
1816 "Windows is the only supported COFF target");
1817 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1818 ? ARMII::MO_DLLIMPORT
1819 : ARMII::MO_NO_FLAG;
1821 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1822 if (GV->hasDLLImportStorageClass())
1824 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1825 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1826 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1827 false, false, false, 0);
1829 // On ELF targets for PIC code, direct calls should go through the PLT
1830 unsigned OpFlags = 0;
1831 if (Subtarget->isTargetELF() &&
1832 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1833 OpFlags = ARMII::MO_PLT;
1834 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1836 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1838 bool isStub = Subtarget->isTargetMachO() &&
1839 getTargetMachine().getRelocationModel() != Reloc::Static;
1840 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1841 // tBX takes a register source operand.
1842 const char *Sym = S->getSymbol();
1843 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1844 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1845 ARMConstantPoolValue *CPV =
1846 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1847 ARMPCLabelIndex, 4);
1848 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1849 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1850 Callee = DAG.getLoad(
1851 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1852 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1854 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1855 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1857 unsigned OpFlags = 0;
1858 // On ELF targets for PIC code, direct calls should go through the PLT
1859 if (Subtarget->isTargetELF() &&
1860 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1861 OpFlags = ARMII::MO_PLT;
1862 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1866 // FIXME: handle tail calls differently.
1868 if (Subtarget->isThumb()) {
1869 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1870 CallOpc = ARMISD::CALL_NOLINK;
1872 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1874 if (!isDirect && !Subtarget->hasV5TOps())
1875 CallOpc = ARMISD::CALL_NOLINK;
1876 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1877 // Emit regular call when code size is the priority
1878 !MF.getFunction()->optForMinSize())
1879 // "mov lr, pc; b _foo" to avoid confusing the RSP
1880 CallOpc = ARMISD::CALL_NOLINK;
1882 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1885 std::vector<SDValue> Ops;
1886 Ops.push_back(Chain);
1887 Ops.push_back(Callee);
1889 // Add argument registers to the end of the list so that they are known live
1891 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1892 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1893 RegsToPass[i].second.getValueType()));
1895 // Add a register mask operand representing the call-preserved registers.
1897 const uint32_t *Mask;
1898 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1900 // For 'this' returns, use the R0-preserving mask if applicable
1901 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1903 // Set isThisReturn to false if the calling convention is not one that
1904 // allows 'returned' to be modeled in this way, so LowerCallResult does
1905 // not try to pass 'this' straight through
1906 isThisReturn = false;
1907 Mask = ARI->getCallPreservedMask(MF, CallConv);
1910 Mask = ARI->getCallPreservedMask(MF, CallConv);
1912 assert(Mask && "Missing call preserved mask for calling convention");
1913 Ops.push_back(DAG.getRegisterMask(Mask));
1916 if (InFlag.getNode())
1917 Ops.push_back(InFlag);
1919 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1921 MF.getFrameInfo()->setHasTailCall();
1922 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1925 // Returns a chain and a flag for retval copy to use.
1926 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1927 InFlag = Chain.getValue(1);
1929 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1930 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1932 InFlag = Chain.getValue(1);
1934 // Handle result values, copying them out of physregs into vregs that we
1936 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1937 InVals, isThisReturn,
1938 isThisReturn ? OutVals[0] : SDValue());
1941 /// HandleByVal - Every parameter *after* a byval parameter is passed
1942 /// on the stack. Remember the next parameter register to allocate,
1943 /// and then confiscate the rest of the parameter registers to insure
1945 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1946 unsigned Align) const {
1947 assert((State->getCallOrPrologue() == Prologue ||
1948 State->getCallOrPrologue() == Call) &&
1949 "unhandled ParmContext");
1951 // Byval (as with any stack) slots are always at least 4 byte aligned.
1952 Align = std::max(Align, 4U);
1954 unsigned Reg = State->AllocateReg(GPRArgRegs);
1958 unsigned AlignInRegs = Align / 4;
1959 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1960 for (unsigned i = 0; i < Waste; ++i)
1961 Reg = State->AllocateReg(GPRArgRegs);
1966 unsigned Excess = 4 * (ARM::R4 - Reg);
1968 // Special case when NSAA != SP and parameter size greater than size of
1969 // all remained GPR regs. In that case we can't split parameter, we must
1970 // send it to stack. We also must set NCRN to R4, so waste all
1971 // remained registers.
1972 const unsigned NSAAOffset = State->getNextStackOffset();
1973 if (NSAAOffset != 0 && Size > Excess) {
1974 while (State->AllocateReg(GPRArgRegs))
1979 // First register for byval parameter is the first register that wasn't
1980 // allocated before this method call, so it would be "reg".
1981 // If parameter is small enough to be saved in range [reg, r4), then
1982 // the end (first after last) register would be reg + param-size-in-regs,
1983 // else parameter would be splitted between registers and stack,
1984 // end register would be r4 in this case.
1985 unsigned ByValRegBegin = Reg;
1986 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1987 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1988 // Note, first register is allocated in the beginning of function already,
1989 // allocate remained amount of registers we need.
1990 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1991 State->AllocateReg(GPRArgRegs);
1992 // A byval parameter that is split between registers and memory needs its
1993 // size truncated here.
1994 // In the case where the entire structure fits in registers, we set the
1995 // size in memory to zero.
1996 Size = std::max<int>(Size - Excess, 0);
1999 /// MatchingStackOffset - Return true if the given stack call argument is
2000 /// already available in the same position (relatively) of the caller's
2001 /// incoming argument stack.
2003 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2004 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2005 const TargetInstrInfo *TII) {
2006 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2008 if (Arg.getOpcode() == ISD::CopyFromReg) {
2009 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2010 if (!TargetRegisterInfo::isVirtualRegister(VR))
2012 MachineInstr *Def = MRI->getVRegDef(VR);
2015 if (!Flags.isByVal()) {
2016 if (!TII->isLoadFromStackSlot(Def, FI))
2021 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2022 if (Flags.isByVal())
2023 // ByVal argument is passed in as a pointer but it's now being
2024 // dereferenced. e.g.
2025 // define @foo(%struct.X* %A) {
2026 // tail call @bar(%struct.X* byval %A)
2029 SDValue Ptr = Ld->getBasePtr();
2030 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2033 FI = FINode->getIndex();
2037 assert(FI != INT_MAX);
2038 if (!MFI->isFixedObjectIndex(FI))
2040 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2043 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2044 /// for tail call optimization. Targets which want to do tail call
2045 /// optimization should implement this function.
2047 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2048 CallingConv::ID CalleeCC,
2050 bool isCalleeStructRet,
2051 bool isCallerStructRet,
2052 const SmallVectorImpl<ISD::OutputArg> &Outs,
2053 const SmallVectorImpl<SDValue> &OutVals,
2054 const SmallVectorImpl<ISD::InputArg> &Ins,
2055 SelectionDAG& DAG) const {
2056 const Function *CallerF = DAG.getMachineFunction().getFunction();
2057 CallingConv::ID CallerCC = CallerF->getCallingConv();
2058 bool CCMatch = CallerCC == CalleeCC;
2060 assert(Subtarget->supportsTailCall());
2062 // Look for obvious safe cases to perform tail call optimization that do not
2063 // require ABI changes. This is what gcc calls sibcall.
2065 // Do not sibcall optimize vararg calls unless the call site is not passing
2067 if (isVarArg && !Outs.empty())
2070 // Exception-handling functions need a special set of instructions to indicate
2071 // a return to the hardware. Tail-calling another function would probably
2073 if (CallerF->hasFnAttribute("interrupt"))
2076 // Also avoid sibcall optimization if either caller or callee uses struct
2077 // return semantics.
2078 if (isCalleeStructRet || isCallerStructRet)
2081 // Externally-defined functions with weak linkage should not be
2082 // tail-called on ARM when the OS does not support dynamic
2083 // pre-emption of symbols, as the AAELF spec requires normal calls
2084 // to undefined weak functions to be replaced with a NOP or jump to the
2085 // next instruction. The behaviour of branch instructions in this
2086 // situation (as used for tail calls) is implementation-defined, so we
2087 // cannot rely on the linker replacing the tail call with a return.
2088 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2089 const GlobalValue *GV = G->getGlobal();
2090 const Triple &TT = getTargetMachine().getTargetTriple();
2091 if (GV->hasExternalWeakLinkage() &&
2092 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2096 // If the calling conventions do not match, then we'd better make sure the
2097 // results are returned in the same way as what the caller expects.
2099 SmallVector<CCValAssign, 16> RVLocs1;
2100 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2101 *DAG.getContext(), Call);
2102 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2104 SmallVector<CCValAssign, 16> RVLocs2;
2105 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2106 *DAG.getContext(), Call);
2107 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2109 if (RVLocs1.size() != RVLocs2.size())
2111 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2112 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2114 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2116 if (RVLocs1[i].isRegLoc()) {
2117 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2120 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2126 // If Caller's vararg or byval argument has been split between registers and
2127 // stack, do not perform tail call, since part of the argument is in caller's
2129 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2130 getInfo<ARMFunctionInfo>();
2131 if (AFI_Caller->getArgRegsSaveSize())
2134 // If the callee takes no arguments then go on to check the results of the
2136 if (!Outs.empty()) {
2137 // Check if stack adjustment is needed. For now, do not do this if any
2138 // argument is passed on the stack.
2139 SmallVector<CCValAssign, 16> ArgLocs;
2140 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2141 *DAG.getContext(), Call);
2142 CCInfo.AnalyzeCallOperands(Outs,
2143 CCAssignFnForNode(CalleeCC, false, isVarArg));
2144 if (CCInfo.getNextStackOffset()) {
2145 MachineFunction &MF = DAG.getMachineFunction();
2147 // Check if the arguments are already laid out in the right way as
2148 // the caller's fixed stack objects.
2149 MachineFrameInfo *MFI = MF.getFrameInfo();
2150 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2151 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2152 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2154 ++i, ++realArgIdx) {
2155 CCValAssign &VA = ArgLocs[i];
2156 EVT RegVT = VA.getLocVT();
2157 SDValue Arg = OutVals[realArgIdx];
2158 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2159 if (VA.getLocInfo() == CCValAssign::Indirect)
2161 if (VA.needsCustom()) {
2162 // f64 and vector types are split into multiple registers or
2163 // register/stack-slot combinations. The types will not match
2164 // the registers; give up on memory f64 refs until we figure
2165 // out what to do about this.
2168 if (!ArgLocs[++i].isRegLoc())
2170 if (RegVT == MVT::v2f64) {
2171 if (!ArgLocs[++i].isRegLoc())
2173 if (!ArgLocs[++i].isRegLoc())
2176 } else if (!VA.isRegLoc()) {
2177 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2189 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2190 MachineFunction &MF, bool isVarArg,
2191 const SmallVectorImpl<ISD::OutputArg> &Outs,
2192 LLVMContext &Context) const {
2193 SmallVector<CCValAssign, 16> RVLocs;
2194 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2195 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2199 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2200 SDLoc DL, SelectionDAG &DAG) {
2201 const MachineFunction &MF = DAG.getMachineFunction();
2202 const Function *F = MF.getFunction();
2204 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2206 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2207 // version of the "preferred return address". These offsets affect the return
2208 // instruction if this is a return from PL1 without hypervisor extensions.
2209 // IRQ/FIQ: +4 "subs pc, lr, #4"
2210 // SWI: 0 "subs pc, lr, #0"
2211 // ABORT: +4 "subs pc, lr, #4"
2212 // UNDEF: +4/+2 "subs pc, lr, #0"
2213 // UNDEF varies depending on where the exception came from ARM or Thumb
2214 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2217 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2220 else if (IntKind == "SWI" || IntKind == "UNDEF")
2223 report_fatal_error("Unsupported interrupt attribute. If present, value "
2224 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2226 RetOps.insert(RetOps.begin() + 1,
2227 DAG.getConstant(LROffset, DL, MVT::i32, false));
2229 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2233 ARMTargetLowering::LowerReturn(SDValue Chain,
2234 CallingConv::ID CallConv, bool isVarArg,
2235 const SmallVectorImpl<ISD::OutputArg> &Outs,
2236 const SmallVectorImpl<SDValue> &OutVals,
2237 SDLoc dl, SelectionDAG &DAG) const {
2239 // CCValAssign - represent the assignment of the return value to a location.
2240 SmallVector<CCValAssign, 16> RVLocs;
2242 // CCState - Info about the registers and stack slots.
2243 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2244 *DAG.getContext(), Call);
2246 // Analyze outgoing return values.
2247 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2251 SmallVector<SDValue, 4> RetOps;
2252 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2253 bool isLittleEndian = Subtarget->isLittle();
2255 MachineFunction &MF = DAG.getMachineFunction();
2256 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2257 AFI->setReturnRegsCount(RVLocs.size());
2259 // Copy the result values into the output registers.
2260 for (unsigned i = 0, realRVLocIdx = 0;
2262 ++i, ++realRVLocIdx) {
2263 CCValAssign &VA = RVLocs[i];
2264 assert(VA.isRegLoc() && "Can only return in registers!");
2266 SDValue Arg = OutVals[realRVLocIdx];
2268 switch (VA.getLocInfo()) {
2269 default: llvm_unreachable("Unknown loc info!");
2270 case CCValAssign::Full: break;
2271 case CCValAssign::BCvt:
2272 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2276 if (VA.needsCustom()) {
2277 if (VA.getLocVT() == MVT::v2f64) {
2278 // Extract the first half and return it in two registers.
2279 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2280 DAG.getConstant(0, dl, MVT::i32));
2281 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2282 DAG.getVTList(MVT::i32, MVT::i32), Half);
2284 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2285 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2287 Flag = Chain.getValue(1);
2288 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2289 VA = RVLocs[++i]; // skip ahead to next loc
2290 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2291 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2293 Flag = Chain.getValue(1);
2294 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2295 VA = RVLocs[++i]; // skip ahead to next loc
2297 // Extract the 2nd half and fall through to handle it as an f64 value.
2298 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2299 DAG.getConstant(1, dl, MVT::i32));
2301 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2303 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2304 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2305 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2306 fmrrd.getValue(isLittleEndian ? 0 : 1),
2308 Flag = Chain.getValue(1);
2309 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2310 VA = RVLocs[++i]; // skip ahead to next loc
2311 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2312 fmrrd.getValue(isLittleEndian ? 1 : 0),
2315 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2317 // Guarantee that all emitted copies are
2318 // stuck together, avoiding something bad.
2319 Flag = Chain.getValue(1);
2320 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2323 // Update chain and glue.
2326 RetOps.push_back(Flag);
2328 // CPUs which aren't M-class use a special sequence to return from
2329 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2330 // though we use "subs pc, lr, #N").
2332 // M-class CPUs actually use a normal return sequence with a special
2333 // (hardware-provided) value in LR, so the normal code path works.
2334 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2335 !Subtarget->isMClass()) {
2336 if (Subtarget->isThumb1Only())
2337 report_fatal_error("interrupt attribute is not supported in Thumb1");
2338 return LowerInterruptReturn(RetOps, dl, DAG);
2341 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2344 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2345 if (N->getNumValues() != 1)
2347 if (!N->hasNUsesOfValue(1, 0))
2350 SDValue TCChain = Chain;
2351 SDNode *Copy = *N->use_begin();
2352 if (Copy->getOpcode() == ISD::CopyToReg) {
2353 // If the copy has a glue operand, we conservatively assume it isn't safe to
2354 // perform a tail call.
2355 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2357 TCChain = Copy->getOperand(0);
2358 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2359 SDNode *VMov = Copy;
2360 // f64 returned in a pair of GPRs.
2361 SmallPtrSet<SDNode*, 2> Copies;
2362 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2364 if (UI->getOpcode() != ISD::CopyToReg)
2368 if (Copies.size() > 2)
2371 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2373 SDValue UseChain = UI->getOperand(0);
2374 if (Copies.count(UseChain.getNode()))
2378 // We are at the top of this chain.
2379 // If the copy has a glue operand, we conservatively assume it
2380 // isn't safe to perform a tail call.
2381 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2387 } else if (Copy->getOpcode() == ISD::BITCAST) {
2388 // f32 returned in a single GPR.
2389 if (!Copy->hasOneUse())
2391 Copy = *Copy->use_begin();
2392 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2394 // If the copy has a glue operand, we conservatively assume it isn't safe to
2395 // perform a tail call.
2396 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2398 TCChain = Copy->getOperand(0);
2403 bool HasRet = false;
2404 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2406 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2407 UI->getOpcode() != ARMISD::INTRET_FLAG)
2419 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2420 if (!Subtarget->supportsTailCall())
2424 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2425 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2431 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2432 // and pass the lower and high parts through.
2433 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2435 SDValue WriteValue = Op->getOperand(2);
2437 // This function is only supposed to be called for i64 type argument.
2438 assert(WriteValue.getValueType() == MVT::i64
2439 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2441 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2442 DAG.getConstant(0, DL, MVT::i32));
2443 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2444 DAG.getConstant(1, DL, MVT::i32));
2445 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2446 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2449 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2450 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2451 // one of the above mentioned nodes. It has to be wrapped because otherwise
2452 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2453 // be used to form addressing mode. These wrapped nodes will be selected
2455 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2456 EVT PtrVT = Op.getValueType();
2457 // FIXME there is no actual debug info here
2459 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2461 if (CP->isMachineConstantPoolEntry())
2462 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2463 CP->getAlignment());
2465 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2466 CP->getAlignment());
2467 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2470 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2471 return MachineJumpTableInfo::EK_Inline;
2474 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2475 SelectionDAG &DAG) const {
2476 MachineFunction &MF = DAG.getMachineFunction();
2477 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2478 unsigned ARMPCLabelIndex = 0;
2480 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2481 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2482 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2484 if (RelocM == Reloc::Static) {
2485 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2487 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2488 ARMPCLabelIndex = AFI->createPICLabelUId();
2489 ARMConstantPoolValue *CPV =
2490 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2491 ARMCP::CPBlockAddress, PCAdj);
2492 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2494 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2496 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2497 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2498 false, false, false, 0);
2499 if (RelocM == Reloc::Static)
2501 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2502 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2505 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2507 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2508 SelectionDAG &DAG) const {
2510 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2511 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2512 MachineFunction &MF = DAG.getMachineFunction();
2513 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2514 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2515 ARMConstantPoolValue *CPV =
2516 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2517 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2518 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2519 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2521 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2522 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2523 false, false, false, 0);
2524 SDValue Chain = Argument.getValue(1);
2526 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2527 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2529 // call __tls_get_addr.
2532 Entry.Node = Argument;
2533 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2534 Args.push_back(Entry);
2536 // FIXME: is there useful debug info available here?
2537 TargetLowering::CallLoweringInfo CLI(DAG);
2538 CLI.setDebugLoc(dl).setChain(Chain)
2539 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2540 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2543 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2544 return CallResult.first;
2547 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2548 // "local exec" model.
2550 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2552 TLSModel::Model model) const {
2553 const GlobalValue *GV = GA->getGlobal();
2556 SDValue Chain = DAG.getEntryNode();
2557 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2558 // Get the Thread Pointer
2559 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2561 if (model == TLSModel::InitialExec) {
2562 MachineFunction &MF = DAG.getMachineFunction();
2563 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2564 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2565 // Initial exec model.
2566 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2567 ARMConstantPoolValue *CPV =
2568 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2569 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2571 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2572 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2573 Offset = DAG.getLoad(
2574 PtrVT, dl, Chain, Offset,
2575 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2577 Chain = Offset.getValue(1);
2579 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2580 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2582 Offset = DAG.getLoad(
2583 PtrVT, dl, Chain, Offset,
2584 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2588 assert(model == TLSModel::LocalExec);
2589 ARMConstantPoolValue *CPV =
2590 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2591 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2592 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2593 Offset = DAG.getLoad(
2594 PtrVT, dl, Chain, Offset,
2595 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2599 // The address of the thread local variable is the add of the thread
2600 // pointer with the offset of the variable.
2601 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2605 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2606 // TODO: implement the "local dynamic" model
2607 assert(Subtarget->isTargetELF() &&
2608 "TLS not implemented for non-ELF targets");
2609 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2610 if (DAG.getTarget().Options.EmulatedTLS)
2611 return LowerToTLSEmulatedModel(GA, DAG);
2613 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2616 case TLSModel::GeneralDynamic:
2617 case TLSModel::LocalDynamic:
2618 return LowerToTLSGeneralDynamicModel(GA, DAG);
2619 case TLSModel::InitialExec:
2620 case TLSModel::LocalExec:
2621 return LowerToTLSExecModels(GA, DAG, model);
2623 llvm_unreachable("bogus TLS model");
2626 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2627 SelectionDAG &DAG) const {
2628 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2630 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2631 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2632 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2633 ARMConstantPoolValue *CPV =
2634 ARMConstantPoolConstant::Create(GV,
2635 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2636 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2637 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2638 SDValue Result = DAG.getLoad(
2639 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2640 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2642 SDValue Chain = Result.getValue(1);
2643 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2644 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2646 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2647 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2648 false, false, false, 0);
2652 // If we have T2 ops, we can materialize the address directly via movt/movw
2653 // pair. This is always cheaper.
2654 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2656 // FIXME: Once remat is capable of dealing with instructions with register
2657 // operands, expand this into two nodes.
2658 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2659 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2661 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2662 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2664 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2665 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2670 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2671 SelectionDAG &DAG) const {
2672 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2674 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2675 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2677 if (Subtarget->useMovt(DAG.getMachineFunction()))
2680 // FIXME: Once remat is capable of dealing with instructions with register
2681 // operands, expand this into multiple nodes
2683 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2685 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2686 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2688 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2689 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2690 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2691 false, false, false, 0);
2695 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2696 SelectionDAG &DAG) const {
2697 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2698 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2699 "Windows on ARM expects to use movw/movt");
2701 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2702 const ARMII::TOF TargetFlags =
2703 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2704 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2710 // FIXME: Once remat is capable of dealing with instructions with register
2711 // operands, expand this into two nodes.
2712 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2713 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2715 if (GV->hasDLLImportStorageClass())
2716 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2717 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2718 false, false, false, 0);
2722 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2723 SelectionDAG &DAG) const {
2724 assert(Subtarget->isTargetELF() &&
2725 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2726 MachineFunction &MF = DAG.getMachineFunction();
2727 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2728 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2729 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2731 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2732 ARMConstantPoolValue *CPV =
2733 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2734 ARMPCLabelIndex, PCAdj);
2735 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2736 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2738 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2739 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2740 false, false, false, 0);
2741 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2742 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2746 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2748 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2749 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2750 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2751 Op.getOperand(1), Val);
2755 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2757 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2758 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2761 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2762 SelectionDAG &DAG) const {
2764 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2769 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2770 const ARMSubtarget *Subtarget) const {
2771 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2774 default: return SDValue(); // Don't custom lower most intrinsics.
2775 case Intrinsic::arm_rbit: {
2776 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2777 "RBIT intrinsic must have i32 type!");
2778 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2780 case Intrinsic::arm_thread_pointer: {
2781 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2782 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2784 case Intrinsic::eh_sjlj_lsda: {
2785 MachineFunction &MF = DAG.getMachineFunction();
2786 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2787 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2788 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2789 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2791 unsigned PCAdj = (RelocM != Reloc::PIC_)
2792 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2793 ARMConstantPoolValue *CPV =
2794 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2795 ARMCP::CPLSDA, PCAdj);
2796 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2797 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2798 SDValue Result = DAG.getLoad(
2799 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2800 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2803 if (RelocM == Reloc::PIC_) {
2804 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2805 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2809 case Intrinsic::arm_neon_vmulls:
2810 case Intrinsic::arm_neon_vmullu: {
2811 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2812 ? ARMISD::VMULLs : ARMISD::VMULLu;
2813 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2814 Op.getOperand(1), Op.getOperand(2));
2816 case Intrinsic::arm_neon_vminnm:
2817 case Intrinsic::arm_neon_vmaxnm: {
2818 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2819 ? ISD::FMINNUM : ISD::FMAXNUM;
2820 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2821 Op.getOperand(1), Op.getOperand(2));
2823 case Intrinsic::arm_neon_vminu:
2824 case Intrinsic::arm_neon_vmaxu: {
2825 if (Op.getValueType().isFloatingPoint())
2827 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2828 ? ISD::UMIN : ISD::UMAX;
2829 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2830 Op.getOperand(1), Op.getOperand(2));
2832 case Intrinsic::arm_neon_vmins:
2833 case Intrinsic::arm_neon_vmaxs: {
2834 // v{min,max}s is overloaded between signed integers and floats.
2835 if (!Op.getValueType().isFloatingPoint()) {
2836 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2837 ? ISD::SMIN : ISD::SMAX;
2838 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2839 Op.getOperand(1), Op.getOperand(2));
2841 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2842 ? ISD::FMINNAN : ISD::FMAXNAN;
2843 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2844 Op.getOperand(1), Op.getOperand(2));
2849 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2850 const ARMSubtarget *Subtarget) {
2851 // FIXME: handle "fence singlethread" more efficiently.
2853 if (!Subtarget->hasDataBarrier()) {
2854 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2855 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2857 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2858 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2859 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2860 DAG.getConstant(0, dl, MVT::i32));
2863 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2864 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2865 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2866 if (Subtarget->isMClass()) {
2867 // Only a full system barrier exists in the M-class architectures.
2868 Domain = ARM_MB::SY;
2869 } else if (Subtarget->isSwift() && Ord == Release) {
2870 // Swift happens to implement ISHST barriers in a way that's compatible with
2871 // Release semantics but weaker than ISH so we'd be fools not to use
2872 // it. Beware: other processors probably don't!
2873 Domain = ARM_MB::ISHST;
2876 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2877 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2878 DAG.getConstant(Domain, dl, MVT::i32));
2881 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2882 const ARMSubtarget *Subtarget) {
2883 // ARM pre v5TE and Thumb1 does not have preload instructions.
2884 if (!(Subtarget->isThumb2() ||
2885 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2886 // Just preserve the chain.
2887 return Op.getOperand(0);
2890 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2892 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2893 // ARMv7 with MP extension has PLDW.
2894 return Op.getOperand(0);
2896 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2897 if (Subtarget->isThumb()) {
2899 isRead = ~isRead & 1;
2900 isData = ~isData & 1;
2903 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2904 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2905 DAG.getConstant(isData, dl, MVT::i32));
2908 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2909 MachineFunction &MF = DAG.getMachineFunction();
2910 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2912 // vastart just stores the address of the VarArgsFrameIndex slot into the
2913 // memory location argument.
2915 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2916 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2917 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2918 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2919 MachinePointerInfo(SV), false, false, 0);
2923 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2924 SDValue &Root, SelectionDAG &DAG,
2926 MachineFunction &MF = DAG.getMachineFunction();
2927 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2929 const TargetRegisterClass *RC;
2930 if (AFI->isThumb1OnlyFunction())
2931 RC = &ARM::tGPRRegClass;
2933 RC = &ARM::GPRRegClass;
2935 // Transform the arguments stored in physical registers into virtual ones.
2936 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2937 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2940 if (NextVA.isMemLoc()) {
2941 MachineFrameInfo *MFI = MF.getFrameInfo();
2942 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2944 // Create load node to retrieve arguments from the stack.
2945 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2946 ArgValue2 = DAG.getLoad(
2947 MVT::i32, dl, Root, FIN,
2948 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2951 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2952 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2954 if (!Subtarget->isLittle())
2955 std::swap (ArgValue, ArgValue2);
2956 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2959 // The remaining GPRs hold either the beginning of variable-argument
2960 // data, or the beginning of an aggregate passed by value (usually
2961 // byval). Either way, we allocate stack slots adjacent to the data
2962 // provided by our caller, and store the unallocated registers there.
2963 // If this is a variadic function, the va_list pointer will begin with
2964 // these values; otherwise, this reassembles a (byval) structure that
2965 // was split between registers and memory.
2966 // Return: The frame index registers were stored into.
2968 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2969 SDLoc dl, SDValue &Chain,
2970 const Value *OrigArg,
2971 unsigned InRegsParamRecordIdx,
2973 unsigned ArgSize) const {
2974 // Currently, two use-cases possible:
2975 // Case #1. Non-var-args function, and we meet first byval parameter.
2976 // Setup first unallocated register as first byval register;
2977 // eat all remained registers
2978 // (these two actions are performed by HandleByVal method).
2979 // Then, here, we initialize stack frame with
2980 // "store-reg" instructions.
2981 // Case #2. Var-args function, that doesn't contain byval parameters.
2982 // The same: eat all remained unallocated registers,
2983 // initialize stack frame.
2985 MachineFunction &MF = DAG.getMachineFunction();
2986 MachineFrameInfo *MFI = MF.getFrameInfo();
2987 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2988 unsigned RBegin, REnd;
2989 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2990 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2992 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2993 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2998 ArgOffset = -4 * (ARM::R4 - RBegin);
3000 auto PtrVT = getPointerTy(DAG.getDataLayout());
3001 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3002 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3004 SmallVector<SDValue, 4> MemOps;
3005 const TargetRegisterClass *RC =
3006 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3008 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3009 unsigned VReg = MF.addLiveIn(Reg, RC);
3010 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3012 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3013 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3014 MemOps.push_back(Store);
3015 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3018 if (!MemOps.empty())
3019 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3023 // Setup stack frame, the va_list pointer will start from.
3025 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3026 SDLoc dl, SDValue &Chain,
3028 unsigned TotalArgRegsSaveSize,
3029 bool ForceMutable) const {
3030 MachineFunction &MF = DAG.getMachineFunction();
3031 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3033 // Try to store any remaining integer argument regs
3034 // to their spots on the stack so that they may be loaded by deferencing
3035 // the result of va_next.
3036 // If there is no regs to be stored, just point address after last
3037 // argument passed via stack.
3038 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3039 CCInfo.getInRegsParamsCount(),
3040 CCInfo.getNextStackOffset(), 4);
3041 AFI->setVarArgsFrameIndex(FrameIndex);
3045 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3046 CallingConv::ID CallConv, bool isVarArg,
3047 const SmallVectorImpl<ISD::InputArg>
3049 SDLoc dl, SelectionDAG &DAG,
3050 SmallVectorImpl<SDValue> &InVals)
3052 MachineFunction &MF = DAG.getMachineFunction();
3053 MachineFrameInfo *MFI = MF.getFrameInfo();
3055 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3057 // Assign locations to all of the incoming arguments.
3058 SmallVector<CCValAssign, 16> ArgLocs;
3059 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3060 *DAG.getContext(), Prologue);
3061 CCInfo.AnalyzeFormalArguments(Ins,
3062 CCAssignFnForNode(CallConv, /* Return*/ false,
3065 SmallVector<SDValue, 16> ArgValues;
3067 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3068 unsigned CurArgIdx = 0;
3070 // Initially ArgRegsSaveSize is zero.
3071 // Then we increase this value each time we meet byval parameter.
3072 // We also increase this value in case of varargs function.
3073 AFI->setArgRegsSaveSize(0);
3075 // Calculate the amount of stack space that we need to allocate to store
3076 // byval and variadic arguments that are passed in registers.
3077 // We need to know this before we allocate the first byval or variadic
3078 // argument, as they will be allocated a stack slot below the CFA (Canonical
3079 // Frame Address, the stack pointer at entry to the function).
3080 unsigned ArgRegBegin = ARM::R4;
3081 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3082 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3085 CCValAssign &VA = ArgLocs[i];
3086 unsigned Index = VA.getValNo();
3087 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3088 if (!Flags.isByVal())
3091 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3092 unsigned RBegin, REnd;
3093 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3094 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3096 CCInfo.nextInRegsParam();
3098 CCInfo.rewindByValRegsInfo();
3100 int lastInsIndex = -1;
3101 if (isVarArg && MFI->hasVAStart()) {
3102 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3103 if (RegIdx != array_lengthof(GPRArgRegs))
3104 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3107 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3108 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3109 auto PtrVT = getPointerTy(DAG.getDataLayout());
3111 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3112 CCValAssign &VA = ArgLocs[i];
3113 if (Ins[VA.getValNo()].isOrigArg()) {
3114 std::advance(CurOrigArg,
3115 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3116 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3118 // Arguments stored in registers.
3119 if (VA.isRegLoc()) {
3120 EVT RegVT = VA.getLocVT();
3122 if (VA.needsCustom()) {
3123 // f64 and vector types are split up into multiple registers or
3124 // combinations of registers and stack slots.
3125 if (VA.getLocVT() == MVT::v2f64) {
3126 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3128 VA = ArgLocs[++i]; // skip ahead to next loc
3130 if (VA.isMemLoc()) {
3131 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3132 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3133 ArgValue2 = DAG.getLoad(
3134 MVT::f64, dl, Chain, FIN,
3135 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3136 false, false, false, 0);
3138 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3141 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3142 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3143 ArgValue, ArgValue1,
3144 DAG.getIntPtrConstant(0, dl));
3145 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3146 ArgValue, ArgValue2,
3147 DAG.getIntPtrConstant(1, dl));
3149 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3152 const TargetRegisterClass *RC;
3154 if (RegVT == MVT::f32)
3155 RC = &ARM::SPRRegClass;
3156 else if (RegVT == MVT::f64)
3157 RC = &ARM::DPRRegClass;
3158 else if (RegVT == MVT::v2f64)
3159 RC = &ARM::QPRRegClass;
3160 else if (RegVT == MVT::i32)
3161 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3162 : &ARM::GPRRegClass;
3164 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3166 // Transform the arguments in physical registers into virtual ones.
3167 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3168 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3171 // If this is an 8 or 16-bit value, it is really passed promoted
3172 // to 32 bits. Insert an assert[sz]ext to capture this, then
3173 // truncate to the right size.
3174 switch (VA.getLocInfo()) {
3175 default: llvm_unreachable("Unknown loc info!");
3176 case CCValAssign::Full: break;
3177 case CCValAssign::BCvt:
3178 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3180 case CCValAssign::SExt:
3181 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3182 DAG.getValueType(VA.getValVT()));
3183 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3185 case CCValAssign::ZExt:
3186 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3187 DAG.getValueType(VA.getValVT()));
3188 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3192 InVals.push_back(ArgValue);
3194 } else { // VA.isRegLoc()
3197 assert(VA.isMemLoc());
3198 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3200 int index = VA.getValNo();
3202 // Some Ins[] entries become multiple ArgLoc[] entries.
3203 // Process them only once.
3204 if (index != lastInsIndex)
3206 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3207 // FIXME: For now, all byval parameter objects are marked mutable.
3208 // This can be changed with more analysis.
3209 // In case of tail call optimization mark all arguments mutable.
3210 // Since they could be overwritten by lowering of arguments in case of
3212 if (Flags.isByVal()) {
3213 assert(Ins[index].isOrigArg() &&
3214 "Byval arguments cannot be implicit");
3215 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3217 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3218 CurByValIndex, VA.getLocMemOffset(),
3219 Flags.getByValSize());
3220 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3221 CCInfo.nextInRegsParam();
3223 unsigned FIOffset = VA.getLocMemOffset();
3224 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3227 // Create load nodes to retrieve arguments from the stack.
3228 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3229 InVals.push_back(DAG.getLoad(
3230 VA.getValVT(), dl, Chain, FIN,
3231 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3232 false, false, false, 0));
3234 lastInsIndex = index;
3240 if (isVarArg && MFI->hasVAStart())
3241 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3242 CCInfo.getNextStackOffset(),
3243 TotalArgRegsSaveSize);
3245 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3250 /// isFloatingPointZero - Return true if this is +0.0.
3251 static bool isFloatingPointZero(SDValue Op) {
3252 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3253 return CFP->getValueAPF().isPosZero();
3254 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3255 // Maybe this has already been legalized into the constant pool?
3256 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3257 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3258 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3259 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3260 return CFP->getValueAPF().isPosZero();
3262 } else if (Op->getOpcode() == ISD::BITCAST &&
3263 Op->getValueType(0) == MVT::f64) {
3264 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3265 // created by LowerConstantFP().
3266 SDValue BitcastOp = Op->getOperand(0);
3267 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3268 SDValue MoveOp = BitcastOp->getOperand(0);
3269 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3270 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3278 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3279 /// the given operands.
3281 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3282 SDValue &ARMcc, SelectionDAG &DAG,
3284 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3285 unsigned C = RHSC->getZExtValue();
3286 if (!isLegalICmpImmediate(C)) {
3287 // Constant does not fit, try adjusting it by one?
3292 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3293 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3294 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3299 if (C != 0 && isLegalICmpImmediate(C-1)) {
3300 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3301 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3306 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3307 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3308 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3313 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3314 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3315 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3322 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3323 ARMISD::NodeType CompareType;
3326 CompareType = ARMISD::CMP;
3331 CompareType = ARMISD::CMPZ;
3334 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3335 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3338 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3340 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3342 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3344 if (!isFloatingPointZero(RHS))
3345 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3347 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3348 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3351 /// duplicateCmp - Glue values can have only one use, so this function
3352 /// duplicates a comparison node.
3354 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3355 unsigned Opc = Cmp.getOpcode();
3357 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3358 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3360 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3361 Cmp = Cmp.getOperand(0);
3362 Opc = Cmp.getOpcode();
3363 if (Opc == ARMISD::CMPFP)
3364 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3366 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3367 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3369 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3372 std::pair<SDValue, SDValue>
3373 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3374 SDValue &ARMcc) const {
3375 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3377 SDValue Value, OverflowCmp;
3378 SDValue LHS = Op.getOperand(0);
3379 SDValue RHS = Op.getOperand(1);
3382 // FIXME: We are currently always generating CMPs because we don't support
3383 // generating CMN through the backend. This is not as good as the natural
3384 // CMP case because it causes a register dependency and cannot be folded
3387 switch (Op.getOpcode()) {
3389 llvm_unreachable("Unknown overflow instruction!");
3391 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3392 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3393 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3396 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3397 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3398 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3401 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3402 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3403 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3406 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3407 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3408 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3412 return std::make_pair(Value, OverflowCmp);
3417 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3418 // Let legalize expand this if it isn't a legal type yet.
3419 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3422 SDValue Value, OverflowCmp;
3424 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3425 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3427 // We use 0 and 1 as false and true values.
3428 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3429 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3430 EVT VT = Op.getValueType();
3432 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3433 ARMcc, CCR, OverflowCmp);
3435 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3436 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3440 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3441 SDValue Cond = Op.getOperand(0);
3442 SDValue SelectTrue = Op.getOperand(1);
3443 SDValue SelectFalse = Op.getOperand(2);
3445 unsigned Opc = Cond.getOpcode();
3447 if (Cond.getResNo() == 1 &&
3448 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3449 Opc == ISD::USUBO)) {
3450 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3453 SDValue Value, OverflowCmp;
3455 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3456 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3457 EVT VT = Op.getValueType();
3459 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3465 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3466 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3468 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3469 const ConstantSDNode *CMOVTrue =
3470 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3471 const ConstantSDNode *CMOVFalse =
3472 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3474 if (CMOVTrue && CMOVFalse) {
3475 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3476 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3480 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3482 False = SelectFalse;
3483 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3488 if (True.getNode() && False.getNode()) {
3489 EVT VT = Op.getValueType();
3490 SDValue ARMcc = Cond.getOperand(2);
3491 SDValue CCR = Cond.getOperand(3);
3492 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3493 assert(True.getValueType() == VT);
3494 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3499 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3500 // undefined bits before doing a full-word comparison with zero.
3501 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3502 DAG.getConstant(1, dl, Cond.getValueType()));
3504 return DAG.getSelectCC(dl, Cond,
3505 DAG.getConstant(0, dl, Cond.getValueType()),
3506 SelectTrue, SelectFalse, ISD::SETNE);
3509 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3510 bool &swpCmpOps, bool &swpVselOps) {
3511 // Start by selecting the GE condition code for opcodes that return true for
3513 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3515 CondCode = ARMCC::GE;
3517 // and GT for opcodes that return false for 'equality'.
3518 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3520 CondCode = ARMCC::GT;
3522 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3523 // to swap the compare operands.
3524 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3528 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3529 // If we have an unordered opcode, we need to swap the operands to the VSEL
3530 // instruction (effectively negating the condition).
3532 // This also has the effect of swapping which one of 'less' or 'greater'
3533 // returns true, so we also swap the compare operands. It also switches
3534 // whether we return true for 'equality', so we compensate by picking the
3535 // opposite condition code to our original choice.
3536 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3537 CC == ISD::SETUGT) {
3538 swpCmpOps = !swpCmpOps;
3539 swpVselOps = !swpVselOps;
3540 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3543 // 'ordered' is 'anything but unordered', so use the VS condition code and
3544 // swap the VSEL operands.
3545 if (CC == ISD::SETO) {
3546 CondCode = ARMCC::VS;
3550 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3551 // code and swap the VSEL operands.
3552 if (CC == ISD::SETUNE) {
3553 CondCode = ARMCC::EQ;
3558 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3559 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3560 SDValue Cmp, SelectionDAG &DAG) const {
3561 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3562 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3563 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3564 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3565 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3567 SDValue TrueLow = TrueVal.getValue(0);
3568 SDValue TrueHigh = TrueVal.getValue(1);
3569 SDValue FalseLow = FalseVal.getValue(0);
3570 SDValue FalseHigh = FalseVal.getValue(1);
3572 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3574 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3575 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3577 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3579 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3584 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3585 EVT VT = Op.getValueType();
3586 SDValue LHS = Op.getOperand(0);
3587 SDValue RHS = Op.getOperand(1);
3588 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3589 SDValue TrueVal = Op.getOperand(2);
3590 SDValue FalseVal = Op.getOperand(3);
3593 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3594 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3597 // If softenSetCCOperands only returned one value, we should compare it to
3599 if (!RHS.getNode()) {
3600 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3605 if (LHS.getValueType() == MVT::i32) {
3606 // Try to generate VSEL on ARMv8.
3607 // The VSEL instruction can't use all the usual ARM condition
3608 // codes: it only has two bits to select the condition code, so it's
3609 // constrained to use only GE, GT, VS and EQ.
3611 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3612 // swap the operands of the previous compare instruction (effectively
3613 // inverting the compare condition, swapping 'less' and 'greater') and
3614 // sometimes need to swap the operands to the VSEL (which inverts the
3615 // condition in the sense of firing whenever the previous condition didn't)
3616 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3617 TrueVal.getValueType() == MVT::f64)) {
3618 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3619 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3620 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3621 CC = ISD::getSetCCInverse(CC, true);
3622 std::swap(TrueVal, FalseVal);
3627 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3628 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3629 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3632 ARMCC::CondCodes CondCode, CondCode2;
3633 FPCCToARMCC(CC, CondCode, CondCode2);
3635 // Try to generate VMAXNM/VMINNM on ARMv8.
3636 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3637 TrueVal.getValueType() == MVT::f64)) {
3638 bool swpCmpOps = false;
3639 bool swpVselOps = false;
3640 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3642 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3643 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3645 std::swap(LHS, RHS);
3647 std::swap(TrueVal, FalseVal);
3651 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3652 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3653 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3654 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3655 if (CondCode2 != ARMCC::AL) {
3656 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3657 // FIXME: Needs another CMP because flag can have but one use.
3658 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3659 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3664 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3665 /// to morph to an integer compare sequence.
3666 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3667 const ARMSubtarget *Subtarget) {
3668 SDNode *N = Op.getNode();
3669 if (!N->hasOneUse())
3670 // Otherwise it requires moving the value from fp to integer registers.
3672 if (!N->getNumValues())
3674 EVT VT = Op.getValueType();
3675 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3676 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3677 // vmrs are very slow, e.g. cortex-a8.
3680 if (isFloatingPointZero(Op)) {
3684 return ISD::isNormalLoad(N);
3687 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3688 if (isFloatingPointZero(Op))
3689 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3691 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3692 return DAG.getLoad(MVT::i32, SDLoc(Op),
3693 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3694 Ld->isVolatile(), Ld->isNonTemporal(),
3695 Ld->isInvariant(), Ld->getAlignment());
3697 llvm_unreachable("Unknown VFP cmp argument!");
3700 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3701 SDValue &RetVal1, SDValue &RetVal2) {
3704 if (isFloatingPointZero(Op)) {
3705 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3706 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3710 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3711 SDValue Ptr = Ld->getBasePtr();
3712 RetVal1 = DAG.getLoad(MVT::i32, dl,
3713 Ld->getChain(), Ptr,
3714 Ld->getPointerInfo(),
3715 Ld->isVolatile(), Ld->isNonTemporal(),
3716 Ld->isInvariant(), Ld->getAlignment());
3718 EVT PtrType = Ptr.getValueType();
3719 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3720 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3721 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3722 RetVal2 = DAG.getLoad(MVT::i32, dl,
3723 Ld->getChain(), NewPtr,
3724 Ld->getPointerInfo().getWithOffset(4),
3725 Ld->isVolatile(), Ld->isNonTemporal(),
3726 Ld->isInvariant(), NewAlign);
3730 llvm_unreachable("Unknown VFP cmp argument!");
3733 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3734 /// f32 and even f64 comparisons to integer ones.
3736 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3737 SDValue Chain = Op.getOperand(0);
3738 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3739 SDValue LHS = Op.getOperand(2);
3740 SDValue RHS = Op.getOperand(3);
3741 SDValue Dest = Op.getOperand(4);
3744 bool LHSSeenZero = false;
3745 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3746 bool RHSSeenZero = false;
3747 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3748 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3749 // If unsafe fp math optimization is enabled and there are no other uses of
3750 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3751 // to an integer comparison.
3752 if (CC == ISD::SETOEQ)
3754 else if (CC == ISD::SETUNE)
3757 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3759 if (LHS.getValueType() == MVT::f32) {
3760 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3761 bitcastf32Toi32(LHS, DAG), Mask);
3762 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3763 bitcastf32Toi32(RHS, DAG), Mask);
3764 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3765 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3766 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3767 Chain, Dest, ARMcc, CCR, Cmp);
3772 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3773 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3774 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3775 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3776 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3777 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3778 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3779 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3780 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3786 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3787 SDValue Chain = Op.getOperand(0);
3788 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3789 SDValue LHS = Op.getOperand(2);
3790 SDValue RHS = Op.getOperand(3);
3791 SDValue Dest = Op.getOperand(4);
3794 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3795 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3798 // If softenSetCCOperands only returned one value, we should compare it to
3800 if (!RHS.getNode()) {
3801 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3806 if (LHS.getValueType() == MVT::i32) {
3808 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3809 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3810 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3811 Chain, Dest, ARMcc, CCR, Cmp);
3814 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3816 if (getTargetMachine().Options.UnsafeFPMath &&
3817 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3818 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3819 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3820 if (Result.getNode())
3824 ARMCC::CondCodes CondCode, CondCode2;
3825 FPCCToARMCC(CC, CondCode, CondCode2);
3827 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3828 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3829 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3830 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3831 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3832 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3833 if (CondCode2 != ARMCC::AL) {
3834 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3835 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3836 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3841 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3842 SDValue Chain = Op.getOperand(0);
3843 SDValue Table = Op.getOperand(1);
3844 SDValue Index = Op.getOperand(2);
3847 EVT PTy = getPointerTy(DAG.getDataLayout());
3848 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3849 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3850 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3851 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3852 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3853 if (Subtarget->isThumb2()) {
3854 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3855 // which does another jump to the destination. This also makes it easier
3856 // to translate it to TBB / TBH later.
3857 // FIXME: This might not work if the function is extremely large.
3858 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3859 Addr, Op.getOperand(2), JTI);
3861 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3863 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3864 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3865 false, false, false, 0);
3866 Chain = Addr.getValue(1);
3867 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3868 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3871 DAG.getLoad(PTy, dl, Chain, Addr,
3872 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3873 false, false, false, 0);
3874 Chain = Addr.getValue(1);
3875 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3879 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3880 EVT VT = Op.getValueType();
3883 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3884 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3886 return DAG.UnrollVectorOp(Op.getNode());
3889 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3890 "Invalid type for custom lowering!");
3891 if (VT != MVT::v4i16)
3892 return DAG.UnrollVectorOp(Op.getNode());
3894 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3895 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3898 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3899 EVT VT = Op.getValueType();
3901 return LowerVectorFP_TO_INT(Op, DAG);
3902 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3904 if (Op.getOpcode() == ISD::FP_TO_SINT)
3905 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3908 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3910 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3911 /*isSigned*/ false, SDLoc(Op)).first;
3917 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3918 EVT VT = Op.getValueType();
3921 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3922 if (VT.getVectorElementType() == MVT::f32)
3924 return DAG.UnrollVectorOp(Op.getNode());
3927 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3928 "Invalid type for custom lowering!");
3929 if (VT != MVT::v4f32)
3930 return DAG.UnrollVectorOp(Op.getNode());
3934 switch (Op.getOpcode()) {
3935 default: llvm_unreachable("Invalid opcode!");
3936 case ISD::SINT_TO_FP:
3937 CastOpc = ISD::SIGN_EXTEND;
3938 Opc = ISD::SINT_TO_FP;
3940 case ISD::UINT_TO_FP:
3941 CastOpc = ISD::ZERO_EXTEND;
3942 Opc = ISD::UINT_TO_FP;
3946 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3947 return DAG.getNode(Opc, dl, VT, Op);
3950 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3951 EVT VT = Op.getValueType();
3953 return LowerVectorINT_TO_FP(Op, DAG);
3954 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3956 if (Op.getOpcode() == ISD::SINT_TO_FP)
3957 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3960 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3962 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3963 /*isSigned*/ false, SDLoc(Op)).first;
3969 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3970 // Implement fcopysign with a fabs and a conditional fneg.
3971 SDValue Tmp0 = Op.getOperand(0);
3972 SDValue Tmp1 = Op.getOperand(1);
3974 EVT VT = Op.getValueType();
3975 EVT SrcVT = Tmp1.getValueType();
3976 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3977 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3978 bool UseNEON = !InGPR && Subtarget->hasNEON();
3981 // Use VBSL to copy the sign bit.
3982 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3983 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3984 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3985 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3987 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3988 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3989 DAG.getConstant(32, dl, MVT::i32));
3990 else /*if (VT == MVT::f32)*/
3991 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3992 if (SrcVT == MVT::f32) {
3993 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3995 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3996 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3997 DAG.getConstant(32, dl, MVT::i32));
3998 } else if (VT == MVT::f32)
3999 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4000 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4001 DAG.getConstant(32, dl, MVT::i32));
4002 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4003 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4005 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4007 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4008 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4009 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4011 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4012 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4013 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4014 if (VT == MVT::f32) {
4015 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4016 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4017 DAG.getConstant(0, dl, MVT::i32));
4019 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4025 // Bitcast operand 1 to i32.
4026 if (SrcVT == MVT::f64)
4027 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4029 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4031 // Or in the signbit with integer operations.
4032 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4033 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4034 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4035 if (VT == MVT::f32) {
4036 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4037 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4038 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4039 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4042 // f64: Or the high part with signbit and then combine two parts.
4043 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4045 SDValue Lo = Tmp0.getValue(0);
4046 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4047 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4048 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4051 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4052 MachineFunction &MF = DAG.getMachineFunction();
4053 MachineFrameInfo *MFI = MF.getFrameInfo();
4054 MFI->setReturnAddressIsTaken(true);
4056 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4059 EVT VT = Op.getValueType();
4061 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4063 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4064 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4065 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4066 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4067 MachinePointerInfo(), false, false, false, 0);
4070 // Return LR, which contains the return address. Mark it an implicit live-in.
4071 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4072 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4075 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4076 const ARMBaseRegisterInfo &ARI =
4077 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4078 MachineFunction &MF = DAG.getMachineFunction();
4079 MachineFrameInfo *MFI = MF.getFrameInfo();
4080 MFI->setFrameAddressIsTaken(true);
4082 EVT VT = Op.getValueType();
4083 SDLoc dl(Op); // FIXME probably not meaningful
4084 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4085 unsigned FrameReg = ARI.getFrameRegister(MF);
4086 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4088 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4089 MachinePointerInfo(),
4090 false, false, false, 0);
4094 // FIXME? Maybe this could be a TableGen attribute on some registers and
4095 // this table could be generated automatically from RegInfo.
4096 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4097 SelectionDAG &DAG) const {
4098 unsigned Reg = StringSwitch<unsigned>(RegName)
4099 .Case("sp", ARM::SP)
4103 report_fatal_error(Twine("Invalid register name \""
4104 + StringRef(RegName) + "\"."));
4107 // Result is 64 bit value so split into two 32 bit values and return as a
4109 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4110 SelectionDAG &DAG) {
4113 // This function is only supposed to be called for i64 type destination.
4114 assert(N->getValueType(0) == MVT::i64
4115 && "ExpandREAD_REGISTER called for non-i64 type result.");
4117 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4118 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4122 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4124 Results.push_back(Read.getOperand(0));
4127 /// ExpandBITCAST - If the target supports VFP, this function is called to
4128 /// expand a bit convert where either the source or destination type is i64 to
4129 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4130 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4131 /// vectors), since the legalizer won't know what to do with that.
4132 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4133 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4135 SDValue Op = N->getOperand(0);
4137 // This function is only supposed to be called for i64 types, either as the
4138 // source or destination of the bit convert.
4139 EVT SrcVT = Op.getValueType();
4140 EVT DstVT = N->getValueType(0);
4141 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4142 "ExpandBITCAST called for non-i64 type");
4144 // Turn i64->f64 into VMOVDRR.
4145 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4146 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4147 DAG.getConstant(0, dl, MVT::i32));
4148 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4149 DAG.getConstant(1, dl, MVT::i32));
4150 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4151 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4154 // Turn f64->i64 into VMOVRRD.
4155 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4157 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4158 SrcVT.getVectorNumElements() > 1)
4159 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4160 DAG.getVTList(MVT::i32, MVT::i32),
4161 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4163 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4164 DAG.getVTList(MVT::i32, MVT::i32), Op);
4165 // Merge the pieces into a single i64 value.
4166 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4172 /// getZeroVector - Returns a vector of specified type with all zero elements.
4173 /// Zero vectors are used to represent vector negation and in those cases
4174 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4175 /// not support i64 elements, so sometimes the zero vectors will need to be
4176 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4178 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4179 assert(VT.isVector() && "Expected a vector type");
4180 // The canonical modified immediate encoding of a zero vector is....0!
4181 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4182 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4183 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4184 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4187 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4188 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4189 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4190 SelectionDAG &DAG) const {
4191 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4192 EVT VT = Op.getValueType();
4193 unsigned VTBits = VT.getSizeInBits();
4195 SDValue ShOpLo = Op.getOperand(0);
4196 SDValue ShOpHi = Op.getOperand(1);
4197 SDValue ShAmt = Op.getOperand(2);
4199 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4201 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4203 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4204 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4205 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4206 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4207 DAG.getConstant(VTBits, dl, MVT::i32));
4208 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4209 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4210 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4212 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4213 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4214 ISD::SETGE, ARMcc, DAG, dl);
4215 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4216 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4219 SDValue Ops[2] = { Lo, Hi };
4220 return DAG.getMergeValues(Ops, dl);
4223 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4224 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4225 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4226 SelectionDAG &DAG) const {
4227 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4228 EVT VT = Op.getValueType();
4229 unsigned VTBits = VT.getSizeInBits();
4231 SDValue ShOpLo = Op.getOperand(0);
4232 SDValue ShOpHi = Op.getOperand(1);
4233 SDValue ShAmt = Op.getOperand(2);
4236 assert(Op.getOpcode() == ISD::SHL_PARTS);
4237 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4238 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4239 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4240 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4241 DAG.getConstant(VTBits, dl, MVT::i32));
4242 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4243 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4245 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4246 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4247 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4248 ISD::SETGE, ARMcc, DAG, dl);
4249 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4250 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4253 SDValue Ops[2] = { Lo, Hi };
4254 return DAG.getMergeValues(Ops, dl);
4257 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4258 SelectionDAG &DAG) const {
4259 // The rounding mode is in bits 23:22 of the FPSCR.
4260 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4261 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4262 // so that the shift + and get folded into a bitfield extract.
4264 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4265 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4267 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4268 DAG.getConstant(1U << 22, dl, MVT::i32));
4269 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4270 DAG.getConstant(22, dl, MVT::i32));
4271 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4272 DAG.getConstant(3, dl, MVT::i32));
4275 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4276 const ARMSubtarget *ST) {
4278 EVT VT = N->getValueType(0);
4279 if (VT.isVector()) {
4280 assert(ST->hasNEON());
4282 // Compute the least significant set bit: LSB = X & -X
4283 SDValue X = N->getOperand(0);
4284 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4285 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4287 EVT ElemTy = VT.getVectorElementType();
4289 if (ElemTy == MVT::i8) {
4290 // Compute with: cttz(x) = ctpop(lsb - 1)
4291 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4292 DAG.getTargetConstant(1, dl, ElemTy));
4293 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4294 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4297 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4298 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4299 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4300 unsigned NumBits = ElemTy.getSizeInBits();
4301 SDValue WidthMinus1 =
4302 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4303 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4304 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4305 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4308 // Compute with: cttz(x) = ctpop(lsb - 1)
4310 // Since we can only compute the number of bits in a byte with vcnt.8, we
4311 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4316 if (ElemTy == MVT::i64) {
4317 // Load constant 0xffff'ffff'ffff'ffff to register.
4318 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4319 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4320 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4322 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4323 DAG.getTargetConstant(1, dl, ElemTy));
4324 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4327 // Count #bits with vcnt.8.
4328 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4329 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4330 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4332 // Gather the #bits with vpaddl (pairwise add.)
4333 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4334 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4335 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4337 if (ElemTy == MVT::i16)
4340 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4341 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4342 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4344 if (ElemTy == MVT::i32)
4347 assert(ElemTy == MVT::i64);
4348 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4349 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4354 if (!ST->hasV6T2Ops())
4357 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4358 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4361 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4362 /// for each 16-bit element from operand, repeated. The basic idea is to
4363 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4365 /// Trace for v4i16:
4366 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4367 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4368 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4369 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4370 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4371 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4372 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4373 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4374 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4375 EVT VT = N->getValueType(0);
4378 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4379 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4380 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4381 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4382 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4383 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4386 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4387 /// bit-count for each 16-bit element from the operand. We need slightly
4388 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4389 /// 64/128-bit registers.
4391 /// Trace for v4i16:
4392 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4393 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4394 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4395 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4396 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4397 EVT VT = N->getValueType(0);
4400 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4401 if (VT.is64BitVector()) {
4402 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4403 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4404 DAG.getIntPtrConstant(0, DL));
4406 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4407 BitCounts, DAG.getIntPtrConstant(0, DL));
4408 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4412 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4413 /// bit-count for each 32-bit element from the operand. The idea here is
4414 /// to split the vector into 16-bit elements, leverage the 16-bit count
4415 /// routine, and then combine the results.
4417 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4418 /// input = [v0 v1 ] (vi: 32-bit elements)
4419 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4420 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4421 /// vrev: N0 = [k1 k0 k3 k2 ]
4423 /// N1 =+[k1 k0 k3 k2 ]
4425 /// N2 =+[k1 k3 k0 k2 ]
4427 /// Extended =+[k1 k3 k0 k2 ]
4429 /// Extracted=+[k1 k3 ]
4431 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4432 EVT VT = N->getValueType(0);
4435 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4437 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4438 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4439 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4440 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4441 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4443 if (VT.is64BitVector()) {
4444 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4445 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4446 DAG.getIntPtrConstant(0, DL));
4448 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4449 DAG.getIntPtrConstant(0, DL));
4450 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4454 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4455 const ARMSubtarget *ST) {
4456 EVT VT = N->getValueType(0);
4458 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4459 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4460 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4461 "Unexpected type for custom ctpop lowering");
4463 if (VT.getVectorElementType() == MVT::i32)
4464 return lowerCTPOP32BitElements(N, DAG);
4466 return lowerCTPOP16BitElements(N, DAG);
4469 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4470 const ARMSubtarget *ST) {
4471 EVT VT = N->getValueType(0);
4477 // Lower vector shifts on NEON to use VSHL.
4478 assert(ST->hasNEON() && "unexpected vector shift");
4480 // Left shifts translate directly to the vshiftu intrinsic.
4481 if (N->getOpcode() == ISD::SHL)
4482 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4483 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4485 N->getOperand(0), N->getOperand(1));
4487 assert((N->getOpcode() == ISD::SRA ||
4488 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4490 // NEON uses the same intrinsics for both left and right shifts. For
4491 // right shifts, the shift amounts are negative, so negate the vector of
4493 EVT ShiftVT = N->getOperand(1).getValueType();
4494 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4495 getZeroVector(ShiftVT, DAG, dl),
4497 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4498 Intrinsic::arm_neon_vshifts :
4499 Intrinsic::arm_neon_vshiftu);
4500 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4501 DAG.getConstant(vshiftInt, dl, MVT::i32),
4502 N->getOperand(0), NegatedCount);
4505 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4506 const ARMSubtarget *ST) {
4507 EVT VT = N->getValueType(0);
4510 // We can get here for a node like i32 = ISD::SHL i32, i64
4514 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4515 "Unknown shift to lower!");
4517 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4518 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4519 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4522 // If we are in thumb mode, we don't have RRX.
4523 if (ST->isThumb1Only()) return SDValue();
4525 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4526 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4527 DAG.getConstant(0, dl, MVT::i32));
4528 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4529 DAG.getConstant(1, dl, MVT::i32));
4531 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4532 // captures the result into a carry flag.
4533 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4534 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4536 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4537 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4539 // Merge the pieces into a single i64 value.
4540 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4543 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4544 SDValue TmpOp0, TmpOp1;
4545 bool Invert = false;
4549 SDValue Op0 = Op.getOperand(0);
4550 SDValue Op1 = Op.getOperand(1);
4551 SDValue CC = Op.getOperand(2);
4552 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4553 EVT VT = Op.getValueType();
4554 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4557 if (CmpVT.getVectorElementType() == MVT::i64)
4558 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4559 // but it's possible that our operands are 64-bit but our result is 32-bit.
4560 // Bail in this case.
4563 if (Op1.getValueType().isFloatingPoint()) {
4564 switch (SetCCOpcode) {
4565 default: llvm_unreachable("Illegal FP comparison");
4567 case ISD::SETNE: Invert = true; // Fallthrough
4569 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4571 case ISD::SETLT: Swap = true; // Fallthrough
4573 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4575 case ISD::SETLE: Swap = true; // Fallthrough
4577 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4578 case ISD::SETUGE: Swap = true; // Fallthrough
4579 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4580 case ISD::SETUGT: Swap = true; // Fallthrough
4581 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4582 case ISD::SETUEQ: Invert = true; // Fallthrough
4584 // Expand this to (OLT | OGT).
4588 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4589 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4591 case ISD::SETUO: Invert = true; // Fallthrough
4593 // Expand this to (OLT | OGE).
4597 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4598 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4602 // Integer comparisons.
4603 switch (SetCCOpcode) {
4604 default: llvm_unreachable("Illegal integer comparison");
4605 case ISD::SETNE: Invert = true;
4606 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4607 case ISD::SETLT: Swap = true;
4608 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4609 case ISD::SETLE: Swap = true;
4610 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4611 case ISD::SETULT: Swap = true;
4612 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4613 case ISD::SETULE: Swap = true;
4614 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4617 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4618 if (Opc == ARMISD::VCEQ) {
4621 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4623 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4626 // Ignore bitconvert.
4627 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4628 AndOp = AndOp.getOperand(0);
4630 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4632 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4633 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4640 std::swap(Op0, Op1);
4642 // If one of the operands is a constant vector zero, attempt to fold the
4643 // comparison to a specialized compare-against-zero form.
4645 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4647 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4648 if (Opc == ARMISD::VCGE)
4649 Opc = ARMISD::VCLEZ;
4650 else if (Opc == ARMISD::VCGT)
4651 Opc = ARMISD::VCLTZ;
4656 if (SingleOp.getNode()) {
4659 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4661 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4663 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4665 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4667 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4669 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4672 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4675 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4678 Result = DAG.getNOT(dl, Result, VT);
4683 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4684 /// valid vector constant for a NEON instruction with a "modified immediate"
4685 /// operand (e.g., VMOV). If so, return the encoded value.
4686 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4687 unsigned SplatBitSize, SelectionDAG &DAG,
4688 SDLoc dl, EVT &VT, bool is128Bits,
4689 NEONModImmType type) {
4690 unsigned OpCmode, Imm;
4692 // SplatBitSize is set to the smallest size that splats the vector, so a
4693 // zero vector will always have SplatBitSize == 8. However, NEON modified
4694 // immediate instructions others than VMOV do not support the 8-bit encoding
4695 // of a zero vector, and the default encoding of zero is supposed to be the
4700 switch (SplatBitSize) {
4702 if (type != VMOVModImm)
4704 // Any 1-byte value is OK. Op=0, Cmode=1110.
4705 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4708 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4712 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4713 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4714 if ((SplatBits & ~0xff) == 0) {
4715 // Value = 0x00nn: Op=x, Cmode=100x.
4720 if ((SplatBits & ~0xff00) == 0) {
4721 // Value = 0xnn00: Op=x, Cmode=101x.
4723 Imm = SplatBits >> 8;
4729 // NEON's 32-bit VMOV supports splat values where:
4730 // * only one byte is nonzero, or
4731 // * the least significant byte is 0xff and the second byte is nonzero, or
4732 // * the least significant 2 bytes are 0xff and the third is nonzero.
4733 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4734 if ((SplatBits & ~0xff) == 0) {
4735 // Value = 0x000000nn: Op=x, Cmode=000x.
4740 if ((SplatBits & ~0xff00) == 0) {
4741 // Value = 0x0000nn00: Op=x, Cmode=001x.
4743 Imm = SplatBits >> 8;
4746 if ((SplatBits & ~0xff0000) == 0) {
4747 // Value = 0x00nn0000: Op=x, Cmode=010x.
4749 Imm = SplatBits >> 16;
4752 if ((SplatBits & ~0xff000000) == 0) {
4753 // Value = 0xnn000000: Op=x, Cmode=011x.
4755 Imm = SplatBits >> 24;
4759 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4760 if (type == OtherModImm) return SDValue();
4762 if ((SplatBits & ~0xffff) == 0 &&
4763 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4764 // Value = 0x0000nnff: Op=x, Cmode=1100.
4766 Imm = SplatBits >> 8;
4770 if ((SplatBits & ~0xffffff) == 0 &&
4771 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4772 // Value = 0x00nnffff: Op=x, Cmode=1101.
4774 Imm = SplatBits >> 16;
4778 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4779 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4780 // VMOV.I32. A (very) minor optimization would be to replicate the value
4781 // and fall through here to test for a valid 64-bit splat. But, then the
4782 // caller would also need to check and handle the change in size.
4786 if (type != VMOVModImm)
4788 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4789 uint64_t BitMask = 0xff;
4791 unsigned ImmMask = 1;
4793 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4794 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4797 } else if ((SplatBits & BitMask) != 0) {
4804 if (DAG.getDataLayout().isBigEndian())
4805 // swap higher and lower 32 bit word
4806 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4808 // Op=1, Cmode=1110.
4810 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4815 llvm_unreachable("unexpected size for isNEONModifiedImm");
4818 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4819 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4822 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4823 const ARMSubtarget *ST) const {
4827 bool IsDouble = Op.getValueType() == MVT::f64;
4828 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4830 // Use the default (constant pool) lowering for double constants when we have
4832 if (IsDouble && Subtarget->isFPOnlySP())
4835 // Try splatting with a VMOV.f32...
4836 APFloat FPVal = CFP->getValueAPF();
4837 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4840 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4841 // We have code in place to select a valid ConstantFP already, no need to
4846 // It's a float and we are trying to use NEON operations where
4847 // possible. Lower it to a splat followed by an extract.
4849 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4850 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4852 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4853 DAG.getConstant(0, DL, MVT::i32));
4856 // The rest of our options are NEON only, make sure that's allowed before
4858 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4862 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4864 // It wouldn't really be worth bothering for doubles except for one very
4865 // important value, which does happen to match: 0.0. So make sure we don't do
4867 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4870 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4871 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4872 VMovVT, false, VMOVModImm);
4873 if (NewVal != SDValue()) {
4875 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4878 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4880 // It's a float: cast and extract a vector element.
4881 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4883 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4884 DAG.getConstant(0, DL, MVT::i32));
4887 // Finally, try a VMVN.i32
4888 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4890 if (NewVal != SDValue()) {
4892 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4895 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4897 // It's a float: cast and extract a vector element.
4898 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4900 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4901 DAG.getConstant(0, DL, MVT::i32));
4907 // check if an VEXT instruction can handle the shuffle mask when the
4908 // vector sources of the shuffle are the same.
4909 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4910 unsigned NumElts = VT.getVectorNumElements();
4912 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4918 // If this is a VEXT shuffle, the immediate value is the index of the first
4919 // element. The other shuffle indices must be the successive elements after
4921 unsigned ExpectedElt = Imm;
4922 for (unsigned i = 1; i < NumElts; ++i) {
4923 // Increment the expected index. If it wraps around, just follow it
4924 // back to index zero and keep going.
4926 if (ExpectedElt == NumElts)
4929 if (M[i] < 0) continue; // ignore UNDEF indices
4930 if (ExpectedElt != static_cast<unsigned>(M[i]))
4938 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4939 bool &ReverseVEXT, unsigned &Imm) {
4940 unsigned NumElts = VT.getVectorNumElements();
4941 ReverseVEXT = false;
4943 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4949 // If this is a VEXT shuffle, the immediate value is the index of the first
4950 // element. The other shuffle indices must be the successive elements after
4952 unsigned ExpectedElt = Imm;
4953 for (unsigned i = 1; i < NumElts; ++i) {
4954 // Increment the expected index. If it wraps around, it may still be
4955 // a VEXT but the source vectors must be swapped.
4957 if (ExpectedElt == NumElts * 2) {
4962 if (M[i] < 0) continue; // ignore UNDEF indices
4963 if (ExpectedElt != static_cast<unsigned>(M[i]))
4967 // Adjust the index value if the source operands will be swapped.
4974 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4975 /// instruction with the specified blocksize. (The order of the elements
4976 /// within each block of the vector is reversed.)
4977 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4978 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4979 "Only possible block sizes for VREV are: 16, 32, 64");
4981 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4985 unsigned NumElts = VT.getVectorNumElements();
4986 unsigned BlockElts = M[0] + 1;
4987 // If the first shuffle index is UNDEF, be optimistic.
4989 BlockElts = BlockSize / EltSz;
4991 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4994 for (unsigned i = 0; i < NumElts; ++i) {
4995 if (M[i] < 0) continue; // ignore UNDEF indices
4996 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5003 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5004 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5005 // range, then 0 is placed into the resulting vector. So pretty much any mask
5006 // of 8 elements can work here.
5007 return VT == MVT::v8i8 && M.size() == 8;
5010 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5011 // checking that pairs of elements in the shuffle mask represent the same index
5012 // in each vector, incrementing the expected index by 2 at each step.
5013 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5014 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5016 // WhichResult gives the offset for each element in the mask based on which
5017 // of the two results it belongs to.
5019 // The transpose can be represented either as:
5020 // result1 = shufflevector v1, v2, result1_shuffle_mask
5021 // result2 = shufflevector v1, v2, result2_shuffle_mask
5022 // where v1/v2 and the shuffle masks have the same number of elements
5023 // (here WhichResult (see below) indicates which result is being checked)
5026 // results = shufflevector v1, v2, shuffle_mask
5027 // where both results are returned in one vector and the shuffle mask has twice
5028 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5029 // want to check the low half and high half of the shuffle mask as if it were
5031 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5032 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5036 unsigned NumElts = VT.getVectorNumElements();
5037 if (M.size() != NumElts && M.size() != NumElts*2)
5040 // If the mask is twice as long as the input vector then we need to check the
5041 // upper and lower parts of the mask with a matching value for WhichResult
5042 // FIXME: A mask with only even values will be rejected in case the first
5043 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5044 // M[0] is used to determine WhichResult
5045 for (unsigned i = 0; i < M.size(); i += NumElts) {
5046 if (M.size() == NumElts * 2)
5047 WhichResult = i / NumElts;
5049 WhichResult = M[i] == 0 ? 0 : 1;
5050 for (unsigned j = 0; j < NumElts; j += 2) {
5051 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5052 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5057 if (M.size() == NumElts*2)
5063 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5064 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5065 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5066 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5067 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5071 unsigned NumElts = VT.getVectorNumElements();
5072 if (M.size() != NumElts && M.size() != NumElts*2)
5075 for (unsigned i = 0; i < M.size(); i += NumElts) {
5076 if (M.size() == NumElts * 2)
5077 WhichResult = i / NumElts;
5079 WhichResult = M[i] == 0 ? 0 : 1;
5080 for (unsigned j = 0; j < NumElts; j += 2) {
5081 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5082 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5087 if (M.size() == NumElts*2)
5093 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5094 // that the mask elements are either all even and in steps of size 2 or all odd
5095 // and in steps of size 2.
5096 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5097 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5099 // Requires similar checks to that of isVTRNMask with
5100 // respect the how results are returned.
5101 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5102 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5106 unsigned NumElts = VT.getVectorNumElements();
5107 if (M.size() != NumElts && M.size() != NumElts*2)
5110 for (unsigned i = 0; i < M.size(); i += NumElts) {
5111 WhichResult = M[i] == 0 ? 0 : 1;
5112 for (unsigned j = 0; j < NumElts; ++j) {
5113 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5118 if (M.size() == NumElts*2)
5121 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5122 if (VT.is64BitVector() && EltSz == 32)
5128 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5129 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5130 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5131 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5132 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5136 unsigned NumElts = VT.getVectorNumElements();
5137 if (M.size() != NumElts && M.size() != NumElts*2)
5140 unsigned Half = NumElts / 2;
5141 for (unsigned i = 0; i < M.size(); i += NumElts) {
5142 WhichResult = M[i] == 0 ? 0 : 1;
5143 for (unsigned j = 0; j < NumElts; j += Half) {
5144 unsigned Idx = WhichResult;
5145 for (unsigned k = 0; k < Half; ++k) {
5146 int MIdx = M[i + j + k];
5147 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5154 if (M.size() == NumElts*2)
5157 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5158 if (VT.is64BitVector() && EltSz == 32)
5164 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5165 // that pairs of elements of the shufflemask represent the same index in each
5166 // vector incrementing sequentially through the vectors.
5167 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5168 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5170 // Requires similar checks to that of isVTRNMask with respect the how results
5172 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5173 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5177 unsigned NumElts = VT.getVectorNumElements();
5178 if (M.size() != NumElts && M.size() != NumElts*2)
5181 for (unsigned i = 0; i < M.size(); i += NumElts) {
5182 WhichResult = M[i] == 0 ? 0 : 1;
5183 unsigned Idx = WhichResult * NumElts / 2;
5184 for (unsigned j = 0; j < NumElts; j += 2) {
5185 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5186 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5192 if (M.size() == NumElts*2)
5195 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5196 if (VT.is64BitVector() && EltSz == 32)
5202 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5203 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5204 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5205 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5206 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5210 unsigned NumElts = VT.getVectorNumElements();
5211 if (M.size() != NumElts && M.size() != NumElts*2)
5214 for (unsigned i = 0; i < M.size(); i += NumElts) {
5215 WhichResult = M[i] == 0 ? 0 : 1;
5216 unsigned Idx = WhichResult * NumElts / 2;
5217 for (unsigned j = 0; j < NumElts; j += 2) {
5218 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5219 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5225 if (M.size() == NumElts*2)
5228 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5229 if (VT.is64BitVector() && EltSz == 32)
5235 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5236 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5237 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5238 unsigned &WhichResult,
5241 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5242 return ARMISD::VTRN;
5243 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5244 return ARMISD::VUZP;
5245 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5246 return ARMISD::VZIP;
5249 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5250 return ARMISD::VTRN;
5251 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5252 return ARMISD::VUZP;
5253 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5254 return ARMISD::VZIP;
5259 /// \return true if this is a reverse operation on an vector.
5260 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5261 unsigned NumElts = VT.getVectorNumElements();
5262 // Make sure the mask has the right size.
5263 if (NumElts != M.size())
5266 // Look for <15, ..., 3, -1, 1, 0>.
5267 for (unsigned i = 0; i != NumElts; ++i)
5268 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5274 // If N is an integer constant that can be moved into a register in one
5275 // instruction, return an SDValue of such a constant (will become a MOV
5276 // instruction). Otherwise return null.
5277 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5278 const ARMSubtarget *ST, SDLoc dl) {
5280 if (!isa<ConstantSDNode>(N))
5282 Val = cast<ConstantSDNode>(N)->getZExtValue();
5284 if (ST->isThumb1Only()) {
5285 if (Val <= 255 || ~Val <= 255)
5286 return DAG.getConstant(Val, dl, MVT::i32);
5288 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5289 return DAG.getConstant(Val, dl, MVT::i32);
5294 // If this is a case we can't handle, return null and let the default
5295 // expansion code take care of it.
5296 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5297 const ARMSubtarget *ST) const {
5298 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5300 EVT VT = Op.getValueType();
5302 APInt SplatBits, SplatUndef;
5303 unsigned SplatBitSize;
5305 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5306 if (SplatBitSize <= 64) {
5307 // Check if an immediate VMOV works.
5309 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5310 SplatUndef.getZExtValue(), SplatBitSize,
5311 DAG, dl, VmovVT, VT.is128BitVector(),
5313 if (Val.getNode()) {
5314 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5315 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5318 // Try an immediate VMVN.
5319 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5320 Val = isNEONModifiedImm(NegatedImm,
5321 SplatUndef.getZExtValue(), SplatBitSize,
5322 DAG, dl, VmovVT, VT.is128BitVector(),
5324 if (Val.getNode()) {
5325 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5326 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5329 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5330 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5331 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5333 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5334 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5340 // Scan through the operands to see if only one value is used.
5342 // As an optimisation, even if more than one value is used it may be more
5343 // profitable to splat with one value then change some lanes.
5345 // Heuristically we decide to do this if the vector has a "dominant" value,
5346 // defined as splatted to more than half of the lanes.
5347 unsigned NumElts = VT.getVectorNumElements();
5348 bool isOnlyLowElement = true;
5349 bool usesOnlyOneValue = true;
5350 bool hasDominantValue = false;
5351 bool isConstant = true;
5353 // Map of the number of times a particular SDValue appears in the
5355 DenseMap<SDValue, unsigned> ValueCounts;
5357 for (unsigned i = 0; i < NumElts; ++i) {
5358 SDValue V = Op.getOperand(i);
5359 if (V.getOpcode() == ISD::UNDEF)
5362 isOnlyLowElement = false;
5363 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5366 ValueCounts.insert(std::make_pair(V, 0));
5367 unsigned &Count = ValueCounts[V];
5369 // Is this value dominant? (takes up more than half of the lanes)
5370 if (++Count > (NumElts / 2)) {
5371 hasDominantValue = true;
5375 if (ValueCounts.size() != 1)
5376 usesOnlyOneValue = false;
5377 if (!Value.getNode() && ValueCounts.size() > 0)
5378 Value = ValueCounts.begin()->first;
5380 if (ValueCounts.size() == 0)
5381 return DAG.getUNDEF(VT);
5383 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5384 // Keep going if we are hitting this case.
5385 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5386 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5388 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5390 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5391 // i32 and try again.
5392 if (hasDominantValue && EltSize <= 32) {
5396 // If we are VDUPing a value that comes directly from a vector, that will
5397 // cause an unnecessary move to and from a GPR, where instead we could
5398 // just use VDUPLANE. We can only do this if the lane being extracted
5399 // is at a constant index, as the VDUP from lane instructions only have
5400 // constant-index forms.
5401 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5402 isa<ConstantSDNode>(Value->getOperand(1))) {
5403 // We need to create a new undef vector to use for the VDUPLANE if the
5404 // size of the vector from which we get the value is different than the
5405 // size of the vector that we need to create. We will insert the element
5406 // such that the register coalescer will remove unnecessary copies.
5407 if (VT != Value->getOperand(0).getValueType()) {
5408 ConstantSDNode *constIndex;
5409 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5410 assert(constIndex && "The index is not a constant!");
5411 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5412 VT.getVectorNumElements();
5413 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5414 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5415 Value, DAG.getConstant(index, dl, MVT::i32)),
5416 DAG.getConstant(index, dl, MVT::i32));
5418 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5419 Value->getOperand(0), Value->getOperand(1));
5421 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5423 if (!usesOnlyOneValue) {
5424 // The dominant value was splatted as 'N', but we now have to insert
5425 // all differing elements.
5426 for (unsigned I = 0; I < NumElts; ++I) {
5427 if (Op.getOperand(I) == Value)
5429 SmallVector<SDValue, 3> Ops;
5431 Ops.push_back(Op.getOperand(I));
5432 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5433 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5438 if (VT.getVectorElementType().isFloatingPoint()) {
5439 SmallVector<SDValue, 8> Ops;
5440 for (unsigned i = 0; i < NumElts; ++i)
5441 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5443 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5444 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5445 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5447 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5449 if (usesOnlyOneValue) {
5450 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5451 if (isConstant && Val.getNode())
5452 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5456 // If all elements are constants and the case above didn't get hit, fall back
5457 // to the default expansion, which will generate a load from the constant
5462 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5464 SDValue shuffle = ReconstructShuffle(Op, DAG);
5465 if (shuffle != SDValue())
5469 // Vectors with 32- or 64-bit elements can be built by directly assigning
5470 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5471 // will be legalized.
5472 if (EltSize >= 32) {
5473 // Do the expansion with floating-point types, since that is what the VFP
5474 // registers are defined to use, and since i64 is not legal.
5475 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5476 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5477 SmallVector<SDValue, 8> Ops;
5478 for (unsigned i = 0; i < NumElts; ++i)
5479 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5480 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5481 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5484 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5485 // know the default expansion would otherwise fall back on something even
5486 // worse. For a vector with one or two non-undef values, that's
5487 // scalar_to_vector for the elements followed by a shuffle (provided the
5488 // shuffle is valid for the target) and materialization element by element
5489 // on the stack followed by a load for everything else.
5490 if (!isConstant && !usesOnlyOneValue) {
5491 SDValue Vec = DAG.getUNDEF(VT);
5492 for (unsigned i = 0 ; i < NumElts; ++i) {
5493 SDValue V = Op.getOperand(i);
5494 if (V.getOpcode() == ISD::UNDEF)
5496 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5497 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5505 // Gather data to see if the operation can be modelled as a
5506 // shuffle in combination with VEXTs.
5507 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5508 SelectionDAG &DAG) const {
5509 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5511 EVT VT = Op.getValueType();
5512 unsigned NumElts = VT.getVectorNumElements();
5514 struct ShuffleSourceInfo {
5519 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5520 // be compatible with the shuffle we intend to construct. As a result
5521 // ShuffleVec will be some sliding window into the original Vec.
5524 // Code should guarantee that element i in Vec starts at element "WindowBase
5525 // + i * WindowScale in ShuffleVec".
5529 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5530 ShuffleSourceInfo(SDValue Vec)
5531 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5535 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5537 SmallVector<ShuffleSourceInfo, 2> Sources;
5538 for (unsigned i = 0; i < NumElts; ++i) {
5539 SDValue V = Op.getOperand(i);
5540 if (V.getOpcode() == ISD::UNDEF)
5542 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5543 // A shuffle can only come from building a vector from various
5544 // elements of other vectors.
5546 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5547 // Furthermore, shuffles require a constant mask, whereas extractelts
5548 // accept variable indices.
5552 // Add this element source to the list if it's not already there.
5553 SDValue SourceVec = V.getOperand(0);
5554 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5555 if (Source == Sources.end())
5556 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5558 // Update the minimum and maximum lane number seen.
5559 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5560 Source->MinElt = std::min(Source->MinElt, EltNo);
5561 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5564 // Currently only do something sane when at most two source vectors
5566 if (Sources.size() > 2)
5569 // Find out the smallest element size among result and two sources, and use
5570 // it as element size to build the shuffle_vector.
5571 EVT SmallestEltTy = VT.getVectorElementType();
5572 for (auto &Source : Sources) {
5573 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5574 if (SrcEltTy.bitsLT(SmallestEltTy))
5575 SmallestEltTy = SrcEltTy;
5577 unsigned ResMultiplier =
5578 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5579 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5580 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5582 // If the source vector is too wide or too narrow, we may nevertheless be able
5583 // to construct a compatible shuffle either by concatenating it with UNDEF or
5584 // extracting a suitable range of elements.
5585 for (auto &Src : Sources) {
5586 EVT SrcVT = Src.ShuffleVec.getValueType();
5588 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5591 // This stage of the search produces a source with the same element type as
5592 // the original, but with a total width matching the BUILD_VECTOR output.
5593 EVT EltVT = SrcVT.getVectorElementType();
5594 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5595 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5597 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5598 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5600 // We can pad out the smaller vector for free, so if it's part of a
5603 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5604 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5608 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5611 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5612 // Span too large for a VEXT to cope
5616 if (Src.MinElt >= NumSrcElts) {
5617 // The extraction can just take the second half
5619 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5620 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5621 Src.WindowBase = -NumSrcElts;
5622 } else if (Src.MaxElt < NumSrcElts) {
5623 // The extraction can just take the first half
5625 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5626 DAG.getConstant(0, dl, MVT::i32));
5628 // An actual VEXT is needed
5630 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5631 DAG.getConstant(0, dl, MVT::i32));
5633 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5634 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5636 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5638 DAG.getConstant(Src.MinElt, dl, MVT::i32));
5639 Src.WindowBase = -Src.MinElt;
5643 // Another possible incompatibility occurs from the vector element types. We
5644 // can fix this by bitcasting the source vectors to the same type we intend
5646 for (auto &Src : Sources) {
5647 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5648 if (SrcEltTy == SmallestEltTy)
5650 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5651 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5652 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5653 Src.WindowBase *= Src.WindowScale;
5656 // Final sanity check before we try to actually produce a shuffle.
5658 for (auto Src : Sources)
5659 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5662 // The stars all align, our next step is to produce the mask for the shuffle.
5663 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5664 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5665 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5666 SDValue Entry = Op.getOperand(i);
5667 if (Entry.getOpcode() == ISD::UNDEF)
5670 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5671 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5673 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5674 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5676 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5677 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5678 VT.getVectorElementType().getSizeInBits());
5679 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5681 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5682 // starting at the appropriate offset.
5683 int *LaneMask = &Mask[i * ResMultiplier];
5685 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5686 ExtractBase += NumElts * (Src - Sources.begin());
5687 for (int j = 0; j < LanesDefined; ++j)
5688 LaneMask[j] = ExtractBase + j;
5691 // Final check before we try to produce nonsense...
5692 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5695 // We can't handle more than two sources. This should have already
5696 // been checked before this point.
5697 assert(Sources.size() <= 2 && "Too many sources!");
5699 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5700 for (unsigned i = 0; i < Sources.size(); ++i)
5701 ShuffleOps[i] = Sources[i].ShuffleVec;
5703 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5704 ShuffleOps[1], &Mask[0]);
5705 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5708 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5709 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5710 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5711 /// are assumed to be legal.
5713 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5715 if (VT.getVectorNumElements() == 4 &&
5716 (VT.is128BitVector() || VT.is64BitVector())) {
5717 unsigned PFIndexes[4];
5718 for (unsigned i = 0; i != 4; ++i) {
5722 PFIndexes[i] = M[i];
5725 // Compute the index in the perfect shuffle table.
5726 unsigned PFTableIndex =
5727 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5728 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5729 unsigned Cost = (PFEntry >> 30);
5735 bool ReverseVEXT, isV_UNDEF;
5736 unsigned Imm, WhichResult;
5738 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5739 return (EltSize >= 32 ||
5740 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5741 isVREVMask(M, VT, 64) ||
5742 isVREVMask(M, VT, 32) ||
5743 isVREVMask(M, VT, 16) ||
5744 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5745 isVTBLMask(M, VT) ||
5746 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5747 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5750 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5751 /// the specified operations to build the shuffle.
5752 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5753 SDValue RHS, SelectionDAG &DAG,
5755 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5756 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5757 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5760 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5769 OP_VUZPL, // VUZP, left result
5770 OP_VUZPR, // VUZP, right result
5771 OP_VZIPL, // VZIP, left result
5772 OP_VZIPR, // VZIP, right result
5773 OP_VTRNL, // VTRN, left result
5774 OP_VTRNR // VTRN, right result
5777 if (OpNum == OP_COPY) {
5778 if (LHSID == (1*9+2)*9+3) return LHS;
5779 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5783 SDValue OpLHS, OpRHS;
5784 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5785 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5786 EVT VT = OpLHS.getValueType();
5789 default: llvm_unreachable("Unknown shuffle opcode!");
5791 // VREV divides the vector in half and swaps within the half.
5792 if (VT.getVectorElementType() == MVT::i32 ||
5793 VT.getVectorElementType() == MVT::f32)
5794 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5795 // vrev <4 x i16> -> VREV32
5796 if (VT.getVectorElementType() == MVT::i16)
5797 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5798 // vrev <4 x i8> -> VREV16
5799 assert(VT.getVectorElementType() == MVT::i8);
5800 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5805 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5806 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5810 return DAG.getNode(ARMISD::VEXT, dl, VT,
5812 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5815 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5816 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5819 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5820 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5823 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5824 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5828 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5829 ArrayRef<int> ShuffleMask,
5830 SelectionDAG &DAG) {
5831 // Check to see if we can use the VTBL instruction.
5832 SDValue V1 = Op.getOperand(0);
5833 SDValue V2 = Op.getOperand(1);
5836 SmallVector<SDValue, 8> VTBLMask;
5837 for (ArrayRef<int>::iterator
5838 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5839 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5841 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5842 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5843 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5845 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5846 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5849 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5850 SelectionDAG &DAG) {
5852 SDValue OpLHS = Op.getOperand(0);
5853 EVT VT = OpLHS.getValueType();
5855 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5856 "Expect an v8i16/v16i8 type");
5857 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5858 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5859 // extract the first 8 bytes into the top double word and the last 8 bytes
5860 // into the bottom double word. The v8i16 case is similar.
5861 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5862 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5863 DAG.getConstant(ExtractNum, DL, MVT::i32));
5866 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5867 SDValue V1 = Op.getOperand(0);
5868 SDValue V2 = Op.getOperand(1);
5870 EVT VT = Op.getValueType();
5871 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5873 // Convert shuffles that are directly supported on NEON to target-specific
5874 // DAG nodes, instead of keeping them as shuffles and matching them again
5875 // during code selection. This is more efficient and avoids the possibility
5876 // of inconsistencies between legalization and selection.
5877 // FIXME: floating-point vectors should be canonicalized to integer vectors
5878 // of the same time so that they get CSEd properly.
5879 ArrayRef<int> ShuffleMask = SVN->getMask();
5881 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5882 if (EltSize <= 32) {
5883 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5884 int Lane = SVN->getSplatIndex();
5885 // If this is undef splat, generate it via "just" vdup, if possible.
5886 if (Lane == -1) Lane = 0;
5888 // Test if V1 is a SCALAR_TO_VECTOR.
5889 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5890 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5892 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5893 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5895 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5896 !isa<ConstantSDNode>(V1.getOperand(0))) {
5897 bool IsScalarToVector = true;
5898 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5899 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5900 IsScalarToVector = false;
5903 if (IsScalarToVector)
5904 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5906 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5907 DAG.getConstant(Lane, dl, MVT::i32));
5912 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5915 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5916 DAG.getConstant(Imm, dl, MVT::i32));
5919 if (isVREVMask(ShuffleMask, VT, 64))
5920 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5921 if (isVREVMask(ShuffleMask, VT, 32))
5922 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5923 if (isVREVMask(ShuffleMask, VT, 16))
5924 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5926 if (V2->getOpcode() == ISD::UNDEF &&
5927 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5928 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5929 DAG.getConstant(Imm, dl, MVT::i32));
5932 // Check for Neon shuffles that modify both input vectors in place.
5933 // If both results are used, i.e., if there are two shuffles with the same
5934 // source operands and with masks corresponding to both results of one of
5935 // these operations, DAG memoization will ensure that a single node is
5936 // used for both shuffles.
5937 unsigned WhichResult;
5939 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5940 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5943 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5944 .getValue(WhichResult);
5947 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5948 // shuffles that produce a result larger than their operands with:
5949 // shuffle(concat(v1, undef), concat(v2, undef))
5951 // shuffle(concat(v1, v2), undef)
5952 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5954 // This is useful in the general case, but there are special cases where
5955 // native shuffles produce larger results: the two-result ops.
5957 // Look through the concat when lowering them:
5958 // shuffle(concat(v1, v2), undef)
5960 // concat(VZIP(v1, v2):0, :1)
5962 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5963 V2->getOpcode() == ISD::UNDEF) {
5964 SDValue SubV1 = V1->getOperand(0);
5965 SDValue SubV2 = V1->getOperand(1);
5966 EVT SubVT = SubV1.getValueType();
5968 // We expect these to have been canonicalized to -1.
5969 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5970 return i < (int)VT.getVectorNumElements();
5971 }) && "Unexpected shuffle index into UNDEF operand!");
5973 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5974 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5977 assert((WhichResult == 0) &&
5978 "In-place shuffle of concat can only have one result!");
5979 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5981 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5987 // If the shuffle is not directly supported and it has 4 elements, use
5988 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5989 unsigned NumElts = VT.getVectorNumElements();
5991 unsigned PFIndexes[4];
5992 for (unsigned i = 0; i != 4; ++i) {
5993 if (ShuffleMask[i] < 0)
5996 PFIndexes[i] = ShuffleMask[i];
5999 // Compute the index in the perfect shuffle table.
6000 unsigned PFTableIndex =
6001 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6002 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6003 unsigned Cost = (PFEntry >> 30);
6006 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6009 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6010 if (EltSize >= 32) {
6011 // Do the expansion with floating-point types, since that is what the VFP
6012 // registers are defined to use, and since i64 is not legal.
6013 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6014 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6015 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6016 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6017 SmallVector<SDValue, 8> Ops;
6018 for (unsigned i = 0; i < NumElts; ++i) {
6019 if (ShuffleMask[i] < 0)
6020 Ops.push_back(DAG.getUNDEF(EltVT));
6022 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6023 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6024 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6027 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6028 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6031 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6032 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6034 if (VT == MVT::v8i8) {
6035 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6036 if (NewOp.getNode())
6043 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6044 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6045 SDValue Lane = Op.getOperand(2);
6046 if (!isa<ConstantSDNode>(Lane))
6052 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6053 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6054 SDValue Lane = Op.getOperand(1);
6055 if (!isa<ConstantSDNode>(Lane))
6058 SDValue Vec = Op.getOperand(0);
6059 if (Op.getValueType() == MVT::i32 &&
6060 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6062 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6068 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6069 // The only time a CONCAT_VECTORS operation can have legal types is when
6070 // two 64-bit vectors are concatenated to a 128-bit vector.
6071 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6072 "unexpected CONCAT_VECTORS");
6074 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6075 SDValue Op0 = Op.getOperand(0);
6076 SDValue Op1 = Op.getOperand(1);
6077 if (Op0.getOpcode() != ISD::UNDEF)
6078 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6079 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6080 DAG.getIntPtrConstant(0, dl));
6081 if (Op1.getOpcode() != ISD::UNDEF)
6082 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6083 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6084 DAG.getIntPtrConstant(1, dl));
6085 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6088 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6089 /// element has been zero/sign-extended, depending on the isSigned parameter,
6090 /// from an integer type half its size.
6091 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6093 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6094 EVT VT = N->getValueType(0);
6095 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6096 SDNode *BVN = N->getOperand(0).getNode();
6097 if (BVN->getValueType(0) != MVT::v4i32 ||
6098 BVN->getOpcode() != ISD::BUILD_VECTOR)
6100 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6101 unsigned HiElt = 1 - LoElt;
6102 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6103 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6104 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6105 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6106 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6109 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6110 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6113 if (Hi0->isNullValue() && Hi1->isNullValue())
6119 if (N->getOpcode() != ISD::BUILD_VECTOR)
6122 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6123 SDNode *Elt = N->getOperand(i).getNode();
6124 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6125 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6126 unsigned HalfSize = EltSize / 2;
6128 if (!isIntN(HalfSize, C->getSExtValue()))
6131 if (!isUIntN(HalfSize, C->getZExtValue()))
6142 /// isSignExtended - Check if a node is a vector value that is sign-extended
6143 /// or a constant BUILD_VECTOR with sign-extended elements.
6144 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6145 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6147 if (isExtendedBUILD_VECTOR(N, DAG, true))
6152 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6153 /// or a constant BUILD_VECTOR with zero-extended elements.
6154 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6155 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6157 if (isExtendedBUILD_VECTOR(N, DAG, false))
6162 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6163 if (OrigVT.getSizeInBits() >= 64)
6166 assert(OrigVT.isSimple() && "Expecting a simple value type");
6168 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6169 switch (OrigSimpleTy) {
6170 default: llvm_unreachable("Unexpected Vector Type");
6179 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6180 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6181 /// We insert the required extension here to get the vector to fill a D register.
6182 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6185 unsigned ExtOpcode) {
6186 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6187 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6188 // 64-bits we need to insert a new extension so that it will be 64-bits.
6189 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6190 if (OrigTy.getSizeInBits() >= 64)
6193 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6194 EVT NewVT = getExtensionTo64Bits(OrigTy);
6196 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6199 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6200 /// does not do any sign/zero extension. If the original vector is less
6201 /// than 64 bits, an appropriate extension will be added after the load to
6202 /// reach a total size of 64 bits. We have to add the extension separately
6203 /// because ARM does not have a sign/zero extending load for vectors.
6204 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6205 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6207 // The load already has the right type.
6208 if (ExtendedTy == LD->getMemoryVT())
6209 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6210 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6211 LD->isNonTemporal(), LD->isInvariant(),
6212 LD->getAlignment());
6214 // We need to create a zextload/sextload. We cannot just create a load
6215 // followed by a zext/zext node because LowerMUL is also run during normal
6216 // operation legalization where we can't create illegal types.
6217 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6218 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6219 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6220 LD->isNonTemporal(), LD->getAlignment());
6223 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6224 /// extending load, or BUILD_VECTOR with extended elements, return the
6225 /// unextended value. The unextended vector should be 64 bits so that it can
6226 /// be used as an operand to a VMULL instruction. If the original vector size
6227 /// before extension is less than 64 bits we add a an extension to resize
6228 /// the vector to 64 bits.
6229 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6230 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6231 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6232 N->getOperand(0)->getValueType(0),
6236 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6237 return SkipLoadExtensionForVMULL(LD, DAG);
6239 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6240 // have been legalized as a BITCAST from v4i32.
6241 if (N->getOpcode() == ISD::BITCAST) {
6242 SDNode *BVN = N->getOperand(0).getNode();
6243 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6244 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6245 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6246 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6247 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6249 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6250 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6251 EVT VT = N->getValueType(0);
6252 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6253 unsigned NumElts = VT.getVectorNumElements();
6254 MVT TruncVT = MVT::getIntegerVT(EltSize);
6255 SmallVector<SDValue, 8> Ops;
6257 for (unsigned i = 0; i != NumElts; ++i) {
6258 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6259 const APInt &CInt = C->getAPIntValue();
6260 // Element types smaller than 32 bits are not legal, so use i32 elements.
6261 // The values are implicitly truncated so sext vs. zext doesn't matter.
6262 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6264 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6265 MVT::getVectorVT(TruncVT, NumElts), Ops);
6268 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6269 unsigned Opcode = N->getOpcode();
6270 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6271 SDNode *N0 = N->getOperand(0).getNode();
6272 SDNode *N1 = N->getOperand(1).getNode();
6273 return N0->hasOneUse() && N1->hasOneUse() &&
6274 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6279 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6280 unsigned Opcode = N->getOpcode();
6281 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6282 SDNode *N0 = N->getOperand(0).getNode();
6283 SDNode *N1 = N->getOperand(1).getNode();
6284 return N0->hasOneUse() && N1->hasOneUse() &&
6285 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6290 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6291 // Multiplications are only custom-lowered for 128-bit vectors so that
6292 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6293 EVT VT = Op.getValueType();
6294 assert(VT.is128BitVector() && VT.isInteger() &&
6295 "unexpected type for custom-lowering ISD::MUL");
6296 SDNode *N0 = Op.getOperand(0).getNode();
6297 SDNode *N1 = Op.getOperand(1).getNode();
6298 unsigned NewOpc = 0;
6300 bool isN0SExt = isSignExtended(N0, DAG);
6301 bool isN1SExt = isSignExtended(N1, DAG);
6302 if (isN0SExt && isN1SExt)
6303 NewOpc = ARMISD::VMULLs;
6305 bool isN0ZExt = isZeroExtended(N0, DAG);
6306 bool isN1ZExt = isZeroExtended(N1, DAG);
6307 if (isN0ZExt && isN1ZExt)
6308 NewOpc = ARMISD::VMULLu;
6309 else if (isN1SExt || isN1ZExt) {
6310 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6311 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6312 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6313 NewOpc = ARMISD::VMULLs;
6315 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6316 NewOpc = ARMISD::VMULLu;
6318 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6320 NewOpc = ARMISD::VMULLu;
6326 if (VT == MVT::v2i64)
6327 // Fall through to expand this. It is not legal.
6330 // Other vector multiplications are legal.
6335 // Legalize to a VMULL instruction.
6338 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6340 Op0 = SkipExtensionForVMULL(N0, DAG);
6341 assert(Op0.getValueType().is64BitVector() &&
6342 Op1.getValueType().is64BitVector() &&
6343 "unexpected types for extended operands to VMULL");
6344 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6347 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6348 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6355 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6356 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6357 EVT Op1VT = Op1.getValueType();
6358 return DAG.getNode(N0->getOpcode(), DL, VT,
6359 DAG.getNode(NewOpc, DL, VT,
6360 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6361 DAG.getNode(NewOpc, DL, VT,
6362 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6366 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6367 // TODO: Should this propagate fast-math-flags?
6370 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6371 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6372 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6373 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6374 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6375 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6376 // Get reciprocal estimate.
6377 // float4 recip = vrecpeq_f32(yf);
6378 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6379 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6381 // Because char has a smaller range than uchar, we can actually get away
6382 // without any newton steps. This requires that we use a weird bias
6383 // of 0xb000, however (again, this has been exhaustively tested).
6384 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6385 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6386 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6387 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6388 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6389 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6390 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6391 // Convert back to short.
6392 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6393 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6398 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6399 // TODO: Should this propagate fast-math-flags?
6402 // Convert to float.
6403 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6404 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6405 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6406 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6407 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6408 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6410 // Use reciprocal estimate and one refinement step.
6411 // float4 recip = vrecpeq_f32(yf);
6412 // recip *= vrecpsq_f32(yf, recip);
6413 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6414 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6416 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6417 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6419 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6420 // Because short has a smaller range than ushort, we can actually get away
6421 // with only a single newton step. This requires that we use a weird bias
6422 // of 89, however (again, this has been exhaustively tested).
6423 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6424 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6425 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6426 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6427 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6428 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6429 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6430 // Convert back to integer and return.
6431 // return vmovn_s32(vcvt_s32_f32(result));
6432 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6433 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6437 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6438 EVT VT = Op.getValueType();
6439 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6440 "unexpected type for custom-lowering ISD::SDIV");
6443 SDValue N0 = Op.getOperand(0);
6444 SDValue N1 = Op.getOperand(1);
6447 if (VT == MVT::v8i8) {
6448 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6449 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6451 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6452 DAG.getIntPtrConstant(4, dl));
6453 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6454 DAG.getIntPtrConstant(4, dl));
6455 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6456 DAG.getIntPtrConstant(0, dl));
6457 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6458 DAG.getIntPtrConstant(0, dl));
6460 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6461 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6463 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6464 N0 = LowerCONCAT_VECTORS(N0, DAG);
6466 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6469 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6472 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6473 // TODO: Should this propagate fast-math-flags?
6474 EVT VT = Op.getValueType();
6475 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6476 "unexpected type for custom-lowering ISD::UDIV");
6479 SDValue N0 = Op.getOperand(0);
6480 SDValue N1 = Op.getOperand(1);
6483 if (VT == MVT::v8i8) {
6484 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6485 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6487 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6488 DAG.getIntPtrConstant(4, dl));
6489 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6490 DAG.getIntPtrConstant(4, dl));
6491 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6492 DAG.getIntPtrConstant(0, dl));
6493 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6494 DAG.getIntPtrConstant(0, dl));
6496 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6497 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6499 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6500 N0 = LowerCONCAT_VECTORS(N0, DAG);
6502 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6503 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6509 // v4i16 sdiv ... Convert to float.
6510 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6511 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6512 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6513 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6514 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6515 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6517 // Use reciprocal estimate and two refinement steps.
6518 // float4 recip = vrecpeq_f32(yf);
6519 // recip *= vrecpsq_f32(yf, recip);
6520 // recip *= vrecpsq_f32(yf, recip);
6521 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6522 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6524 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6525 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6527 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6528 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6529 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6531 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6532 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6533 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6534 // and that it will never cause us to return an answer too large).
6535 // float4 result = as_float4(as_int4(xf*recip) + 2);
6536 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6537 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6538 N1 = DAG.getConstant(2, dl, MVT::i32);
6539 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6540 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6541 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6542 // Convert back to integer and return.
6543 // return vmovn_u32(vcvt_s32_f32(result));
6544 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6545 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6549 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6550 EVT VT = Op.getNode()->getValueType(0);
6551 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6554 bool ExtraOp = false;
6555 switch (Op.getOpcode()) {
6556 default: llvm_unreachable("Invalid code");
6557 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6558 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6559 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6560 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6564 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6566 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6567 Op.getOperand(1), Op.getOperand(2));
6570 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6571 assert(Subtarget->isTargetDarwin());
6573 // For iOS, we want to call an alternative entry point: __sincos_stret,
6574 // return values are passed via sret.
6576 SDValue Arg = Op.getOperand(0);
6577 EVT ArgVT = Arg.getValueType();
6578 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6579 auto PtrVT = getPointerTy(DAG.getDataLayout());
6581 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6583 // Pair of floats / doubles used to pass the result.
6584 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6586 // Create stack object for sret.
6587 auto &DL = DAG.getDataLayout();
6588 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6589 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6590 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6591 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6597 Entry.Ty = RetTy->getPointerTo();
6598 Entry.isSExt = false;
6599 Entry.isZExt = false;
6600 Entry.isSRet = true;
6601 Args.push_back(Entry);
6605 Entry.isSExt = false;
6606 Entry.isZExt = false;
6607 Args.push_back(Entry);
6609 const char *LibcallName =
6610 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6611 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6613 TargetLowering::CallLoweringInfo CLI(DAG);
6614 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6615 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6617 .setDiscardResult();
6619 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6621 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6622 MachinePointerInfo(), false, false, false, 0);
6624 // Address of cos field.
6625 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6626 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6627 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6628 MachinePointerInfo(), false, false, false, 0);
6630 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6631 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6632 LoadSin.getValue(0), LoadCos.getValue(0));
6635 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6637 SDValue &Chain) const {
6638 EVT VT = Op.getValueType();
6639 assert((VT == MVT::i32 || VT == MVT::i64) &&
6640 "unexpected type for custom lowering DIV");
6643 const auto &DL = DAG.getDataLayout();
6644 const auto &TLI = DAG.getTargetLoweringInfo();
6646 const char *Name = nullptr;
6648 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6650 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6652 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6654 ARMTargetLowering::ArgListTy Args;
6656 for (auto AI : {1, 0}) {
6658 Arg.Node = Op.getOperand(AI);
6659 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6660 Args.push_back(Arg);
6663 CallLoweringInfo CLI(DAG);
6666 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6667 ES, std::move(Args), 0);
6669 return LowerCallTo(CLI).first;
6672 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6673 bool Signed) const {
6674 assert(Op.getValueType() == MVT::i32 &&
6675 "unexpected type for custom lowering DIV");
6678 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6679 DAG.getEntryNode(), Op.getOperand(1));
6681 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6684 void ARMTargetLowering::ExpandDIV_Windows(
6685 SDValue Op, SelectionDAG &DAG, bool Signed,
6686 SmallVectorImpl<SDValue> &Results) const {
6687 const auto &DL = DAG.getDataLayout();
6688 const auto &TLI = DAG.getTargetLoweringInfo();
6690 assert(Op.getValueType() == MVT::i64 &&
6691 "unexpected type for custom lowering DIV");
6694 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6695 DAG.getConstant(0, dl, MVT::i32));
6696 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6697 DAG.getConstant(1, dl, MVT::i32));
6698 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6701 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6703 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6705 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6706 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6707 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6708 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6710 Results.push_back(Lower);
6711 Results.push_back(Upper);
6714 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6715 // Monotonic load/store is legal for all targets
6716 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6719 // Acquire/Release load/store is not legal for targets without a
6720 // dmb or equivalent available.
6724 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6725 SmallVectorImpl<SDValue> &Results,
6727 const ARMSubtarget *Subtarget) {
6729 // Under Power Management extensions, the cycle-count is:
6730 // mrc p15, #0, <Rt>, c9, c13, #0
6731 SDValue Ops[] = { N->getOperand(0), // Chain
6732 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6733 DAG.getConstant(15, DL, MVT::i32),
6734 DAG.getConstant(0, DL, MVT::i32),
6735 DAG.getConstant(9, DL, MVT::i32),
6736 DAG.getConstant(13, DL, MVT::i32),
6737 DAG.getConstant(0, DL, MVT::i32)
6740 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6741 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6742 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6743 DAG.getConstant(0, DL, MVT::i32)));
6744 Results.push_back(Cycles32.getValue(1));
6747 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6748 switch (Op.getOpcode()) {
6749 default: llvm_unreachable("Don't know how to custom lower this!");
6750 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6751 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6752 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6753 case ISD::GlobalAddress:
6754 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6755 default: llvm_unreachable("unknown object format");
6757 return LowerGlobalAddressWindows(Op, DAG);
6759 return LowerGlobalAddressELF(Op, DAG);
6761 return LowerGlobalAddressDarwin(Op, DAG);
6763 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6764 case ISD::SELECT: return LowerSELECT(Op, DAG);
6765 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6766 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6767 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6768 case ISD::VASTART: return LowerVASTART(Op, DAG);
6769 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6770 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6771 case ISD::SINT_TO_FP:
6772 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6773 case ISD::FP_TO_SINT:
6774 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6775 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6776 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6777 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6778 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6779 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6780 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6781 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6782 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6784 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6787 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6788 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
6789 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
6790 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6791 case ISD::SRL_PARTS:
6792 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6794 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6795 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6796 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6797 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6798 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6799 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6800 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6801 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6802 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6803 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6804 case ISD::MUL: return LowerMUL(Op, DAG);
6806 if (Subtarget->isTargetWindows())
6807 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
6808 return LowerSDIV(Op, DAG);
6810 if (Subtarget->isTargetWindows())
6811 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
6812 return LowerUDIV(Op, DAG);
6816 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6821 return LowerXALUO(Op, DAG);
6822 case ISD::ATOMIC_LOAD:
6823 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6824 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6826 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6827 case ISD::DYNAMIC_STACKALLOC:
6828 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6829 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6830 llvm_unreachable("Don't know how to custom lower this!");
6831 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6832 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6833 case ARMISD::WIN__DBZCHK: return SDValue();
6837 /// ReplaceNodeResults - Replace the results of node with an illegal result
6838 /// type with new values built out of custom code.
6839 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6840 SmallVectorImpl<SDValue> &Results,
6841 SelectionDAG &DAG) const {
6843 switch (N->getOpcode()) {
6845 llvm_unreachable("Don't know how to custom expand this!");
6846 case ISD::READ_REGISTER:
6847 ExpandREAD_REGISTER(N, Results, DAG);
6850 Res = ExpandBITCAST(N, DAG);
6854 Res = Expand64BitShift(N, DAG, Subtarget);
6858 Res = LowerREM(N, DAG);
6860 case ISD::READCYCLECOUNTER:
6861 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6865 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6866 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6870 Results.push_back(Res);
6873 //===----------------------------------------------------------------------===//
6874 // ARM Scheduler Hooks
6875 //===----------------------------------------------------------------------===//
6877 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6878 /// registers the function context.
6879 void ARMTargetLowering::
6880 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6881 MachineBasicBlock *DispatchBB, int FI) const {
6882 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6883 DebugLoc dl = MI->getDebugLoc();
6884 MachineFunction *MF = MBB->getParent();
6885 MachineRegisterInfo *MRI = &MF->getRegInfo();
6886 MachineConstantPool *MCP = MF->getConstantPool();
6887 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6888 const Function *F = MF->getFunction();
6890 bool isThumb = Subtarget->isThumb();
6891 bool isThumb2 = Subtarget->isThumb2();
6893 unsigned PCLabelId = AFI->createPICLabelUId();
6894 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6895 ARMConstantPoolValue *CPV =
6896 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6897 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6899 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6900 : &ARM::GPRRegClass;
6902 // Grab constant pool and fixed stack memory operands.
6903 MachineMemOperand *CPMMO =
6904 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6905 MachineMemOperand::MOLoad, 4, 4);
6907 MachineMemOperand *FIMMOSt =
6908 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6909 MachineMemOperand::MOStore, 4, 4);
6911 // Load the address of the dispatch MBB into the jump buffer.
6913 // Incoming value: jbuf
6914 // ldr.n r5, LCPI1_1
6917 // str r5, [$jbuf, #+4] ; &jbuf[1]
6918 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6919 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6920 .addConstantPoolIndex(CPI)
6921 .addMemOperand(CPMMO));
6922 // Set the low bit because of thumb mode.
6923 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6925 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6926 .addReg(NewVReg1, RegState::Kill)
6928 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6929 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6930 .addReg(NewVReg2, RegState::Kill)
6932 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6933 .addReg(NewVReg3, RegState::Kill)
6935 .addImm(36) // &jbuf[1] :: pc
6936 .addMemOperand(FIMMOSt));
6937 } else if (isThumb) {
6938 // Incoming value: jbuf
6939 // ldr.n r1, LCPI1_4
6943 // add r2, $jbuf, #+4 ; &jbuf[1]
6945 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6946 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6947 .addConstantPoolIndex(CPI)
6948 .addMemOperand(CPMMO));
6949 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6950 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6951 .addReg(NewVReg1, RegState::Kill)
6953 // Set the low bit because of thumb mode.
6954 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6955 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6956 .addReg(ARM::CPSR, RegState::Define)
6958 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6959 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6960 .addReg(ARM::CPSR, RegState::Define)
6961 .addReg(NewVReg2, RegState::Kill)
6962 .addReg(NewVReg3, RegState::Kill));
6963 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6964 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6966 .addImm(36); // &jbuf[1] :: pc
6967 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6968 .addReg(NewVReg4, RegState::Kill)
6969 .addReg(NewVReg5, RegState::Kill)
6971 .addMemOperand(FIMMOSt));
6973 // Incoming value: jbuf
6976 // str r1, [$jbuf, #+4] ; &jbuf[1]
6977 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6978 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6979 .addConstantPoolIndex(CPI)
6981 .addMemOperand(CPMMO));
6982 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6983 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6984 .addReg(NewVReg1, RegState::Kill)
6985 .addImm(PCLabelId));
6986 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6987 .addReg(NewVReg2, RegState::Kill)
6989 .addImm(36) // &jbuf[1] :: pc
6990 .addMemOperand(FIMMOSt));
6994 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6995 MachineBasicBlock *MBB) const {
6996 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6997 DebugLoc dl = MI->getDebugLoc();
6998 MachineFunction *MF = MBB->getParent();
6999 MachineRegisterInfo *MRI = &MF->getRegInfo();
7000 MachineFrameInfo *MFI = MF->getFrameInfo();
7001 int FI = MFI->getFunctionContextIndex();
7003 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7004 : &ARM::GPRnopcRegClass;
7006 // Get a mapping of the call site numbers to all of the landing pads they're
7008 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7009 unsigned MaxCSNum = 0;
7010 MachineModuleInfo &MMI = MF->getMMI();
7011 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7013 if (!BB->isEHPad()) continue;
7015 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7017 for (MachineBasicBlock::iterator
7018 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7019 if (!II->isEHLabel()) continue;
7021 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7022 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7024 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7025 for (SmallVectorImpl<unsigned>::iterator
7026 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7027 CSI != CSE; ++CSI) {
7028 CallSiteNumToLPad[*CSI].push_back(BB);
7029 MaxCSNum = std::max(MaxCSNum, *CSI);
7035 // Get an ordered list of the machine basic blocks for the jump table.
7036 std::vector<MachineBasicBlock*> LPadList;
7037 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7038 LPadList.reserve(CallSiteNumToLPad.size());
7039 for (unsigned I = 1; I <= MaxCSNum; ++I) {
7040 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7041 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7042 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7043 LPadList.push_back(*II);
7044 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7048 assert(!LPadList.empty() &&
7049 "No landing pad destinations for the dispatch jump table!");
7051 // Create the jump table and associated information.
7052 MachineJumpTableInfo *JTI =
7053 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7054 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7055 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7057 // Create the MBBs for the dispatch code.
7059 // Shove the dispatch's address into the return slot in the function context.
7060 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7061 DispatchBB->setIsEHPad();
7063 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7064 unsigned trap_opcode;
7065 if (Subtarget->isThumb())
7066 trap_opcode = ARM::tTRAP;
7068 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7070 BuildMI(TrapBB, dl, TII->get(trap_opcode));
7071 DispatchBB->addSuccessor(TrapBB);
7073 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7074 DispatchBB->addSuccessor(DispContBB);
7077 MF->insert(MF->end(), DispatchBB);
7078 MF->insert(MF->end(), DispContBB);
7079 MF->insert(MF->end(), TrapBB);
7081 // Insert code into the entry block that creates and registers the function
7083 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7085 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7086 MachinePointerInfo::getFixedStack(*MF, FI),
7087 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7089 MachineInstrBuilder MIB;
7090 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7092 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7093 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7095 // Add a register mask with no preserved registers. This results in all
7096 // registers being marked as clobbered.
7097 MIB.addRegMask(RI.getNoPreservedMask());
7099 unsigned NumLPads = LPadList.size();
7100 if (Subtarget->isThumb2()) {
7101 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7102 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7105 .addMemOperand(FIMMOLd));
7107 if (NumLPads < 256) {
7108 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7110 .addImm(LPadList.size()));
7112 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7113 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7114 .addImm(NumLPads & 0xFFFF));
7116 unsigned VReg2 = VReg1;
7117 if ((NumLPads & 0xFFFF0000) != 0) {
7118 VReg2 = MRI->createVirtualRegister(TRC);
7119 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7121 .addImm(NumLPads >> 16));
7124 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7129 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7134 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7135 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7136 .addJumpTableIndex(MJTI));
7138 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7141 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7142 .addReg(NewVReg3, RegState::Kill)
7144 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7146 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7147 .addReg(NewVReg4, RegState::Kill)
7149 .addJumpTableIndex(MJTI);
7150 } else if (Subtarget->isThumb()) {
7151 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7152 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7155 .addMemOperand(FIMMOLd));
7157 if (NumLPads < 256) {
7158 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7162 MachineConstantPool *ConstantPool = MF->getConstantPool();
7163 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7164 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7166 // MachineConstantPool wants an explicit alignment.
7167 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7169 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7170 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7172 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7173 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7174 .addReg(VReg1, RegState::Define)
7175 .addConstantPoolIndex(Idx));
7176 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7181 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7186 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7187 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7188 .addReg(ARM::CPSR, RegState::Define)
7192 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7193 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7194 .addJumpTableIndex(MJTI));
7196 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7197 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7198 .addReg(ARM::CPSR, RegState::Define)
7199 .addReg(NewVReg2, RegState::Kill)
7202 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7203 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7205 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7206 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7207 .addReg(NewVReg4, RegState::Kill)
7209 .addMemOperand(JTMMOLd));
7211 unsigned NewVReg6 = NewVReg5;
7212 if (RelocM == Reloc::PIC_) {
7213 NewVReg6 = MRI->createVirtualRegister(TRC);
7214 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7215 .addReg(ARM::CPSR, RegState::Define)
7216 .addReg(NewVReg5, RegState::Kill)
7220 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7221 .addReg(NewVReg6, RegState::Kill)
7222 .addJumpTableIndex(MJTI);
7224 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7225 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7228 .addMemOperand(FIMMOLd));
7230 if (NumLPads < 256) {
7231 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7234 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7235 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7236 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7237 .addImm(NumLPads & 0xFFFF));
7239 unsigned VReg2 = VReg1;
7240 if ((NumLPads & 0xFFFF0000) != 0) {
7241 VReg2 = MRI->createVirtualRegister(TRC);
7242 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7244 .addImm(NumLPads >> 16));
7247 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7251 MachineConstantPool *ConstantPool = MF->getConstantPool();
7252 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7253 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7255 // MachineConstantPool wants an explicit alignment.
7256 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7258 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7259 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7261 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7262 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7263 .addReg(VReg1, RegState::Define)
7264 .addConstantPoolIndex(Idx)
7266 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7268 .addReg(VReg1, RegState::Kill));
7271 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7276 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7278 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7280 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7281 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7282 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7283 .addJumpTableIndex(MJTI));
7285 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7286 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7287 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7289 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7290 .addReg(NewVReg3, RegState::Kill)
7293 .addMemOperand(JTMMOLd));
7295 if (RelocM == Reloc::PIC_) {
7296 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7297 .addReg(NewVReg5, RegState::Kill)
7299 .addJumpTableIndex(MJTI);
7301 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7302 .addReg(NewVReg5, RegState::Kill)
7303 .addJumpTableIndex(MJTI);
7307 // Add the jump table entries as successors to the MBB.
7308 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7309 for (std::vector<MachineBasicBlock*>::iterator
7310 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7311 MachineBasicBlock *CurMBB = *I;
7312 if (SeenMBBs.insert(CurMBB).second)
7313 DispContBB->addSuccessor(CurMBB);
7316 // N.B. the order the invoke BBs are processed in doesn't matter here.
7317 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7318 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7319 for (MachineBasicBlock *BB : InvokeBBs) {
7321 // Remove the landing pad successor from the invoke block and replace it
7322 // with the new dispatch block.
7323 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7325 while (!Successors.empty()) {
7326 MachineBasicBlock *SMBB = Successors.pop_back_val();
7327 if (SMBB->isEHPad()) {
7328 BB->removeSuccessor(SMBB);
7329 MBBLPads.push_back(SMBB);
7333 BB->addSuccessor(DispatchBB);
7335 // Find the invoke call and mark all of the callee-saved registers as
7336 // 'implicit defined' so that they're spilled. This prevents code from
7337 // moving instructions to before the EH block, where they will never be
7339 for (MachineBasicBlock::reverse_iterator
7340 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7341 if (!II->isCall()) continue;
7343 DenseMap<unsigned, bool> DefRegs;
7344 for (MachineInstr::mop_iterator
7345 OI = II->operands_begin(), OE = II->operands_end();
7347 if (!OI->isReg()) continue;
7348 DefRegs[OI->getReg()] = true;
7351 MachineInstrBuilder MIB(*MF, &*II);
7353 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7354 unsigned Reg = SavedRegs[i];
7355 if (Subtarget->isThumb2() &&
7356 !ARM::tGPRRegClass.contains(Reg) &&
7357 !ARM::hGPRRegClass.contains(Reg))
7359 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7361 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7364 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7371 // Mark all former landing pads as non-landing pads. The dispatch is the only
7373 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7374 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7375 (*I)->setIsEHPad(false);
7377 // The instruction is gone now.
7378 MI->eraseFromParent();
7382 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7383 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7384 E = MBB->succ_end(); I != E; ++I)
7387 llvm_unreachable("Expecting a BB with two successors!");
7390 /// Return the load opcode for a given load size. If load size >= 8,
7391 /// neon opcode will be returned.
7392 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7394 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7395 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7397 return LdSize == 4 ? ARM::tLDRi
7398 : LdSize == 2 ? ARM::tLDRHi
7399 : LdSize == 1 ? ARM::tLDRBi : 0;
7401 return LdSize == 4 ? ARM::t2LDR_POST
7402 : LdSize == 2 ? ARM::t2LDRH_POST
7403 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7404 return LdSize == 4 ? ARM::LDR_POST_IMM
7405 : LdSize == 2 ? ARM::LDRH_POST
7406 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7409 /// Return the store opcode for a given store size. If store size >= 8,
7410 /// neon opcode will be returned.
7411 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7413 return StSize == 16 ? ARM::VST1q32wb_fixed
7414 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7416 return StSize == 4 ? ARM::tSTRi
7417 : StSize == 2 ? ARM::tSTRHi
7418 : StSize == 1 ? ARM::tSTRBi : 0;
7420 return StSize == 4 ? ARM::t2STR_POST
7421 : StSize == 2 ? ARM::t2STRH_POST
7422 : StSize == 1 ? ARM::t2STRB_POST : 0;
7423 return StSize == 4 ? ARM::STR_POST_IMM
7424 : StSize == 2 ? ARM::STRH_POST
7425 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7428 /// Emit a post-increment load operation with given size. The instructions
7429 /// will be added to BB at Pos.
7430 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7431 const TargetInstrInfo *TII, DebugLoc dl,
7432 unsigned LdSize, unsigned Data, unsigned AddrIn,
7433 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7434 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7435 assert(LdOpc != 0 && "Should have a load opcode");
7437 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7438 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7440 } else if (IsThumb1) {
7441 // load + update AddrIn
7442 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7443 .addReg(AddrIn).addImm(0));
7444 MachineInstrBuilder MIB =
7445 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7446 MIB = AddDefaultT1CC(MIB);
7447 MIB.addReg(AddrIn).addImm(LdSize);
7448 AddDefaultPred(MIB);
7449 } else if (IsThumb2) {
7450 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7451 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7454 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7455 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7456 .addReg(0).addImm(LdSize));
7460 /// Emit a post-increment store operation with given size. The instructions
7461 /// will be added to BB at Pos.
7462 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7463 const TargetInstrInfo *TII, DebugLoc dl,
7464 unsigned StSize, unsigned Data, unsigned AddrIn,
7465 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7466 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7467 assert(StOpc != 0 && "Should have a store opcode");
7469 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7470 .addReg(AddrIn).addImm(0).addReg(Data));
7471 } else if (IsThumb1) {
7472 // store + update AddrIn
7473 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7474 .addReg(AddrIn).addImm(0));
7475 MachineInstrBuilder MIB =
7476 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7477 MIB = AddDefaultT1CC(MIB);
7478 MIB.addReg(AddrIn).addImm(StSize);
7479 AddDefaultPred(MIB);
7480 } else if (IsThumb2) {
7481 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7482 .addReg(Data).addReg(AddrIn).addImm(StSize));
7484 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7485 .addReg(Data).addReg(AddrIn).addReg(0)
7491 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7492 MachineBasicBlock *BB) const {
7493 // This pseudo instruction has 3 operands: dst, src, size
7494 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7495 // Otherwise, we will generate unrolled scalar copies.
7496 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7497 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7498 MachineFunction::iterator It = BB;
7501 unsigned dest = MI->getOperand(0).getReg();
7502 unsigned src = MI->getOperand(1).getReg();
7503 unsigned SizeVal = MI->getOperand(2).getImm();
7504 unsigned Align = MI->getOperand(3).getImm();
7505 DebugLoc dl = MI->getDebugLoc();
7507 MachineFunction *MF = BB->getParent();
7508 MachineRegisterInfo &MRI = MF->getRegInfo();
7509 unsigned UnitSize = 0;
7510 const TargetRegisterClass *TRC = nullptr;
7511 const TargetRegisterClass *VecTRC = nullptr;
7513 bool IsThumb1 = Subtarget->isThumb1Only();
7514 bool IsThumb2 = Subtarget->isThumb2();
7518 } else if (Align & 2) {
7521 // Check whether we can use NEON instructions.
7522 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7523 Subtarget->hasNEON()) {
7524 if ((Align % 16 == 0) && SizeVal >= 16)
7526 else if ((Align % 8 == 0) && SizeVal >= 8)
7529 // Can't use NEON instructions.
7534 // Select the correct opcode and register class for unit size load/store
7535 bool IsNeon = UnitSize >= 8;
7536 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7538 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7539 : UnitSize == 8 ? &ARM::DPRRegClass
7542 unsigned BytesLeft = SizeVal % UnitSize;
7543 unsigned LoopSize = SizeVal - BytesLeft;
7545 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7546 // Use LDR and STR to copy.
7547 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7548 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7549 unsigned srcIn = src;
7550 unsigned destIn = dest;
7551 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7552 unsigned srcOut = MRI.createVirtualRegister(TRC);
7553 unsigned destOut = MRI.createVirtualRegister(TRC);
7554 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7555 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7556 IsThumb1, IsThumb2);
7557 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7558 IsThumb1, IsThumb2);
7563 // Handle the leftover bytes with LDRB and STRB.
7564 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7565 // [destOut] = STRB_POST(scratch, destIn, 1)
7566 for (unsigned i = 0; i < BytesLeft; i++) {
7567 unsigned srcOut = MRI.createVirtualRegister(TRC);
7568 unsigned destOut = MRI.createVirtualRegister(TRC);
7569 unsigned scratch = MRI.createVirtualRegister(TRC);
7570 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7571 IsThumb1, IsThumb2);
7572 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7573 IsThumb1, IsThumb2);
7577 MI->eraseFromParent(); // The instruction is gone now.
7581 // Expand the pseudo op to a loop.
7584 // movw varEnd, # --> with thumb2
7586 // ldrcp varEnd, idx --> without thumb2
7587 // fallthrough --> loopMBB
7589 // PHI varPhi, varEnd, varLoop
7590 // PHI srcPhi, src, srcLoop
7591 // PHI destPhi, dst, destLoop
7592 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7593 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7594 // subs varLoop, varPhi, #UnitSize
7596 // fallthrough --> exitMBB
7598 // epilogue to handle left-over bytes
7599 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7600 // [destOut] = STRB_POST(scratch, destLoop, 1)
7601 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7602 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7603 MF->insert(It, loopMBB);
7604 MF->insert(It, exitMBB);
7606 // Transfer the remainder of BB and its successor edges to exitMBB.
7607 exitMBB->splice(exitMBB->begin(), BB,
7608 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7609 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7611 // Load an immediate to varEnd.
7612 unsigned varEnd = MRI.createVirtualRegister(TRC);
7613 if (Subtarget->useMovt(*MF)) {
7614 unsigned Vtmp = varEnd;
7615 if ((LoopSize & 0xFFFF0000) != 0)
7616 Vtmp = MRI.createVirtualRegister(TRC);
7617 AddDefaultPred(BuildMI(BB, dl,
7618 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7619 Vtmp).addImm(LoopSize & 0xFFFF));
7621 if ((LoopSize & 0xFFFF0000) != 0)
7622 AddDefaultPred(BuildMI(BB, dl,
7623 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7626 .addImm(LoopSize >> 16));
7628 MachineConstantPool *ConstantPool = MF->getConstantPool();
7629 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7630 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7632 // MachineConstantPool wants an explicit alignment.
7633 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7635 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7636 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7639 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7640 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7642 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7643 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7645 BB->addSuccessor(loopMBB);
7647 // Generate the loop body:
7648 // varPhi = PHI(varLoop, varEnd)
7649 // srcPhi = PHI(srcLoop, src)
7650 // destPhi = PHI(destLoop, dst)
7651 MachineBasicBlock *entryBB = BB;
7653 unsigned varLoop = MRI.createVirtualRegister(TRC);
7654 unsigned varPhi = MRI.createVirtualRegister(TRC);
7655 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7656 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7657 unsigned destLoop = MRI.createVirtualRegister(TRC);
7658 unsigned destPhi = MRI.createVirtualRegister(TRC);
7660 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7661 .addReg(varLoop).addMBB(loopMBB)
7662 .addReg(varEnd).addMBB(entryBB);
7663 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7664 .addReg(srcLoop).addMBB(loopMBB)
7665 .addReg(src).addMBB(entryBB);
7666 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7667 .addReg(destLoop).addMBB(loopMBB)
7668 .addReg(dest).addMBB(entryBB);
7670 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7671 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7672 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7673 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7674 IsThumb1, IsThumb2);
7675 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7676 IsThumb1, IsThumb2);
7678 // Decrement loop variable by UnitSize.
7680 MachineInstrBuilder MIB =
7681 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7682 MIB = AddDefaultT1CC(MIB);
7683 MIB.addReg(varPhi).addImm(UnitSize);
7684 AddDefaultPred(MIB);
7686 MachineInstrBuilder MIB =
7687 BuildMI(*BB, BB->end(), dl,
7688 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7689 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7690 MIB->getOperand(5).setReg(ARM::CPSR);
7691 MIB->getOperand(5).setIsDef(true);
7693 BuildMI(*BB, BB->end(), dl,
7694 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7695 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7697 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7698 BB->addSuccessor(loopMBB);
7699 BB->addSuccessor(exitMBB);
7701 // Add epilogue to handle BytesLeft.
7703 MachineInstr *StartOfExit = exitMBB->begin();
7705 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7706 // [destOut] = STRB_POST(scratch, destLoop, 1)
7707 unsigned srcIn = srcLoop;
7708 unsigned destIn = destLoop;
7709 for (unsigned i = 0; i < BytesLeft; i++) {
7710 unsigned srcOut = MRI.createVirtualRegister(TRC);
7711 unsigned destOut = MRI.createVirtualRegister(TRC);
7712 unsigned scratch = MRI.createVirtualRegister(TRC);
7713 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7714 IsThumb1, IsThumb2);
7715 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7716 IsThumb1, IsThumb2);
7721 MI->eraseFromParent(); // The instruction is gone now.
7726 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7727 MachineBasicBlock *MBB) const {
7728 const TargetMachine &TM = getTargetMachine();
7729 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7730 DebugLoc DL = MI->getDebugLoc();
7732 assert(Subtarget->isTargetWindows() &&
7733 "__chkstk is only supported on Windows");
7734 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7736 // __chkstk takes the number of words to allocate on the stack in R4, and
7737 // returns the stack adjustment in number of bytes in R4. This will not
7738 // clober any other registers (other than the obvious lr).
7740 // Although, technically, IP should be considered a register which may be
7741 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7742 // thumb-2 environment, so there is no interworking required. As a result, we
7743 // do not expect a veneer to be emitted by the linker, clobbering IP.
7745 // Each module receives its own copy of __chkstk, so no import thunk is
7746 // required, again, ensuring that IP is not clobbered.
7748 // Finally, although some linkers may theoretically provide a trampoline for
7749 // out of range calls (which is quite common due to a 32M range limitation of
7750 // branches for Thumb), we can generate the long-call version via
7751 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7754 switch (TM.getCodeModel()) {
7755 case CodeModel::Small:
7756 case CodeModel::Medium:
7757 case CodeModel::Default:
7758 case CodeModel::Kernel:
7759 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7760 .addImm((unsigned)ARMCC::AL).addReg(0)
7761 .addExternalSymbol("__chkstk")
7762 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7763 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7764 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7766 case CodeModel::Large:
7767 case CodeModel::JITDefault: {
7768 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7769 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7771 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7772 .addExternalSymbol("__chkstk");
7773 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7774 .addImm((unsigned)ARMCC::AL).addReg(0)
7775 .addReg(Reg, RegState::Kill)
7776 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7777 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7778 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7783 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7785 .addReg(ARM::SP).addReg(ARM::R4)));
7787 MI->eraseFromParent();
7792 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7793 MachineBasicBlock *MBB) const {
7794 DebugLoc DL = MI->getDebugLoc();
7795 MachineFunction *MF = MBB->getParent();
7796 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7798 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7799 MF->push_back(ContBB);
7800 ContBB->splice(ContBB->begin(), MBB,
7801 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7802 MBB->addSuccessor(ContBB);
7804 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7805 MF->push_back(TrapBB);
7806 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7807 MBB->addSuccessor(TrapBB);
7809 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7810 .addReg(MI->getOperand(0).getReg())
7813 MI->eraseFromParent();
7818 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7819 MachineBasicBlock *BB) const {
7820 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7821 DebugLoc dl = MI->getDebugLoc();
7822 bool isThumb2 = Subtarget->isThumb2();
7823 switch (MI->getOpcode()) {
7826 llvm_unreachable("Unexpected instr type to insert");
7828 // The Thumb2 pre-indexed stores have the same MI operands, they just
7829 // define them differently in the .td files from the isel patterns, so
7830 // they need pseudos.
7831 case ARM::t2STR_preidx:
7832 MI->setDesc(TII->get(ARM::t2STR_PRE));
7834 case ARM::t2STRB_preidx:
7835 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7837 case ARM::t2STRH_preidx:
7838 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7841 case ARM::STRi_preidx:
7842 case ARM::STRBi_preidx: {
7843 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7844 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7845 // Decode the offset.
7846 unsigned Offset = MI->getOperand(4).getImm();
7847 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7848 Offset = ARM_AM::getAM2Offset(Offset);
7852 MachineMemOperand *MMO = *MI->memoperands_begin();
7853 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7854 .addOperand(MI->getOperand(0)) // Rn_wb
7855 .addOperand(MI->getOperand(1)) // Rt
7856 .addOperand(MI->getOperand(2)) // Rn
7857 .addImm(Offset) // offset (skip GPR==zero_reg)
7858 .addOperand(MI->getOperand(5)) // pred
7859 .addOperand(MI->getOperand(6))
7860 .addMemOperand(MMO);
7861 MI->eraseFromParent();
7864 case ARM::STRr_preidx:
7865 case ARM::STRBr_preidx:
7866 case ARM::STRH_preidx: {
7868 switch (MI->getOpcode()) {
7869 default: llvm_unreachable("unexpected opcode!");
7870 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7871 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7872 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7874 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7875 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7876 MIB.addOperand(MI->getOperand(i));
7877 MI->eraseFromParent();
7881 case ARM::tMOVCCr_pseudo: {
7882 // To "insert" a SELECT_CC instruction, we actually have to insert the
7883 // diamond control-flow pattern. The incoming instruction knows the
7884 // destination vreg to set, the condition code register to branch on, the
7885 // true/false values to select between, and a branch opcode to use.
7886 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7887 MachineFunction::iterator It = BB;
7893 // cmpTY ccX, r1, r2
7895 // fallthrough --> copy0MBB
7896 MachineBasicBlock *thisMBB = BB;
7897 MachineFunction *F = BB->getParent();
7898 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7899 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7900 F->insert(It, copy0MBB);
7901 F->insert(It, sinkMBB);
7903 // Transfer the remainder of BB and its successor edges to sinkMBB.
7904 sinkMBB->splice(sinkMBB->begin(), BB,
7905 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7906 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7908 BB->addSuccessor(copy0MBB);
7909 BB->addSuccessor(sinkMBB);
7911 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7912 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7915 // %FalseValue = ...
7916 // # fallthrough to sinkMBB
7919 // Update machine-CFG edges
7920 BB->addSuccessor(sinkMBB);
7923 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7926 BuildMI(*BB, BB->begin(), dl,
7927 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7928 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7929 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7931 MI->eraseFromParent(); // The pseudo instruction is gone now.
7936 case ARM::BCCZi64: {
7937 // If there is an unconditional branch to the other successor, remove it.
7938 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7940 // Compare both parts that make up the double comparison separately for
7942 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7944 unsigned LHS1 = MI->getOperand(1).getReg();
7945 unsigned LHS2 = MI->getOperand(2).getReg();
7947 AddDefaultPred(BuildMI(BB, dl,
7948 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7949 .addReg(LHS1).addImm(0));
7950 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7951 .addReg(LHS2).addImm(0)
7952 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7954 unsigned RHS1 = MI->getOperand(3).getReg();
7955 unsigned RHS2 = MI->getOperand(4).getReg();
7956 AddDefaultPred(BuildMI(BB, dl,
7957 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7958 .addReg(LHS1).addReg(RHS1));
7959 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7960 .addReg(LHS2).addReg(RHS2)
7961 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7964 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7965 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7966 if (MI->getOperand(0).getImm() == ARMCC::NE)
7967 std::swap(destMBB, exitMBB);
7969 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7970 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7972 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7974 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7976 MI->eraseFromParent(); // The pseudo instruction is gone now.
7980 case ARM::Int_eh_sjlj_setjmp:
7981 case ARM::Int_eh_sjlj_setjmp_nofp:
7982 case ARM::tInt_eh_sjlj_setjmp:
7983 case ARM::t2Int_eh_sjlj_setjmp:
7984 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7987 case ARM::Int_eh_sjlj_setup_dispatch:
7988 EmitSjLjDispatchBlock(MI, BB);
7993 // To insert an ABS instruction, we have to insert the
7994 // diamond control-flow pattern. The incoming instruction knows the
7995 // source vreg to test against 0, the destination vreg to set,
7996 // the condition code register to branch on, the
7997 // true/false values to select between, and a branch opcode to use.
8002 // BCC (branch to SinkBB if V0 >= 0)
8003 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
8004 // SinkBB: V1 = PHI(V2, V3)
8005 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8006 MachineFunction::iterator BBI = BB;
8008 MachineFunction *Fn = BB->getParent();
8009 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8010 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8011 Fn->insert(BBI, RSBBB);
8012 Fn->insert(BBI, SinkBB);
8014 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8015 unsigned int ABSDstReg = MI->getOperand(0).getReg();
8016 bool ABSSrcKIll = MI->getOperand(1).isKill();
8017 bool isThumb2 = Subtarget->isThumb2();
8018 MachineRegisterInfo &MRI = Fn->getRegInfo();
8019 // In Thumb mode S must not be specified if source register is the SP or
8020 // PC and if destination register is the SP, so restrict register class
8021 unsigned NewRsbDstReg =
8022 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8024 // Transfer the remainder of BB and its successor edges to sinkMBB.
8025 SinkBB->splice(SinkBB->begin(), BB,
8026 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8027 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8029 BB->addSuccessor(RSBBB);
8030 BB->addSuccessor(SinkBB);
8032 // fall through to SinkMBB
8033 RSBBB->addSuccessor(SinkBB);
8035 // insert a cmp at the end of BB
8036 AddDefaultPred(BuildMI(BB, dl,
8037 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8038 .addReg(ABSSrcReg).addImm(0));
8040 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8042 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8043 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8045 // insert rsbri in RSBBB
8046 // Note: BCC and rsbri will be converted into predicated rsbmi
8047 // by if-conversion pass
8048 BuildMI(*RSBBB, RSBBB->begin(), dl,
8049 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8050 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8051 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8053 // insert PHI in SinkBB,
8054 // reuse ABSDstReg to not change uses of ABS instruction
8055 BuildMI(*SinkBB, SinkBB->begin(), dl,
8056 TII->get(ARM::PHI), ABSDstReg)
8057 .addReg(NewRsbDstReg).addMBB(RSBBB)
8058 .addReg(ABSSrcReg).addMBB(BB);
8060 // remove ABS instruction
8061 MI->eraseFromParent();
8063 // return last added BB
8066 case ARM::COPY_STRUCT_BYVAL_I32:
8068 return EmitStructByval(MI, BB);
8069 case ARM::WIN__CHKSTK:
8070 return EmitLowered__chkstk(MI, BB);
8071 case ARM::WIN__DBZCHK:
8072 return EmitLowered__dbzchk(MI, BB);
8076 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8077 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8078 /// instead of as a custom inserter because we need the use list from the SDNode.
8079 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8080 MachineInstr *MI, const SDNode *Node) {
8081 bool isThumb1 = Subtarget->isThumb1Only();
8083 DebugLoc DL = MI->getDebugLoc();
8084 MachineFunction *MF = MI->getParent()->getParent();
8085 MachineRegisterInfo &MRI = MF->getRegInfo();
8086 MachineInstrBuilder MIB(*MF, MI);
8088 // If the new dst/src is unused mark it as dead.
8089 if (!Node->hasAnyUseOfValue(0)) {
8090 MI->getOperand(0).setIsDead(true);
8092 if (!Node->hasAnyUseOfValue(1)) {
8093 MI->getOperand(1).setIsDead(true);
8096 // The MEMCPY both defines and kills the scratch registers.
8097 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8098 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8099 : &ARM::GPRRegClass);
8100 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8104 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8105 SDNode *Node) const {
8106 if (MI->getOpcode() == ARM::MEMCPY) {
8107 attachMEMCPYScratchRegs(Subtarget, MI, Node);
8111 const MCInstrDesc *MCID = &MI->getDesc();
8112 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8113 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8114 // operand is still set to noreg. If needed, set the optional operand's
8115 // register to CPSR, and remove the redundant implicit def.
8117 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8119 // Rename pseudo opcodes.
8120 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8122 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8123 MCID = &TII->get(NewOpc);
8125 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8126 "converted opcode should be the same except for cc_out");
8130 // Add the optional cc_out operand
8131 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8133 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8135 // Any ARM instruction that sets the 's' bit should specify an optional
8136 // "cc_out" operand in the last operand position.
8137 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8138 assert(!NewOpc && "Optional cc_out operand required");
8141 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8142 // since we already have an optional CPSR def.
8143 bool definesCPSR = false;
8144 bool deadCPSR = false;
8145 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8147 const MachineOperand &MO = MI->getOperand(i);
8148 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8152 MI->RemoveOperand(i);
8157 assert(!NewOpc && "Optional cc_out operand required");
8160 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8162 assert(!MI->getOperand(ccOutIdx).getReg() &&
8163 "expect uninitialized optional cc_out operand");
8167 // If this instruction was defined with an optional CPSR def and its dag node
8168 // had a live implicit CPSR def, then activate the optional CPSR def.
8169 MachineOperand &MO = MI->getOperand(ccOutIdx);
8170 MO.setReg(ARM::CPSR);
8174 //===----------------------------------------------------------------------===//
8175 // ARM Optimization Hooks
8176 //===----------------------------------------------------------------------===//
8178 // Helper function that checks if N is a null or all ones constant.
8179 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8180 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8183 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8186 // Return true if N is conditionally 0 or all ones.
8187 // Detects these expressions where cc is an i1 value:
8189 // (select cc 0, y) [AllOnes=0]
8190 // (select cc y, 0) [AllOnes=0]
8191 // (zext cc) [AllOnes=0]
8192 // (sext cc) [AllOnes=0/1]
8193 // (select cc -1, y) [AllOnes=1]
8194 // (select cc y, -1) [AllOnes=1]
8196 // Invert is set when N is the null/all ones constant when CC is false.
8197 // OtherOp is set to the alternative value of N.
8198 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8199 SDValue &CC, bool &Invert,
8201 SelectionDAG &DAG) {
8202 switch (N->getOpcode()) {
8203 default: return false;
8205 CC = N->getOperand(0);
8206 SDValue N1 = N->getOperand(1);
8207 SDValue N2 = N->getOperand(2);
8208 if (isZeroOrAllOnes(N1, AllOnes)) {
8213 if (isZeroOrAllOnes(N2, AllOnes)) {
8220 case ISD::ZERO_EXTEND:
8221 // (zext cc) can never be the all ones value.
8225 case ISD::SIGN_EXTEND: {
8227 EVT VT = N->getValueType(0);
8228 CC = N->getOperand(0);
8229 if (CC.getValueType() != MVT::i1)
8233 // When looking for an AllOnes constant, N is an sext, and the 'other'
8235 OtherOp = DAG.getConstant(0, dl, VT);
8236 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8237 // When looking for a 0 constant, N can be zext or sext.
8238 OtherOp = DAG.getConstant(1, dl, VT);
8240 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8247 // Combine a constant select operand into its use:
8249 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8250 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8251 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8252 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8253 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8255 // The transform is rejected if the select doesn't have a constant operand that
8256 // is null, or all ones when AllOnes is set.
8258 // Also recognize sext/zext from i1:
8260 // (add (zext cc), x) -> (select cc (add x, 1), x)
8261 // (add (sext cc), x) -> (select cc (add x, -1), x)
8263 // These transformations eventually create predicated instructions.
8265 // @param N The node to transform.
8266 // @param Slct The N operand that is a select.
8267 // @param OtherOp The other N operand (x above).
8268 // @param DCI Context.
8269 // @param AllOnes Require the select constant to be all ones instead of null.
8270 // @returns The new node, or SDValue() on failure.
8272 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8273 TargetLowering::DAGCombinerInfo &DCI,
8274 bool AllOnes = false) {
8275 SelectionDAG &DAG = DCI.DAG;
8276 EVT VT = N->getValueType(0);
8277 SDValue NonConstantVal;
8280 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8281 NonConstantVal, DAG))
8284 // Slct is now know to be the desired identity constant when CC is true.
8285 SDValue TrueVal = OtherOp;
8286 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8287 OtherOp, NonConstantVal);
8288 // Unless SwapSelectOps says CC should be false.
8290 std::swap(TrueVal, FalseVal);
8292 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8293 CCOp, TrueVal, FalseVal);
8296 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8298 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8299 TargetLowering::DAGCombinerInfo &DCI) {
8300 SDValue N0 = N->getOperand(0);
8301 SDValue N1 = N->getOperand(1);
8302 if (N0.getNode()->hasOneUse()) {
8303 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8304 if (Result.getNode())
8307 if (N1.getNode()->hasOneUse()) {
8308 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8309 if (Result.getNode())
8315 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8316 // (only after legalization).
8317 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8318 TargetLowering::DAGCombinerInfo &DCI,
8319 const ARMSubtarget *Subtarget) {
8321 // Only perform optimization if after legalize, and if NEON is available. We
8322 // also expected both operands to be BUILD_VECTORs.
8323 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8324 || N0.getOpcode() != ISD::BUILD_VECTOR
8325 || N1.getOpcode() != ISD::BUILD_VECTOR)
8328 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8329 EVT VT = N->getValueType(0);
8330 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8333 // Check that the vector operands are of the right form.
8334 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8335 // operands, where N is the size of the formed vector.
8336 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8337 // index such that we have a pair wise add pattern.
8339 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8340 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8342 SDValue Vec = N0->getOperand(0)->getOperand(0);
8343 SDNode *V = Vec.getNode();
8344 unsigned nextIndex = 0;
8346 // For each operands to the ADD which are BUILD_VECTORs,
8347 // check to see if each of their operands are an EXTRACT_VECTOR with
8348 // the same vector and appropriate index.
8349 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8350 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8351 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8353 SDValue ExtVec0 = N0->getOperand(i);
8354 SDValue ExtVec1 = N1->getOperand(i);
8356 // First operand is the vector, verify its the same.
8357 if (V != ExtVec0->getOperand(0).getNode() ||
8358 V != ExtVec1->getOperand(0).getNode())
8361 // Second is the constant, verify its correct.
8362 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8363 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8365 // For the constant, we want to see all the even or all the odd.
8366 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8367 || C1->getZExtValue() != nextIndex+1)
8376 // Create VPADDL node.
8377 SelectionDAG &DAG = DCI.DAG;
8378 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8382 // Build operand list.
8383 SmallVector<SDValue, 8> Ops;
8384 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8385 TLI.getPointerTy(DAG.getDataLayout())));
8387 // Input is the vector.
8390 // Get widened type and narrowed type.
8392 unsigned numElem = VT.getVectorNumElements();
8394 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8395 switch (inputLaneType.getSimpleVT().SimpleTy) {
8396 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8397 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8398 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8400 llvm_unreachable("Invalid vector element type for padd optimization.");
8403 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8404 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8405 return DAG.getNode(ExtOp, dl, VT, tmp);
8408 static SDValue findMUL_LOHI(SDValue V) {
8409 if (V->getOpcode() == ISD::UMUL_LOHI ||
8410 V->getOpcode() == ISD::SMUL_LOHI)
8415 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8416 TargetLowering::DAGCombinerInfo &DCI,
8417 const ARMSubtarget *Subtarget) {
8419 if (Subtarget->isThumb1Only()) return SDValue();
8421 // Only perform the checks after legalize when the pattern is available.
8422 if (DCI.isBeforeLegalize()) return SDValue();
8424 // Look for multiply add opportunities.
8425 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8426 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8427 // a glue link from the first add to the second add.
8428 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8429 // a S/UMLAL instruction.
8432 // / \ [no multiline comment]
8438 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8439 SDValue AddcOp0 = AddcNode->getOperand(0);
8440 SDValue AddcOp1 = AddcNode->getOperand(1);
8442 // Check if the two operands are from the same mul_lohi node.
8443 if (AddcOp0.getNode() == AddcOp1.getNode())
8446 assert(AddcNode->getNumValues() == 2 &&
8447 AddcNode->getValueType(0) == MVT::i32 &&
8448 "Expect ADDC with two result values. First: i32");
8450 // Check that we have a glued ADDC node.
8451 if (AddcNode->getValueType(1) != MVT::Glue)
8454 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8455 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8456 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8457 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8458 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8461 // Look for the glued ADDE.
8462 SDNode* AddeNode = AddcNode->getGluedUser();
8466 // Make sure it is really an ADDE.
8467 if (AddeNode->getOpcode() != ISD::ADDE)
8470 assert(AddeNode->getNumOperands() == 3 &&
8471 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8472 "ADDE node has the wrong inputs");
8474 // Check for the triangle shape.
8475 SDValue AddeOp0 = AddeNode->getOperand(0);
8476 SDValue AddeOp1 = AddeNode->getOperand(1);
8478 // Make sure that the ADDE operands are not coming from the same node.
8479 if (AddeOp0.getNode() == AddeOp1.getNode())
8482 // Find the MUL_LOHI node walking up ADDE's operands.
8483 bool IsLeftOperandMUL = false;
8484 SDValue MULOp = findMUL_LOHI(AddeOp0);
8485 if (MULOp == SDValue())
8486 MULOp = findMUL_LOHI(AddeOp1);
8488 IsLeftOperandMUL = true;
8489 if (MULOp == SDValue())
8492 // Figure out the right opcode.
8493 unsigned Opc = MULOp->getOpcode();
8494 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8496 // Figure out the high and low input values to the MLAL node.
8497 SDValue* HiAdd = nullptr;
8498 SDValue* LoMul = nullptr;
8499 SDValue* LowAdd = nullptr;
8501 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8502 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8505 if (IsLeftOperandMUL)
8511 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8512 // whose low result is fed to the ADDC we are checking.
8514 if (AddcOp0 == MULOp.getValue(0)) {
8518 if (AddcOp1 == MULOp.getValue(0)) {
8526 // Create the merged node.
8527 SelectionDAG &DAG = DCI.DAG;
8529 // Build operand list.
8530 SmallVector<SDValue, 8> Ops;
8531 Ops.push_back(LoMul->getOperand(0));
8532 Ops.push_back(LoMul->getOperand(1));
8533 Ops.push_back(*LowAdd);
8534 Ops.push_back(*HiAdd);
8536 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8537 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8539 // Replace the ADDs' nodes uses by the MLA node's values.
8540 SDValue HiMLALResult(MLALNode.getNode(), 1);
8541 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8543 SDValue LoMLALResult(MLALNode.getNode(), 0);
8544 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8546 // Return original node to notify the driver to stop replacing.
8547 SDValue resNode(AddcNode, 0);
8551 /// PerformADDCCombine - Target-specific dag combine transform from
8552 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8553 static SDValue PerformADDCCombine(SDNode *N,
8554 TargetLowering::DAGCombinerInfo &DCI,
8555 const ARMSubtarget *Subtarget) {
8557 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8561 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8562 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8563 /// called with the default operands, and if that fails, with commuted
8565 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8566 TargetLowering::DAGCombinerInfo &DCI,
8567 const ARMSubtarget *Subtarget){
8569 // Attempt to create vpaddl for this add.
8570 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8571 if (Result.getNode())
8574 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8575 if (N0.getNode()->hasOneUse()) {
8576 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8577 if (Result.getNode()) return Result;
8582 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8584 static SDValue PerformADDCombine(SDNode *N,
8585 TargetLowering::DAGCombinerInfo &DCI,
8586 const ARMSubtarget *Subtarget) {
8587 SDValue N0 = N->getOperand(0);
8588 SDValue N1 = N->getOperand(1);
8590 // First try with the default operand order.
8591 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8592 if (Result.getNode())
8595 // If that didn't work, try again with the operands commuted.
8596 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8599 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8601 static SDValue PerformSUBCombine(SDNode *N,
8602 TargetLowering::DAGCombinerInfo &DCI) {
8603 SDValue N0 = N->getOperand(0);
8604 SDValue N1 = N->getOperand(1);
8606 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8607 if (N1.getNode()->hasOneUse()) {
8608 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8609 if (Result.getNode()) return Result;
8615 /// PerformVMULCombine
8616 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8617 /// special multiplier accumulator forwarding.
8623 // However, for (A + B) * (A + B),
8630 static SDValue PerformVMULCombine(SDNode *N,
8631 TargetLowering::DAGCombinerInfo &DCI,
8632 const ARMSubtarget *Subtarget) {
8633 if (!Subtarget->hasVMLxForwarding())
8636 SelectionDAG &DAG = DCI.DAG;
8637 SDValue N0 = N->getOperand(0);
8638 SDValue N1 = N->getOperand(1);
8639 unsigned Opcode = N0.getOpcode();
8640 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8641 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8642 Opcode = N1.getOpcode();
8643 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8644 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8652 EVT VT = N->getValueType(0);
8654 SDValue N00 = N0->getOperand(0);
8655 SDValue N01 = N0->getOperand(1);
8656 return DAG.getNode(Opcode, DL, VT,
8657 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8658 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8661 static SDValue PerformMULCombine(SDNode *N,
8662 TargetLowering::DAGCombinerInfo &DCI,
8663 const ARMSubtarget *Subtarget) {
8664 SelectionDAG &DAG = DCI.DAG;
8666 if (Subtarget->isThumb1Only())
8669 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8672 EVT VT = N->getValueType(0);
8673 if (VT.is64BitVector() || VT.is128BitVector())
8674 return PerformVMULCombine(N, DCI, Subtarget);
8678 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8682 int64_t MulAmt = C->getSExtValue();
8683 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8685 ShiftAmt = ShiftAmt & (32 - 1);
8686 SDValue V = N->getOperand(0);
8690 MulAmt >>= ShiftAmt;
8693 if (isPowerOf2_32(MulAmt - 1)) {
8694 // (mul x, 2^N + 1) => (add (shl x, N), x)
8695 Res = DAG.getNode(ISD::ADD, DL, VT,
8697 DAG.getNode(ISD::SHL, DL, VT,
8699 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8701 } else if (isPowerOf2_32(MulAmt + 1)) {
8702 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8703 Res = DAG.getNode(ISD::SUB, DL, VT,
8704 DAG.getNode(ISD::SHL, DL, VT,
8706 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8712 uint64_t MulAmtAbs = -MulAmt;
8713 if (isPowerOf2_32(MulAmtAbs + 1)) {
8714 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8715 Res = DAG.getNode(ISD::SUB, DL, VT,
8717 DAG.getNode(ISD::SHL, DL, VT,
8719 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8721 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8722 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8723 Res = DAG.getNode(ISD::ADD, DL, VT,
8725 DAG.getNode(ISD::SHL, DL, VT,
8727 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8729 Res = DAG.getNode(ISD::SUB, DL, VT,
8730 DAG.getConstant(0, DL, MVT::i32), Res);
8737 Res = DAG.getNode(ISD::SHL, DL, VT,
8738 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8740 // Do not add new nodes to DAG combiner worklist.
8741 DCI.CombineTo(N, Res, false);
8745 static SDValue PerformANDCombine(SDNode *N,
8746 TargetLowering::DAGCombinerInfo &DCI,
8747 const ARMSubtarget *Subtarget) {
8749 // Attempt to use immediate-form VBIC
8750 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8752 EVT VT = N->getValueType(0);
8753 SelectionDAG &DAG = DCI.DAG;
8755 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8758 APInt SplatBits, SplatUndef;
8759 unsigned SplatBitSize;
8762 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8763 if (SplatBitSize <= 64) {
8765 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8766 SplatUndef.getZExtValue(), SplatBitSize,
8767 DAG, dl, VbicVT, VT.is128BitVector(),
8769 if (Val.getNode()) {
8771 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8772 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8773 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8778 if (!Subtarget->isThumb1Only()) {
8779 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8780 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8781 if (Result.getNode())
8788 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8789 static SDValue PerformORCombine(SDNode *N,
8790 TargetLowering::DAGCombinerInfo &DCI,
8791 const ARMSubtarget *Subtarget) {
8792 // Attempt to use immediate-form VORR
8793 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8795 EVT VT = N->getValueType(0);
8796 SelectionDAG &DAG = DCI.DAG;
8798 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8801 APInt SplatBits, SplatUndef;
8802 unsigned SplatBitSize;
8804 if (BVN && Subtarget->hasNEON() &&
8805 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8806 if (SplatBitSize <= 64) {
8808 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8809 SplatUndef.getZExtValue(), SplatBitSize,
8810 DAG, dl, VorrVT, VT.is128BitVector(),
8812 if (Val.getNode()) {
8814 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8815 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8816 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8821 if (!Subtarget->isThumb1Only()) {
8822 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8823 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8824 if (Result.getNode())
8828 // The code below optimizes (or (and X, Y), Z).
8829 // The AND operand needs to have a single user to make these optimizations
8831 SDValue N0 = N->getOperand(0);
8832 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8834 SDValue N1 = N->getOperand(1);
8836 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8837 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8838 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8840 unsigned SplatBitSize;
8843 APInt SplatBits0, SplatBits1;
8844 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8845 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8846 // Ensure that the second operand of both ands are constants
8847 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8848 HasAnyUndefs) && !HasAnyUndefs) {
8849 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8850 HasAnyUndefs) && !HasAnyUndefs) {
8851 // Ensure that the bit width of the constants are the same and that
8852 // the splat arguments are logical inverses as per the pattern we
8853 // are trying to simplify.
8854 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8855 SplatBits0 == ~SplatBits1) {
8856 // Canonicalize the vector type to make instruction selection
8858 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8859 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8863 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8869 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8872 // BFI is only available on V6T2+
8873 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8877 // 1) or (and A, mask), val => ARMbfi A, val, mask
8878 // iff (val & mask) == val
8880 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8881 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8882 // && mask == ~mask2
8883 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8884 // && ~mask == mask2
8885 // (i.e., copy a bitfield value into another bitfield of the same width)
8890 SDValue N00 = N0.getOperand(0);
8892 // The value and the mask need to be constants so we can verify this is
8893 // actually a bitfield set. If the mask is 0xffff, we can do better
8894 // via a movt instruction, so don't use BFI in that case.
8895 SDValue MaskOp = N0.getOperand(1);
8896 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8899 unsigned Mask = MaskC->getZExtValue();
8903 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8904 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8906 unsigned Val = N1C->getZExtValue();
8907 if ((Val & ~Mask) != Val)
8910 if (ARM::isBitFieldInvertedMask(Mask)) {
8911 Val >>= countTrailingZeros(~Mask);
8913 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8914 DAG.getConstant(Val, DL, MVT::i32),
8915 DAG.getConstant(Mask, DL, MVT::i32));
8917 // Do not add new nodes to DAG combiner worklist.
8918 DCI.CombineTo(N, Res, false);
8921 } else if (N1.getOpcode() == ISD::AND) {
8922 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8923 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8926 unsigned Mask2 = N11C->getZExtValue();
8928 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8930 if (ARM::isBitFieldInvertedMask(Mask) &&
8932 // The pack halfword instruction works better for masks that fit it,
8933 // so use that when it's available.
8934 if (Subtarget->hasT2ExtractPack() &&
8935 (Mask == 0xffff || Mask == 0xffff0000))
8938 unsigned amt = countTrailingZeros(Mask2);
8939 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8940 DAG.getConstant(amt, DL, MVT::i32));
8941 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8942 DAG.getConstant(Mask, DL, MVT::i32));
8943 // Do not add new nodes to DAG combiner worklist.
8944 DCI.CombineTo(N, Res, false);
8946 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8948 // The pack halfword instruction works better for masks that fit it,
8949 // so use that when it's available.
8950 if (Subtarget->hasT2ExtractPack() &&
8951 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8954 unsigned lsb = countTrailingZeros(Mask);
8955 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8956 DAG.getConstant(lsb, DL, MVT::i32));
8957 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8958 DAG.getConstant(Mask2, DL, MVT::i32));
8959 // Do not add new nodes to DAG combiner worklist.
8960 DCI.CombineTo(N, Res, false);
8965 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8966 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8967 ARM::isBitFieldInvertedMask(~Mask)) {
8968 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8969 // where lsb(mask) == #shamt and masked bits of B are known zero.
8970 SDValue ShAmt = N00.getOperand(1);
8971 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8972 unsigned LSB = countTrailingZeros(Mask);
8976 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8977 DAG.getConstant(~Mask, DL, MVT::i32));
8979 // Do not add new nodes to DAG combiner worklist.
8980 DCI.CombineTo(N, Res, false);
8986 static SDValue PerformXORCombine(SDNode *N,
8987 TargetLowering::DAGCombinerInfo &DCI,
8988 const ARMSubtarget *Subtarget) {
8989 EVT VT = N->getValueType(0);
8990 SelectionDAG &DAG = DCI.DAG;
8992 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8995 if (!Subtarget->isThumb1Only()) {
8996 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8997 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8998 if (Result.getNode())
9005 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9006 /// the bits being cleared by the AND are not demanded by the BFI.
9007 static SDValue PerformBFICombine(SDNode *N,
9008 TargetLowering::DAGCombinerInfo &DCI) {
9009 SDValue N1 = N->getOperand(1);
9010 if (N1.getOpcode() == ISD::AND) {
9011 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9014 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9015 unsigned LSB = countTrailingZeros(~InvMask);
9016 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9018 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9019 "undefined behavior");
9020 unsigned Mask = (1u << Width) - 1;
9021 unsigned Mask2 = N11C->getZExtValue();
9022 if ((Mask & (~Mask2)) == 0)
9023 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9024 N->getOperand(0), N1.getOperand(0),
9030 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9031 /// ARMISD::VMOVRRD.
9032 static SDValue PerformVMOVRRDCombine(SDNode *N,
9033 TargetLowering::DAGCombinerInfo &DCI,
9034 const ARMSubtarget *Subtarget) {
9035 // vmovrrd(vmovdrr x, y) -> x,y
9036 SDValue InDouble = N->getOperand(0);
9037 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9038 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9040 // vmovrrd(load f64) -> (load i32), (load i32)
9041 SDNode *InNode = InDouble.getNode();
9042 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9043 InNode->getValueType(0) == MVT::f64 &&
9044 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9045 !cast<LoadSDNode>(InNode)->isVolatile()) {
9046 // TODO: Should this be done for non-FrameIndex operands?
9047 LoadSDNode *LD = cast<LoadSDNode>(InNode);
9049 SelectionDAG &DAG = DCI.DAG;
9051 SDValue BasePtr = LD->getBasePtr();
9052 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9053 LD->getPointerInfo(), LD->isVolatile(),
9054 LD->isNonTemporal(), LD->isInvariant(),
9055 LD->getAlignment());
9057 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9058 DAG.getConstant(4, DL, MVT::i32));
9059 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9060 LD->getPointerInfo(), LD->isVolatile(),
9061 LD->isNonTemporal(), LD->isInvariant(),
9062 std::min(4U, LD->getAlignment() / 2));
9064 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9065 if (DCI.DAG.getDataLayout().isBigEndian())
9066 std::swap (NewLD1, NewLD2);
9067 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9074 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9075 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
9076 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9077 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9078 SDValue Op0 = N->getOperand(0);
9079 SDValue Op1 = N->getOperand(1);
9080 if (Op0.getOpcode() == ISD::BITCAST)
9081 Op0 = Op0.getOperand(0);
9082 if (Op1.getOpcode() == ISD::BITCAST)
9083 Op1 = Op1.getOperand(0);
9084 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9085 Op0.getNode() == Op1.getNode() &&
9086 Op0.getResNo() == 0 && Op1.getResNo() == 1)
9087 return DAG.getNode(ISD::BITCAST, SDLoc(N),
9088 N->getValueType(0), Op0.getOperand(0));
9092 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9093 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9094 /// i64 vector to have f64 elements, since the value can then be loaded
9095 /// directly into a VFP register.
9096 static bool hasNormalLoadOperand(SDNode *N) {
9097 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9098 for (unsigned i = 0; i < NumElts; ++i) {
9099 SDNode *Elt = N->getOperand(i).getNode();
9100 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9106 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9107 /// ISD::BUILD_VECTOR.
9108 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9109 TargetLowering::DAGCombinerInfo &DCI,
9110 const ARMSubtarget *Subtarget) {
9111 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9112 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9113 // into a pair of GPRs, which is fine when the value is used as a scalar,
9114 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9115 SelectionDAG &DAG = DCI.DAG;
9116 if (N->getNumOperands() == 2) {
9117 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9122 // Load i64 elements as f64 values so that type legalization does not split
9123 // them up into i32 values.
9124 EVT VT = N->getValueType(0);
9125 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9128 SmallVector<SDValue, 8> Ops;
9129 unsigned NumElts = VT.getVectorNumElements();
9130 for (unsigned i = 0; i < NumElts; ++i) {
9131 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9133 // Make the DAGCombiner fold the bitcast.
9134 DCI.AddToWorklist(V.getNode());
9136 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9137 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9138 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9141 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9143 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9144 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9145 // At that time, we may have inserted bitcasts from integer to float.
9146 // If these bitcasts have survived DAGCombine, change the lowering of this
9147 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9148 // force to use floating point types.
9150 // Make sure we can change the type of the vector.
9151 // This is possible iff:
9152 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9153 // 1.1. Vector is used only once.
9154 // 1.2. Use is a bit convert to an integer type.
9155 // 2. The size of its operands are 32-bits (64-bits are not legal).
9156 EVT VT = N->getValueType(0);
9157 EVT EltVT = VT.getVectorElementType();
9159 // Check 1.1. and 2.
9160 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9163 // By construction, the input type must be float.
9164 assert(EltVT == MVT::f32 && "Unexpected type!");
9167 SDNode *Use = *N->use_begin();
9168 if (Use->getOpcode() != ISD::BITCAST ||
9169 Use->getValueType(0).isFloatingPoint())
9172 // Check profitability.
9173 // Model is, if more than half of the relevant operands are bitcast from
9174 // i32, turn the build_vector into a sequence of insert_vector_elt.
9175 // Relevant operands are everything that is not statically
9176 // (i.e., at compile time) bitcasted.
9177 unsigned NumOfBitCastedElts = 0;
9178 unsigned NumElts = VT.getVectorNumElements();
9179 unsigned NumOfRelevantElts = NumElts;
9180 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9181 SDValue Elt = N->getOperand(Idx);
9182 if (Elt->getOpcode() == ISD::BITCAST) {
9183 // Assume only bit cast to i32 will go away.
9184 if (Elt->getOperand(0).getValueType() == MVT::i32)
9185 ++NumOfBitCastedElts;
9186 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9187 // Constants are statically casted, thus do not count them as
9188 // relevant operands.
9189 --NumOfRelevantElts;
9192 // Check if more than half of the elements require a non-free bitcast.
9193 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9196 SelectionDAG &DAG = DCI.DAG;
9197 // Create the new vector type.
9198 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9199 // Check if the type is legal.
9200 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9201 if (!TLI.isTypeLegal(VecVT))
9205 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9206 // => BITCAST INSERT_VECTOR_ELT
9207 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9209 SDValue Vec = DAG.getUNDEF(VecVT);
9211 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9212 SDValue V = N->getOperand(Idx);
9213 if (V.getOpcode() == ISD::UNDEF)
9215 if (V.getOpcode() == ISD::BITCAST &&
9216 V->getOperand(0).getValueType() == MVT::i32)
9217 // Fold obvious case.
9218 V = V.getOperand(0);
9220 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9221 // Make the DAGCombiner fold the bitcasts.
9222 DCI.AddToWorklist(V.getNode());
9224 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9225 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9227 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9228 // Make the DAGCombiner fold the bitcasts.
9229 DCI.AddToWorklist(Vec.getNode());
9233 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9234 /// ISD::INSERT_VECTOR_ELT.
9235 static SDValue PerformInsertEltCombine(SDNode *N,
9236 TargetLowering::DAGCombinerInfo &DCI) {
9237 // Bitcast an i64 load inserted into a vector to f64.
9238 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9239 EVT VT = N->getValueType(0);
9240 SDNode *Elt = N->getOperand(1).getNode();
9241 if (VT.getVectorElementType() != MVT::i64 ||
9242 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9245 SelectionDAG &DAG = DCI.DAG;
9247 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9248 VT.getVectorNumElements());
9249 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9250 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9251 // Make the DAGCombiner fold the bitcasts.
9252 DCI.AddToWorklist(Vec.getNode());
9253 DCI.AddToWorklist(V.getNode());
9254 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9255 Vec, V, N->getOperand(2));
9256 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9259 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9260 /// ISD::VECTOR_SHUFFLE.
9261 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9262 // The LLVM shufflevector instruction does not require the shuffle mask
9263 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9264 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9265 // operands do not match the mask length, they are extended by concatenating
9266 // them with undef vectors. That is probably the right thing for other
9267 // targets, but for NEON it is better to concatenate two double-register
9268 // size vector operands into a single quad-register size vector. Do that
9269 // transformation here:
9270 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9271 // shuffle(concat(v1, v2), undef)
9272 SDValue Op0 = N->getOperand(0);
9273 SDValue Op1 = N->getOperand(1);
9274 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9275 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9276 Op0.getNumOperands() != 2 ||
9277 Op1.getNumOperands() != 2)
9279 SDValue Concat0Op1 = Op0.getOperand(1);
9280 SDValue Concat1Op1 = Op1.getOperand(1);
9281 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9282 Concat1Op1.getOpcode() != ISD::UNDEF)
9284 // Skip the transformation if any of the types are illegal.
9285 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9286 EVT VT = N->getValueType(0);
9287 if (!TLI.isTypeLegal(VT) ||
9288 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9289 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9292 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9293 Op0.getOperand(0), Op1.getOperand(0));
9294 // Translate the shuffle mask.
9295 SmallVector<int, 16> NewMask;
9296 unsigned NumElts = VT.getVectorNumElements();
9297 unsigned HalfElts = NumElts/2;
9298 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9299 for (unsigned n = 0; n < NumElts; ++n) {
9300 int MaskElt = SVN->getMaskElt(n);
9302 if (MaskElt < (int)HalfElts)
9304 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9305 NewElt = HalfElts + MaskElt - NumElts;
9306 NewMask.push_back(NewElt);
9308 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9309 DAG.getUNDEF(VT), NewMask.data());
9312 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9313 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9314 /// base address updates.
9315 /// For generic load/stores, the memory type is assumed to be a vector.
9316 /// The caller is assumed to have checked legality.
9317 static SDValue CombineBaseUpdate(SDNode *N,
9318 TargetLowering::DAGCombinerInfo &DCI) {
9319 SelectionDAG &DAG = DCI.DAG;
9320 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9321 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9322 const bool isStore = N->getOpcode() == ISD::STORE;
9323 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9324 SDValue Addr = N->getOperand(AddrOpIdx);
9325 MemSDNode *MemN = cast<MemSDNode>(N);
9328 // Search for a use of the address operand that is an increment.
9329 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9330 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9332 if (User->getOpcode() != ISD::ADD ||
9333 UI.getUse().getResNo() != Addr.getResNo())
9336 // Check that the add is independent of the load/store. Otherwise, folding
9337 // it would create a cycle.
9338 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9341 // Find the new opcode for the updating load/store.
9342 bool isLoadOp = true;
9343 bool isLaneOp = false;
9344 unsigned NewOpc = 0;
9345 unsigned NumVecs = 0;
9347 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9349 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9350 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9352 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9354 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9356 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9358 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9359 NumVecs = 2; isLaneOp = true; break;
9360 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9361 NumVecs = 3; isLaneOp = true; break;
9362 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9363 NumVecs = 4; isLaneOp = true; break;
9364 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9365 NumVecs = 1; isLoadOp = false; break;
9366 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9367 NumVecs = 2; isLoadOp = false; break;
9368 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9369 NumVecs = 3; isLoadOp = false; break;
9370 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9371 NumVecs = 4; isLoadOp = false; break;
9372 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9373 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9374 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9375 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9376 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9377 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9381 switch (N->getOpcode()) {
9382 default: llvm_unreachable("unexpected opcode for Neon base update");
9383 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9384 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9385 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9386 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9387 NumVecs = 1; isLaneOp = false; break;
9388 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9389 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9393 // Find the size of memory referenced by the load/store.
9396 VecTy = N->getValueType(0);
9397 } else if (isIntrinsic) {
9398 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9400 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9401 VecTy = N->getOperand(1).getValueType();
9404 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9406 NumBytes /= VecTy.getVectorNumElements();
9408 // If the increment is a constant, it must match the memory ref size.
9409 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9410 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9411 uint64_t IncVal = CInc->getZExtValue();
9412 if (IncVal != NumBytes)
9414 } else if (NumBytes >= 3 * 16) {
9415 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9416 // separate instructions that make it harder to use a non-constant update.
9420 // OK, we found an ADD we can fold into the base update.
9421 // Now, create a _UPD node, taking care of not breaking alignment.
9423 EVT AlignedVecTy = VecTy;
9424 unsigned Alignment = MemN->getAlignment();
9426 // If this is a less-than-standard-aligned load/store, change the type to
9427 // match the standard alignment.
9428 // The alignment is overlooked when selecting _UPD variants; and it's
9429 // easier to introduce bitcasts here than fix that.
9430 // There are 3 ways to get to this base-update combine:
9431 // - intrinsics: they are assumed to be properly aligned (to the standard
9432 // alignment of the memory type), so we don't need to do anything.
9433 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9434 // intrinsics, so, likewise, there's nothing to do.
9435 // - generic load/store instructions: the alignment is specified as an
9436 // explicit operand, rather than implicitly as the standard alignment
9437 // of the memory type (like the intrisics). We need to change the
9438 // memory type to match the explicit alignment. That way, we don't
9439 // generate non-standard-aligned ARMISD::VLDx nodes.
9440 if (isa<LSBaseSDNode>(N)) {
9443 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9444 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9445 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9446 assert(!isLaneOp && "Unexpected generic load/store lane.");
9447 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9448 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9450 // Don't set an explicit alignment on regular load/stores that we want
9451 // to transform to VLD/VST 1_UPD nodes.
9452 // This matches the behavior of regular load/stores, which only get an
9453 // explicit alignment if the MMO alignment is larger than the standard
9454 // alignment of the memory type.
9455 // Intrinsics, however, always get an explicit alignment, set to the
9456 // alignment of the MMO.
9460 // Create the new updating load/store node.
9461 // First, create an SDVTList for the new updating node's results.
9463 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9465 for (n = 0; n < NumResultVecs; ++n)
9466 Tys[n] = AlignedVecTy;
9467 Tys[n++] = MVT::i32;
9468 Tys[n] = MVT::Other;
9469 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9471 // Then, gather the new node's operands.
9472 SmallVector<SDValue, 8> Ops;
9473 Ops.push_back(N->getOperand(0)); // incoming chain
9474 Ops.push_back(N->getOperand(AddrOpIdx));
9477 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9478 // Try to match the intrinsic's signature
9479 Ops.push_back(StN->getValue());
9481 // Loads (and of course intrinsics) match the intrinsics' signature,
9482 // so just add all but the alignment operand.
9483 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9484 Ops.push_back(N->getOperand(i));
9487 // For all node types, the alignment operand is always the last one.
9488 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9490 // If this is a non-standard-aligned STORE, the penultimate operand is the
9491 // stored value. Bitcast it to the aligned type.
9492 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9493 SDValue &StVal = Ops[Ops.size()-2];
9494 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9497 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9499 MemN->getMemOperand());
9502 SmallVector<SDValue, 5> NewResults;
9503 for (unsigned i = 0; i < NumResultVecs; ++i)
9504 NewResults.push_back(SDValue(UpdN.getNode(), i));
9506 // If this is an non-standard-aligned LOAD, the first result is the loaded
9507 // value. Bitcast it to the expected result type.
9508 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9509 SDValue &LdVal = NewResults[0];
9510 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9513 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9514 DCI.CombineTo(N, NewResults);
9515 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9522 static SDValue PerformVLDCombine(SDNode *N,
9523 TargetLowering::DAGCombinerInfo &DCI) {
9524 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9527 return CombineBaseUpdate(N, DCI);
9530 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9531 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9532 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9534 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9535 SelectionDAG &DAG = DCI.DAG;
9536 EVT VT = N->getValueType(0);
9537 // vldN-dup instructions only support 64-bit vectors for N > 1.
9538 if (!VT.is64BitVector())
9541 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9542 SDNode *VLD = N->getOperand(0).getNode();
9543 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9545 unsigned NumVecs = 0;
9546 unsigned NewOpc = 0;
9547 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9548 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9550 NewOpc = ARMISD::VLD2DUP;
9551 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9553 NewOpc = ARMISD::VLD3DUP;
9554 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9556 NewOpc = ARMISD::VLD4DUP;
9561 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9562 // numbers match the load.
9563 unsigned VLDLaneNo =
9564 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9565 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9567 // Ignore uses of the chain result.
9568 if (UI.getUse().getResNo() == NumVecs)
9571 if (User->getOpcode() != ARMISD::VDUPLANE ||
9572 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9576 // Create the vldN-dup node.
9579 for (n = 0; n < NumVecs; ++n)
9581 Tys[n] = MVT::Other;
9582 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9583 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9584 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9585 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9586 Ops, VLDMemInt->getMemoryVT(),
9587 VLDMemInt->getMemOperand());
9590 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9592 unsigned ResNo = UI.getUse().getResNo();
9593 // Ignore uses of the chain result.
9594 if (ResNo == NumVecs)
9597 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9600 // Now the vldN-lane intrinsic is dead except for its chain result.
9601 // Update uses of the chain.
9602 std::vector<SDValue> VLDDupResults;
9603 for (unsigned n = 0; n < NumVecs; ++n)
9604 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9605 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9606 DCI.CombineTo(VLD, VLDDupResults);
9611 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9612 /// ARMISD::VDUPLANE.
9613 static SDValue PerformVDUPLANECombine(SDNode *N,
9614 TargetLowering::DAGCombinerInfo &DCI) {
9615 SDValue Op = N->getOperand(0);
9617 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9618 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9619 if (CombineVLDDUP(N, DCI))
9620 return SDValue(N, 0);
9622 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9623 // redundant. Ignore bit_converts for now; element sizes are checked below.
9624 while (Op.getOpcode() == ISD::BITCAST)
9625 Op = Op.getOperand(0);
9626 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9629 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9630 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9631 // The canonical VMOV for a zero vector uses a 32-bit element size.
9632 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9634 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9636 EVT VT = N->getValueType(0);
9637 if (EltSize > VT.getVectorElementType().getSizeInBits())
9640 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9643 static SDValue PerformLOADCombine(SDNode *N,
9644 TargetLowering::DAGCombinerInfo &DCI) {
9645 EVT VT = N->getValueType(0);
9647 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9648 if (ISD::isNormalLoad(N) && VT.isVector() &&
9649 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9650 return CombineBaseUpdate(N, DCI);
9655 /// PerformSTORECombine - Target-specific dag combine xforms for
9657 static SDValue PerformSTORECombine(SDNode *N,
9658 TargetLowering::DAGCombinerInfo &DCI) {
9659 StoreSDNode *St = cast<StoreSDNode>(N);
9660 if (St->isVolatile())
9663 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9664 // pack all of the elements in one place. Next, store to memory in fewer
9666 SDValue StVal = St->getValue();
9667 EVT VT = StVal.getValueType();
9668 if (St->isTruncatingStore() && VT.isVector()) {
9669 SelectionDAG &DAG = DCI.DAG;
9670 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9671 EVT StVT = St->getMemoryVT();
9672 unsigned NumElems = VT.getVectorNumElements();
9673 assert(StVT != VT && "Cannot truncate to the same type");
9674 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9675 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9677 // From, To sizes and ElemCount must be pow of two
9678 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9680 // We are going to use the original vector elt for storing.
9681 // Accumulated smaller vector elements must be a multiple of the store size.
9682 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9684 unsigned SizeRatio = FromEltSz / ToEltSz;
9685 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9687 // Create a type on which we perform the shuffle.
9688 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9689 NumElems*SizeRatio);
9690 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9693 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9694 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9695 for (unsigned i = 0; i < NumElems; ++i)
9696 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9697 ? (i + 1) * SizeRatio - 1
9700 // Can't shuffle using an illegal type.
9701 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9703 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9704 DAG.getUNDEF(WideVec.getValueType()),
9706 // At this point all of the data is stored at the bottom of the
9707 // register. We now need to save it to mem.
9709 // Find the largest store unit
9710 MVT StoreType = MVT::i8;
9711 for (MVT Tp : MVT::integer_valuetypes()) {
9712 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9715 // Didn't find a legal store type.
9716 if (!TLI.isTypeLegal(StoreType))
9719 // Bitcast the original vector into a vector of store-size units
9720 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9721 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9722 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9723 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9724 SmallVector<SDValue, 8> Chains;
9725 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9726 TLI.getPointerTy(DAG.getDataLayout()));
9727 SDValue BasePtr = St->getBasePtr();
9729 // Perform one or more big stores into memory.
9730 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9731 for (unsigned I = 0; I < E; I++) {
9732 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9733 StoreType, ShuffWide,
9734 DAG.getIntPtrConstant(I, DL));
9735 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9736 St->getPointerInfo(), St->isVolatile(),
9737 St->isNonTemporal(), St->getAlignment());
9738 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9740 Chains.push_back(Ch);
9742 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9745 if (!ISD::isNormalStore(St))
9748 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9749 // ARM stores of arguments in the same cache line.
9750 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9751 StVal.getNode()->hasOneUse()) {
9752 SelectionDAG &DAG = DCI.DAG;
9753 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9755 SDValue BasePtr = St->getBasePtr();
9756 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9757 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9758 BasePtr, St->getPointerInfo(), St->isVolatile(),
9759 St->isNonTemporal(), St->getAlignment());
9761 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9762 DAG.getConstant(4, DL, MVT::i32));
9763 return DAG.getStore(NewST1.getValue(0), DL,
9764 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9765 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9766 St->isNonTemporal(),
9767 std::min(4U, St->getAlignment() / 2));
9770 if (StVal.getValueType() == MVT::i64 &&
9771 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9773 // Bitcast an i64 store extracted from a vector to f64.
9774 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9775 SelectionDAG &DAG = DCI.DAG;
9777 SDValue IntVec = StVal.getOperand(0);
9778 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9779 IntVec.getValueType().getVectorNumElements());
9780 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9781 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9782 Vec, StVal.getOperand(1));
9784 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9785 // Make the DAGCombiner fold the bitcasts.
9786 DCI.AddToWorklist(Vec.getNode());
9787 DCI.AddToWorklist(ExtElt.getNode());
9788 DCI.AddToWorklist(V.getNode());
9789 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9790 St->getPointerInfo(), St->isVolatile(),
9791 St->isNonTemporal(), St->getAlignment(),
9795 // If this is a legal vector store, try to combine it into a VST1_UPD.
9796 if (ISD::isNormalStore(N) && VT.isVector() &&
9797 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9798 return CombineBaseUpdate(N, DCI);
9803 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9804 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9805 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9809 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9811 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9816 APFloat APF = C->getValueAPF();
9817 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9818 != APFloat::opOK || !isExact)
9821 c0 = (I == 0) ? cN : c0;
9822 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9829 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9830 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9831 /// when the VMUL has a constant operand that is a power of 2.
9833 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9834 /// vmul.f32 d16, d17, d16
9835 /// vcvt.s32.f32 d16, d16
9837 /// vcvt.s32.f32 d16, d16, #3
9838 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
9839 const ARMSubtarget *Subtarget) {
9840 if (!Subtarget->hasNEON())
9843 SDValue Op = N->getOperand(0);
9844 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
9848 SDValue N0 = Op->getOperand(0);
9849 SDValue ConstVec = Op->getOperand(1);
9850 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9852 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9853 !isConstVecPow2(ConstVec, isSigned, C))
9856 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9857 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9858 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9859 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9861 // These instructions only exist converting from f32 to i32. We can handle
9862 // smaller integers by generating an extra truncate, but larger ones would
9863 // be lossy. We also can't handle more then 4 lanes, since these intructions
9864 // only support v2i32/v4i32 types.
9869 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9870 Intrinsic::arm_neon_vcvtfp2fxu;
9871 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9872 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9873 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9875 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9877 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9878 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9883 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9884 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9885 /// when the VDIV has a constant operand that is a power of 2.
9887 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9888 /// vcvt.f32.s32 d16, d16
9889 /// vdiv.f32 d16, d17, d16
9891 /// vcvt.f32.s32 d16, d16, #3
9892 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
9893 const ARMSubtarget *Subtarget) {
9894 if (!Subtarget->hasNEON())
9897 SDValue Op = N->getOperand(0);
9898 unsigned OpOpcode = Op.getNode()->getOpcode();
9899 if (!N->getValueType(0).isVector() ||
9900 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9904 SDValue ConstVec = N->getOperand(1);
9905 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9907 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9908 !isConstVecPow2(ConstVec, isSigned, C))
9911 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9912 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9913 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9914 // These instructions only exist converting from i32 to f32. We can handle
9915 // smaller integers by generating an extra extend, but larger ones would
9921 SDValue ConvInput = Op.getOperand(0);
9922 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9923 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9924 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9925 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9928 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9929 Intrinsic::arm_neon_vcvtfxu2fp;
9930 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9932 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9933 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9936 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9937 /// operand of a vector shift operation, where all the elements of the
9938 /// build_vector must have the same constant integer value.
9939 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9940 // Ignore bit_converts.
9941 while (Op.getOpcode() == ISD::BITCAST)
9942 Op = Op.getOperand(0);
9943 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9944 APInt SplatBits, SplatUndef;
9945 unsigned SplatBitSize;
9947 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9948 HasAnyUndefs, ElementBits) ||
9949 SplatBitSize > ElementBits)
9951 Cnt = SplatBits.getSExtValue();
9955 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9956 /// operand of a vector shift left operation. That value must be in the range:
9957 /// 0 <= Value < ElementBits for a left shift; or
9958 /// 0 <= Value <= ElementBits for a long left shift.
9959 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9960 assert(VT.isVector() && "vector shift count is not a vector type");
9961 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9962 if (! getVShiftImm(Op, ElementBits, Cnt))
9964 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9967 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9968 /// operand of a vector shift right operation. For a shift opcode, the value
9969 /// is positive, but for an intrinsic the value count must be negative. The
9970 /// absolute value must be in the range:
9971 /// 1 <= |Value| <= ElementBits for a right shift; or
9972 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9973 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9975 assert(VT.isVector() && "vector shift count is not a vector type");
9976 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9977 if (! getVShiftImm(Op, ElementBits, Cnt))
9980 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9981 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9988 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9989 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9990 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9993 // Don't do anything for most intrinsics.
9996 case Intrinsic::arm_neon_vabds:
9997 if (!N->getValueType(0).isInteger())
9999 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
10000 N->getOperand(1), N->getOperand(2));
10001 case Intrinsic::arm_neon_vabdu:
10002 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
10003 N->getOperand(1), N->getOperand(2));
10005 // Vector shifts: check for immediate versions and lower them.
10006 // Note: This is done during DAG combining instead of DAG legalizing because
10007 // the build_vectors for 64-bit vector element shift counts are generally
10008 // not legal, and it is hard to see their values after they get legalized to
10009 // loads from a constant pool.
10010 case Intrinsic::arm_neon_vshifts:
10011 case Intrinsic::arm_neon_vshiftu:
10012 case Intrinsic::arm_neon_vrshifts:
10013 case Intrinsic::arm_neon_vrshiftu:
10014 case Intrinsic::arm_neon_vrshiftn:
10015 case Intrinsic::arm_neon_vqshifts:
10016 case Intrinsic::arm_neon_vqshiftu:
10017 case Intrinsic::arm_neon_vqshiftsu:
10018 case Intrinsic::arm_neon_vqshiftns:
10019 case Intrinsic::arm_neon_vqshiftnu:
10020 case Intrinsic::arm_neon_vqshiftnsu:
10021 case Intrinsic::arm_neon_vqrshiftns:
10022 case Intrinsic::arm_neon_vqrshiftnu:
10023 case Intrinsic::arm_neon_vqrshiftnsu: {
10024 EVT VT = N->getOperand(1).getValueType();
10026 unsigned VShiftOpc = 0;
10029 case Intrinsic::arm_neon_vshifts:
10030 case Intrinsic::arm_neon_vshiftu:
10031 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10032 VShiftOpc = ARMISD::VSHL;
10035 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10036 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10037 ARMISD::VSHRs : ARMISD::VSHRu);
10042 case Intrinsic::arm_neon_vrshifts:
10043 case Intrinsic::arm_neon_vrshiftu:
10044 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10048 case Intrinsic::arm_neon_vqshifts:
10049 case Intrinsic::arm_neon_vqshiftu:
10050 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10054 case Intrinsic::arm_neon_vqshiftsu:
10055 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10057 llvm_unreachable("invalid shift count for vqshlu intrinsic");
10059 case Intrinsic::arm_neon_vrshiftn:
10060 case Intrinsic::arm_neon_vqshiftns:
10061 case Intrinsic::arm_neon_vqshiftnu:
10062 case Intrinsic::arm_neon_vqshiftnsu:
10063 case Intrinsic::arm_neon_vqrshiftns:
10064 case Intrinsic::arm_neon_vqrshiftnu:
10065 case Intrinsic::arm_neon_vqrshiftnsu:
10066 // Narrowing shifts require an immediate right shift.
10067 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10069 llvm_unreachable("invalid shift count for narrowing vector shift "
10073 llvm_unreachable("unhandled vector shift");
10077 case Intrinsic::arm_neon_vshifts:
10078 case Intrinsic::arm_neon_vshiftu:
10079 // Opcode already set above.
10081 case Intrinsic::arm_neon_vrshifts:
10082 VShiftOpc = ARMISD::VRSHRs; break;
10083 case Intrinsic::arm_neon_vrshiftu:
10084 VShiftOpc = ARMISD::VRSHRu; break;
10085 case Intrinsic::arm_neon_vrshiftn:
10086 VShiftOpc = ARMISD::VRSHRN; break;
10087 case Intrinsic::arm_neon_vqshifts:
10088 VShiftOpc = ARMISD::VQSHLs; break;
10089 case Intrinsic::arm_neon_vqshiftu:
10090 VShiftOpc = ARMISD::VQSHLu; break;
10091 case Intrinsic::arm_neon_vqshiftsu:
10092 VShiftOpc = ARMISD::VQSHLsu; break;
10093 case Intrinsic::arm_neon_vqshiftns:
10094 VShiftOpc = ARMISD::VQSHRNs; break;
10095 case Intrinsic::arm_neon_vqshiftnu:
10096 VShiftOpc = ARMISD::VQSHRNu; break;
10097 case Intrinsic::arm_neon_vqshiftnsu:
10098 VShiftOpc = ARMISD::VQSHRNsu; break;
10099 case Intrinsic::arm_neon_vqrshiftns:
10100 VShiftOpc = ARMISD::VQRSHRNs; break;
10101 case Intrinsic::arm_neon_vqrshiftnu:
10102 VShiftOpc = ARMISD::VQRSHRNu; break;
10103 case Intrinsic::arm_neon_vqrshiftnsu:
10104 VShiftOpc = ARMISD::VQRSHRNsu; break;
10108 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10109 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10112 case Intrinsic::arm_neon_vshiftins: {
10113 EVT VT = N->getOperand(1).getValueType();
10115 unsigned VShiftOpc = 0;
10117 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10118 VShiftOpc = ARMISD::VSLI;
10119 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10120 VShiftOpc = ARMISD::VSRI;
10122 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10126 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10127 N->getOperand(1), N->getOperand(2),
10128 DAG.getConstant(Cnt, dl, MVT::i32));
10131 case Intrinsic::arm_neon_vqrshifts:
10132 case Intrinsic::arm_neon_vqrshiftu:
10133 // No immediate versions of these to check for.
10140 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10141 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10142 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10143 /// vector element shift counts are generally not legal, and it is hard to see
10144 /// their values after they get legalized to loads from a constant pool.
10145 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10146 const ARMSubtarget *ST) {
10147 EVT VT = N->getValueType(0);
10148 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10149 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10150 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10151 SDValue N1 = N->getOperand(1);
10152 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10153 SDValue N0 = N->getOperand(0);
10154 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10155 DAG.MaskedValueIsZero(N0.getOperand(0),
10156 APInt::getHighBitsSet(32, 16)))
10157 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10161 // Nothing to be done for scalar shifts.
10162 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10163 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10166 assert(ST->hasNEON() && "unexpected vector shift");
10169 switch (N->getOpcode()) {
10170 default: llvm_unreachable("unexpected shift opcode");
10173 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10175 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10176 DAG.getConstant(Cnt, dl, MVT::i32));
10182 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10183 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10184 ARMISD::VSHRs : ARMISD::VSHRu);
10186 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10187 DAG.getConstant(Cnt, dl, MVT::i32));
10193 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10194 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10195 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10196 const ARMSubtarget *ST) {
10197 SDValue N0 = N->getOperand(0);
10199 // Check for sign- and zero-extensions of vector extract operations of 8-
10200 // and 16-bit vector elements. NEON supports these directly. They are
10201 // handled during DAG combining because type legalization will promote them
10202 // to 32-bit types and it is messy to recognize the operations after that.
10203 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10204 SDValue Vec = N0.getOperand(0);
10205 SDValue Lane = N0.getOperand(1);
10206 EVT VT = N->getValueType(0);
10207 EVT EltVT = N0.getValueType();
10208 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10210 if (VT == MVT::i32 &&
10211 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10212 TLI.isTypeLegal(Vec.getValueType()) &&
10213 isa<ConstantSDNode>(Lane)) {
10216 switch (N->getOpcode()) {
10217 default: llvm_unreachable("unexpected opcode");
10218 case ISD::SIGN_EXTEND:
10219 Opc = ARMISD::VGETLANEs;
10221 case ISD::ZERO_EXTEND:
10222 case ISD::ANY_EXTEND:
10223 Opc = ARMISD::VGETLANEu;
10226 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10233 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10235 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10236 SDValue Cmp = N->getOperand(4);
10237 if (Cmp.getOpcode() != ARMISD::CMPZ)
10238 // Only looking at EQ and NE cases.
10241 EVT VT = N->getValueType(0);
10243 SDValue LHS = Cmp.getOperand(0);
10244 SDValue RHS = Cmp.getOperand(1);
10245 SDValue FalseVal = N->getOperand(0);
10246 SDValue TrueVal = N->getOperand(1);
10247 SDValue ARMcc = N->getOperand(2);
10248 ARMCC::CondCodes CC =
10249 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10267 /// FIXME: Turn this into a target neutral optimization?
10269 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10270 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10271 N->getOperand(3), Cmp);
10272 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10274 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10275 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10276 N->getOperand(3), NewCmp);
10279 if (Res.getNode()) {
10280 APInt KnownZero, KnownOne;
10281 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10282 // Capture demanded bits information that would be otherwise lost.
10283 if (KnownZero == 0xfffffffe)
10284 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10285 DAG.getValueType(MVT::i1));
10286 else if (KnownZero == 0xffffff00)
10287 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10288 DAG.getValueType(MVT::i8));
10289 else if (KnownZero == 0xffff0000)
10290 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10291 DAG.getValueType(MVT::i16));
10297 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10298 DAGCombinerInfo &DCI) const {
10299 switch (N->getOpcode()) {
10301 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10302 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10303 case ISD::SUB: return PerformSUBCombine(N, DCI);
10304 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10305 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10306 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10307 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10308 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10309 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10310 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10311 case ISD::STORE: return PerformSTORECombine(N, DCI);
10312 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10313 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10314 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10315 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10316 case ISD::FP_TO_SINT:
10317 case ISD::FP_TO_UINT:
10318 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10320 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10321 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10324 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10325 case ISD::SIGN_EXTEND:
10326 case ISD::ZERO_EXTEND:
10327 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10328 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10329 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10330 case ARMISD::VLD2DUP:
10331 case ARMISD::VLD3DUP:
10332 case ARMISD::VLD4DUP:
10333 return PerformVLDCombine(N, DCI);
10334 case ARMISD::BUILD_VECTOR:
10335 return PerformARMBUILD_VECTORCombine(N, DCI);
10336 case ISD::INTRINSIC_VOID:
10337 case ISD::INTRINSIC_W_CHAIN:
10338 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10339 case Intrinsic::arm_neon_vld1:
10340 case Intrinsic::arm_neon_vld2:
10341 case Intrinsic::arm_neon_vld3:
10342 case Intrinsic::arm_neon_vld4:
10343 case Intrinsic::arm_neon_vld2lane:
10344 case Intrinsic::arm_neon_vld3lane:
10345 case Intrinsic::arm_neon_vld4lane:
10346 case Intrinsic::arm_neon_vst1:
10347 case Intrinsic::arm_neon_vst2:
10348 case Intrinsic::arm_neon_vst3:
10349 case Intrinsic::arm_neon_vst4:
10350 case Intrinsic::arm_neon_vst2lane:
10351 case Intrinsic::arm_neon_vst3lane:
10352 case Intrinsic::arm_neon_vst4lane:
10353 return PerformVLDCombine(N, DCI);
10361 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10363 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10366 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10369 bool *Fast) const {
10370 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10371 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10373 switch (VT.getSimpleVT().SimpleTy) {
10379 // Unaligned access can use (for example) LRDB, LRDH, LDR
10380 if (AllowsUnaligned) {
10382 *Fast = Subtarget->hasV7Ops();
10389 // For any little-endian targets with neon, we can support unaligned ld/st
10390 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10391 // A big-endian target may also explicitly support unaligned accesses
10392 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10402 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10403 unsigned AlignCheck) {
10404 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10405 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10408 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10409 unsigned DstAlign, unsigned SrcAlign,
10410 bool IsMemset, bool ZeroMemset,
10412 MachineFunction &MF) const {
10413 const Function *F = MF.getFunction();
10415 // See if we can use NEON instructions for this...
10416 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10417 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10420 (memOpAlign(SrcAlign, DstAlign, 16) ||
10421 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10423 } else if (Size >= 8 &&
10424 (memOpAlign(SrcAlign, DstAlign, 8) ||
10425 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10431 // Lowering to i32/i16 if the size permits.
10434 else if (Size >= 2)
10437 // Let the target-independent logic figure it out.
10441 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10442 if (Val.getOpcode() != ISD::LOAD)
10445 EVT VT1 = Val.getValueType();
10446 if (!VT1.isSimple() || !VT1.isInteger() ||
10447 !VT2.isSimple() || !VT2.isInteger())
10450 switch (VT1.getSimpleVT().SimpleTy) {
10455 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10462 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10463 EVT VT = ExtVal.getValueType();
10465 if (!isTypeLegal(VT))
10468 // Don't create a loadext if we can fold the extension into a wide/long
10470 // If there's more than one user instruction, the loadext is desirable no
10471 // matter what. There can be two uses by the same instruction.
10472 if (ExtVal->use_empty() ||
10473 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10476 SDNode *U = *ExtVal->use_begin();
10477 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10478 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10484 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10485 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10488 if (!isTypeLegal(EVT::getEVT(Ty1)))
10491 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10493 // Assuming the caller doesn't have a zeroext or signext return parameter,
10494 // truncation all the way down to i1 is valid.
10499 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10503 unsigned Scale = 1;
10504 switch (VT.getSimpleVT().SimpleTy) {
10505 default: return false;
10520 if ((V & (Scale - 1)) != 0)
10523 return V == (V & ((1LL << 5) - 1));
10526 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10527 const ARMSubtarget *Subtarget) {
10528 bool isNeg = false;
10534 switch (VT.getSimpleVT().SimpleTy) {
10535 default: return false;
10540 // + imm12 or - imm8
10542 return V == (V & ((1LL << 8) - 1));
10543 return V == (V & ((1LL << 12) - 1));
10546 // Same as ARM mode. FIXME: NEON?
10547 if (!Subtarget->hasVFP2())
10552 return V == (V & ((1LL << 8) - 1));
10556 /// isLegalAddressImmediate - Return true if the integer value can be used
10557 /// as the offset of the target addressing mode for load / store of the
10559 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10560 const ARMSubtarget *Subtarget) {
10564 if (!VT.isSimple())
10567 if (Subtarget->isThumb1Only())
10568 return isLegalT1AddressImmediate(V, VT);
10569 else if (Subtarget->isThumb2())
10570 return isLegalT2AddressImmediate(V, VT, Subtarget);
10575 switch (VT.getSimpleVT().SimpleTy) {
10576 default: return false;
10581 return V == (V & ((1LL << 12) - 1));
10584 return V == (V & ((1LL << 8) - 1));
10587 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10592 return V == (V & ((1LL << 8) - 1));
10596 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10598 int Scale = AM.Scale;
10602 switch (VT.getSimpleVT().SimpleTy) {
10603 default: return false;
10611 Scale = Scale & ~1;
10612 return Scale == 2 || Scale == 4 || Scale == 8;
10615 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10619 // Note, we allow "void" uses (basically, uses that aren't loads or
10620 // stores), because arm allows folding a scale into many arithmetic
10621 // operations. This should be made more precise and revisited later.
10623 // Allow r << imm, but the imm has to be a multiple of two.
10624 if (Scale & 1) return false;
10625 return isPowerOf2_32(Scale);
10629 /// isLegalAddressingMode - Return true if the addressing mode represented
10630 /// by AM is legal for this target, for a load/store of the specified type.
10631 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10632 const AddrMode &AM, Type *Ty,
10633 unsigned AS) const {
10634 EVT VT = getValueType(DL, Ty, true);
10635 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10638 // Can never fold addr of global into load/store.
10642 switch (AM.Scale) {
10643 case 0: // no scale reg, must be "r+i" or "r", or "i".
10646 if (Subtarget->isThumb1Only())
10650 // ARM doesn't support any R+R*scale+imm addr modes.
10654 if (!VT.isSimple())
10657 if (Subtarget->isThumb2())
10658 return isLegalT2ScaledAddressingMode(AM, VT);
10660 int Scale = AM.Scale;
10661 switch (VT.getSimpleVT().SimpleTy) {
10662 default: return false;
10666 if (Scale < 0) Scale = -Scale;
10670 return isPowerOf2_32(Scale & ~1);
10674 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10679 // Note, we allow "void" uses (basically, uses that aren't loads or
10680 // stores), because arm allows folding a scale into many arithmetic
10681 // operations. This should be made more precise and revisited later.
10683 // Allow r << imm, but the imm has to be a multiple of two.
10684 if (Scale & 1) return false;
10685 return isPowerOf2_32(Scale);
10691 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10692 /// icmp immediate, that is the target has icmp instructions which can compare
10693 /// a register against the immediate without having to materialize the
10694 /// immediate into a register.
10695 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10696 // Thumb2 and ARM modes can use cmn for negative immediates.
10697 if (!Subtarget->isThumb())
10698 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10699 if (Subtarget->isThumb2())
10700 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10701 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10702 return Imm >= 0 && Imm <= 255;
10705 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10706 /// *or sub* immediate, that is the target has add or sub instructions which can
10707 /// add a register with the immediate without having to materialize the
10708 /// immediate into a register.
10709 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10710 // Same encoding for add/sub, just flip the sign.
10711 int64_t AbsImm = std::abs(Imm);
10712 if (!Subtarget->isThumb())
10713 return ARM_AM::getSOImmVal(AbsImm) != -1;
10714 if (Subtarget->isThumb2())
10715 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10716 // Thumb1 only has 8-bit unsigned immediate.
10717 return AbsImm >= 0 && AbsImm <= 255;
10720 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10721 bool isSEXTLoad, SDValue &Base,
10722 SDValue &Offset, bool &isInc,
10723 SelectionDAG &DAG) {
10724 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10727 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10728 // AddressingMode 3
10729 Base = Ptr->getOperand(0);
10730 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10731 int RHSC = (int)RHS->getZExtValue();
10732 if (RHSC < 0 && RHSC > -256) {
10733 assert(Ptr->getOpcode() == ISD::ADD);
10735 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10739 isInc = (Ptr->getOpcode() == ISD::ADD);
10740 Offset = Ptr->getOperand(1);
10742 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10743 // AddressingMode 2
10744 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10745 int RHSC = (int)RHS->getZExtValue();
10746 if (RHSC < 0 && RHSC > -0x1000) {
10747 assert(Ptr->getOpcode() == ISD::ADD);
10749 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10750 Base = Ptr->getOperand(0);
10755 if (Ptr->getOpcode() == ISD::ADD) {
10757 ARM_AM::ShiftOpc ShOpcVal=
10758 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10759 if (ShOpcVal != ARM_AM::no_shift) {
10760 Base = Ptr->getOperand(1);
10761 Offset = Ptr->getOperand(0);
10763 Base = Ptr->getOperand(0);
10764 Offset = Ptr->getOperand(1);
10769 isInc = (Ptr->getOpcode() == ISD::ADD);
10770 Base = Ptr->getOperand(0);
10771 Offset = Ptr->getOperand(1);
10775 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10779 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10780 bool isSEXTLoad, SDValue &Base,
10781 SDValue &Offset, bool &isInc,
10782 SelectionDAG &DAG) {
10783 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10786 Base = Ptr->getOperand(0);
10787 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10788 int RHSC = (int)RHS->getZExtValue();
10789 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10790 assert(Ptr->getOpcode() == ISD::ADD);
10792 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10794 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10795 isInc = Ptr->getOpcode() == ISD::ADD;
10796 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10804 /// getPreIndexedAddressParts - returns true by value, base pointer and
10805 /// offset pointer and addressing mode by reference if the node's address
10806 /// can be legally represented as pre-indexed load / store address.
10808 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10810 ISD::MemIndexedMode &AM,
10811 SelectionDAG &DAG) const {
10812 if (Subtarget->isThumb1Only())
10817 bool isSEXTLoad = false;
10818 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10819 Ptr = LD->getBasePtr();
10820 VT = LD->getMemoryVT();
10821 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10822 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10823 Ptr = ST->getBasePtr();
10824 VT = ST->getMemoryVT();
10829 bool isLegal = false;
10830 if (Subtarget->isThumb2())
10831 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10832 Offset, isInc, DAG);
10834 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10835 Offset, isInc, DAG);
10839 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10843 /// getPostIndexedAddressParts - returns true by value, base pointer and
10844 /// offset pointer and addressing mode by reference if this node can be
10845 /// combined with a load / store to form a post-indexed load / store.
10846 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10849 ISD::MemIndexedMode &AM,
10850 SelectionDAG &DAG) const {
10851 if (Subtarget->isThumb1Only())
10856 bool isSEXTLoad = false;
10857 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10858 VT = LD->getMemoryVT();
10859 Ptr = LD->getBasePtr();
10860 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10861 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10862 VT = ST->getMemoryVT();
10863 Ptr = ST->getBasePtr();
10868 bool isLegal = false;
10869 if (Subtarget->isThumb2())
10870 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10873 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10879 // Swap base ptr and offset to catch more post-index load / store when
10880 // it's legal. In Thumb2 mode, offset must be an immediate.
10881 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10882 !Subtarget->isThumb2())
10883 std::swap(Base, Offset);
10885 // Post-indexed load / store update the base pointer.
10890 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10894 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10897 const SelectionDAG &DAG,
10898 unsigned Depth) const {
10899 unsigned BitWidth = KnownOne.getBitWidth();
10900 KnownZero = KnownOne = APInt(BitWidth, 0);
10901 switch (Op.getOpcode()) {
10907 // These nodes' second result is a boolean
10908 if (Op.getResNo() == 0)
10910 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10912 case ARMISD::CMOV: {
10913 // Bits are known zero/one if known on the LHS and RHS.
10914 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10915 if (KnownZero == 0 && KnownOne == 0) return;
10917 APInt KnownZeroRHS, KnownOneRHS;
10918 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10919 KnownZero &= KnownZeroRHS;
10920 KnownOne &= KnownOneRHS;
10923 case ISD::INTRINSIC_W_CHAIN: {
10924 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10925 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10928 case Intrinsic::arm_ldaex:
10929 case Intrinsic::arm_ldrex: {
10930 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10931 unsigned MemBits = VT.getScalarType().getSizeInBits();
10932 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10940 //===----------------------------------------------------------------------===//
10941 // ARM Inline Assembly Support
10942 //===----------------------------------------------------------------------===//
10944 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10945 // Looking for "rev" which is V6+.
10946 if (!Subtarget->hasV6Ops())
10949 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10950 std::string AsmStr = IA->getAsmString();
10951 SmallVector<StringRef, 4> AsmPieces;
10952 SplitString(AsmStr, AsmPieces, ";\n");
10954 switch (AsmPieces.size()) {
10955 default: return false;
10957 AsmStr = AsmPieces[0];
10959 SplitString(AsmStr, AsmPieces, " \t,");
10962 if (AsmPieces.size() == 3 &&
10963 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10964 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10965 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10966 if (Ty && Ty->getBitWidth() == 32)
10967 return IntrinsicLowering::LowerToByteSwap(CI);
10975 /// getConstraintType - Given a constraint letter, return the type of
10976 /// constraint it is for this target.
10977 ARMTargetLowering::ConstraintType
10978 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10979 if (Constraint.size() == 1) {
10980 switch (Constraint[0]) {
10982 case 'l': return C_RegisterClass;
10983 case 'w': return C_RegisterClass;
10984 case 'h': return C_RegisterClass;
10985 case 'x': return C_RegisterClass;
10986 case 't': return C_RegisterClass;
10987 case 'j': return C_Other; // Constant for movw.
10988 // An address with a single base register. Due to the way we
10989 // currently handle addresses it is the same as an 'r' memory constraint.
10990 case 'Q': return C_Memory;
10992 } else if (Constraint.size() == 2) {
10993 switch (Constraint[0]) {
10995 // All 'U+' constraints are addresses.
10996 case 'U': return C_Memory;
10999 return TargetLowering::getConstraintType(Constraint);
11002 /// Examine constraint type and operand type and determine a weight value.
11003 /// This object must already have been set up with the operand type
11004 /// and the current alternative constraint selected.
11005 TargetLowering::ConstraintWeight
11006 ARMTargetLowering::getSingleConstraintMatchWeight(
11007 AsmOperandInfo &info, const char *constraint) const {
11008 ConstraintWeight weight = CW_Invalid;
11009 Value *CallOperandVal = info.CallOperandVal;
11010 // If we don't have a value, we can't do a match,
11011 // but allow it at the lowest weight.
11012 if (!CallOperandVal)
11014 Type *type = CallOperandVal->getType();
11015 // Look at the constraint type.
11016 switch (*constraint) {
11018 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11021 if (type->isIntegerTy()) {
11022 if (Subtarget->isThumb())
11023 weight = CW_SpecificReg;
11025 weight = CW_Register;
11029 if (type->isFloatingPointTy())
11030 weight = CW_Register;
11036 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11037 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11038 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11039 if (Constraint.size() == 1) {
11040 // GCC ARM Constraint Letters
11041 switch (Constraint[0]) {
11042 case 'l': // Low regs or general regs.
11043 if (Subtarget->isThumb())
11044 return RCPair(0U, &ARM::tGPRRegClass);
11045 return RCPair(0U, &ARM::GPRRegClass);
11046 case 'h': // High regs or no regs.
11047 if (Subtarget->isThumb())
11048 return RCPair(0U, &ARM::hGPRRegClass);
11051 if (Subtarget->isThumb1Only())
11052 return RCPair(0U, &ARM::tGPRRegClass);
11053 return RCPair(0U, &ARM::GPRRegClass);
11055 if (VT == MVT::Other)
11057 if (VT == MVT::f32)
11058 return RCPair(0U, &ARM::SPRRegClass);
11059 if (VT.getSizeInBits() == 64)
11060 return RCPair(0U, &ARM::DPRRegClass);
11061 if (VT.getSizeInBits() == 128)
11062 return RCPair(0U, &ARM::QPRRegClass);
11065 if (VT == MVT::Other)
11067 if (VT == MVT::f32)
11068 return RCPair(0U, &ARM::SPR_8RegClass);
11069 if (VT.getSizeInBits() == 64)
11070 return RCPair(0U, &ARM::DPR_8RegClass);
11071 if (VT.getSizeInBits() == 128)
11072 return RCPair(0U, &ARM::QPR_8RegClass);
11075 if (VT == MVT::f32)
11076 return RCPair(0U, &ARM::SPRRegClass);
11080 if (StringRef("{cc}").equals_lower(Constraint))
11081 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11083 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11086 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11087 /// vector. If it is invalid, don't add anything to Ops.
11088 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11089 std::string &Constraint,
11090 std::vector<SDValue>&Ops,
11091 SelectionDAG &DAG) const {
11094 // Currently only support length 1 constraints.
11095 if (Constraint.length() != 1) return;
11097 char ConstraintLetter = Constraint[0];
11098 switch (ConstraintLetter) {
11101 case 'I': case 'J': case 'K': case 'L':
11102 case 'M': case 'N': case 'O':
11103 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11107 int64_t CVal64 = C->getSExtValue();
11108 int CVal = (int) CVal64;
11109 // None of these constraints allow values larger than 32 bits. Check
11110 // that the value fits in an int.
11111 if (CVal != CVal64)
11114 switch (ConstraintLetter) {
11116 // Constant suitable for movw, must be between 0 and
11118 if (Subtarget->hasV6T2Ops())
11119 if (CVal >= 0 && CVal <= 65535)
11123 if (Subtarget->isThumb1Only()) {
11124 // This must be a constant between 0 and 255, for ADD
11126 if (CVal >= 0 && CVal <= 255)
11128 } else if (Subtarget->isThumb2()) {
11129 // A constant that can be used as an immediate value in a
11130 // data-processing instruction.
11131 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11134 // A constant that can be used as an immediate value in a
11135 // data-processing instruction.
11136 if (ARM_AM::getSOImmVal(CVal) != -1)
11142 if (Subtarget->isThumb()) { // FIXME thumb2
11143 // This must be a constant between -255 and -1, for negated ADD
11144 // immediates. This can be used in GCC with an "n" modifier that
11145 // prints the negated value, for use with SUB instructions. It is
11146 // not useful otherwise but is implemented for compatibility.
11147 if (CVal >= -255 && CVal <= -1)
11150 // This must be a constant between -4095 and 4095. It is not clear
11151 // what this constraint is intended for. Implemented for
11152 // compatibility with GCC.
11153 if (CVal >= -4095 && CVal <= 4095)
11159 if (Subtarget->isThumb1Only()) {
11160 // A 32-bit value where only one byte has a nonzero value. Exclude
11161 // zero to match GCC. This constraint is used by GCC internally for
11162 // constants that can be loaded with a move/shift combination.
11163 // It is not useful otherwise but is implemented for compatibility.
11164 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11166 } else if (Subtarget->isThumb2()) {
11167 // A constant whose bitwise inverse can be used as an immediate
11168 // value in a data-processing instruction. This can be used in GCC
11169 // with a "B" modifier that prints the inverted value, for use with
11170 // BIC and MVN instructions. It is not useful otherwise but is
11171 // implemented for compatibility.
11172 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11175 // A constant whose bitwise inverse can be used as an immediate
11176 // value in a data-processing instruction. This can be used in GCC
11177 // with a "B" modifier that prints the inverted value, for use with
11178 // BIC and MVN instructions. It is not useful otherwise but is
11179 // implemented for compatibility.
11180 if (ARM_AM::getSOImmVal(~CVal) != -1)
11186 if (Subtarget->isThumb1Only()) {
11187 // This must be a constant between -7 and 7,
11188 // for 3-operand ADD/SUB immediate instructions.
11189 if (CVal >= -7 && CVal < 7)
11191 } else if (Subtarget->isThumb2()) {
11192 // A constant whose negation can be used as an immediate value in a
11193 // data-processing instruction. This can be used in GCC with an "n"
11194 // modifier that prints the negated value, for use with SUB
11195 // instructions. It is not useful otherwise but is implemented for
11197 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11200 // A constant whose negation can be used as an immediate value in a
11201 // data-processing instruction. This can be used in GCC with an "n"
11202 // modifier that prints the negated value, for use with SUB
11203 // instructions. It is not useful otherwise but is implemented for
11205 if (ARM_AM::getSOImmVal(-CVal) != -1)
11211 if (Subtarget->isThumb()) { // FIXME thumb2
11212 // This must be a multiple of 4 between 0 and 1020, for
11213 // ADD sp + immediate.
11214 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11217 // A power of two or a constant between 0 and 32. This is used in
11218 // GCC for the shift amount on shifted register operands, but it is
11219 // useful in general for any shift amounts.
11220 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11226 if (Subtarget->isThumb()) { // FIXME thumb2
11227 // This must be a constant between 0 and 31, for shift amounts.
11228 if (CVal >= 0 && CVal <= 31)
11234 if (Subtarget->isThumb()) { // FIXME thumb2
11235 // This must be a multiple of 4 between -508 and 508, for
11236 // ADD/SUB sp = sp + immediate.
11237 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11242 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11246 if (Result.getNode()) {
11247 Ops.push_back(Result);
11250 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11253 static RTLIB::Libcall getDivRemLibcall(
11254 const SDNode *N, MVT::SimpleValueType SVT) {
11255 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11256 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11257 "Unhandled Opcode in getDivRemLibcall");
11258 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11259 N->getOpcode() == ISD::SREM;
11262 default: llvm_unreachable("Unexpected request for libcall!");
11263 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11264 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11265 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11266 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11271 static TargetLowering::ArgListTy getDivRemArgList(
11272 const SDNode *N, LLVMContext *Context) {
11273 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11274 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11275 "Unhandled Opcode in getDivRemArgList");
11276 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11277 N->getOpcode() == ISD::SREM;
11278 TargetLowering::ArgListTy Args;
11279 TargetLowering::ArgListEntry Entry;
11280 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11281 EVT ArgVT = N->getOperand(i).getValueType();
11282 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11283 Entry.Node = N->getOperand(i);
11285 Entry.isSExt = isSigned;
11286 Entry.isZExt = !isSigned;
11287 Args.push_back(Entry);
11292 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11293 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11294 "Register-based DivRem lowering only");
11295 unsigned Opcode = Op->getOpcode();
11296 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11297 "Invalid opcode for Div/Rem lowering");
11298 bool isSigned = (Opcode == ISD::SDIVREM);
11299 EVT VT = Op->getValueType(0);
11300 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11302 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11303 VT.getSimpleVT().SimpleTy);
11304 SDValue InChain = DAG.getEntryNode();
11306 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11309 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11310 getPointerTy(DAG.getDataLayout()));
11312 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11315 TargetLowering::CallLoweringInfo CLI(DAG);
11316 CLI.setDebugLoc(dl).setChain(InChain)
11317 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11318 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11320 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11321 return CallInfo.first;
11324 // Lowers REM using divmod helpers
11325 // see RTABI section 4.2/4.3
11326 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11327 // Build return types (div and rem)
11328 std::vector<Type*> RetTyParams;
11329 Type *RetTyElement;
11331 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11332 default: llvm_unreachable("Unexpected request for libcall!");
11333 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
11334 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11335 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11336 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11339 RetTyParams.push_back(RetTyElement);
11340 RetTyParams.push_back(RetTyElement);
11341 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11342 Type *RetTy = StructType::get(*DAG.getContext(), ret);
11344 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11346 SDValue InChain = DAG.getEntryNode();
11347 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11348 bool isSigned = N->getOpcode() == ISD::SREM;
11349 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11350 getPointerTy(DAG.getDataLayout()));
11353 CallLoweringInfo CLI(DAG);
11354 CLI.setChain(InChain)
11355 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11356 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11357 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11359 // Return second (rem) result operand (first contains div)
11360 SDNode *ResNode = CallResult.first.getNode();
11361 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11362 return ResNode->getOperand(1);
11366 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11367 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11371 SDValue Chain = Op.getOperand(0);
11372 SDValue Size = Op.getOperand(1);
11374 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11375 DAG.getConstant(2, DL, MVT::i32));
11378 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11379 Flag = Chain.getValue(1);
11381 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11382 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11384 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11385 Chain = NewSP.getValue(1);
11387 SDValue Ops[2] = { NewSP, Chain };
11388 return DAG.getMergeValues(Ops, DL);
11391 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11392 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11393 "Unexpected type for custom-lowering FP_EXTEND");
11396 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11398 SDValue SrcVal = Op.getOperand(0);
11399 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11400 /*isSigned*/ false, SDLoc(Op)).first;
11403 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11404 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11405 Subtarget->isFPOnlySP() &&
11406 "Unexpected type for custom-lowering FP_ROUND");
11409 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11411 SDValue SrcVal = Op.getOperand(0);
11412 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11413 /*isSigned*/ false, SDLoc(Op)).first;
11417 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11418 // The ARM target isn't yet aware of offsets.
11422 bool ARM::isBitFieldInvertedMask(unsigned v) {
11423 if (v == 0xffffffff)
11426 // there can be 1's on either or both "outsides", all the "inside"
11427 // bits must be 0's
11428 return isShiftedMask_32(~v);
11431 /// isFPImmLegal - Returns true if the target can instruction select the
11432 /// specified FP immediate natively. If false, the legalizer will
11433 /// materialize the FP immediate as a load from a constant pool.
11434 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11435 if (!Subtarget->hasVFP3())
11437 if (VT == MVT::f32)
11438 return ARM_AM::getFP32Imm(Imm) != -1;
11439 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11440 return ARM_AM::getFP64Imm(Imm) != -1;
11444 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11445 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11446 /// specified in the intrinsic calls.
11447 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11449 unsigned Intrinsic) const {
11450 switch (Intrinsic) {
11451 case Intrinsic::arm_neon_vld1:
11452 case Intrinsic::arm_neon_vld2:
11453 case Intrinsic::arm_neon_vld3:
11454 case Intrinsic::arm_neon_vld4:
11455 case Intrinsic::arm_neon_vld2lane:
11456 case Intrinsic::arm_neon_vld3lane:
11457 case Intrinsic::arm_neon_vld4lane: {
11458 Info.opc = ISD::INTRINSIC_W_CHAIN;
11459 // Conservatively set memVT to the entire set of vectors loaded.
11460 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11461 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11462 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11463 Info.ptrVal = I.getArgOperand(0);
11465 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11466 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11467 Info.vol = false; // volatile loads with NEON intrinsics not supported
11468 Info.readMem = true;
11469 Info.writeMem = false;
11472 case Intrinsic::arm_neon_vst1:
11473 case Intrinsic::arm_neon_vst2:
11474 case Intrinsic::arm_neon_vst3:
11475 case Intrinsic::arm_neon_vst4:
11476 case Intrinsic::arm_neon_vst2lane:
11477 case Intrinsic::arm_neon_vst3lane:
11478 case Intrinsic::arm_neon_vst4lane: {
11479 Info.opc = ISD::INTRINSIC_VOID;
11480 // Conservatively set memVT to the entire set of vectors stored.
11481 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11482 unsigned NumElts = 0;
11483 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11484 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11485 if (!ArgTy->isVectorTy())
11487 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11489 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11490 Info.ptrVal = I.getArgOperand(0);
11492 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11493 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11494 Info.vol = false; // volatile stores with NEON intrinsics not supported
11495 Info.readMem = false;
11496 Info.writeMem = true;
11499 case Intrinsic::arm_ldaex:
11500 case Intrinsic::arm_ldrex: {
11501 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11502 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11503 Info.opc = ISD::INTRINSIC_W_CHAIN;
11504 Info.memVT = MVT::getVT(PtrTy->getElementType());
11505 Info.ptrVal = I.getArgOperand(0);
11507 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11509 Info.readMem = true;
11510 Info.writeMem = false;
11513 case Intrinsic::arm_stlex:
11514 case Intrinsic::arm_strex: {
11515 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11516 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11517 Info.opc = ISD::INTRINSIC_W_CHAIN;
11518 Info.memVT = MVT::getVT(PtrTy->getElementType());
11519 Info.ptrVal = I.getArgOperand(1);
11521 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11523 Info.readMem = false;
11524 Info.writeMem = true;
11527 case Intrinsic::arm_stlexd:
11528 case Intrinsic::arm_strexd: {
11529 Info.opc = ISD::INTRINSIC_W_CHAIN;
11530 Info.memVT = MVT::i64;
11531 Info.ptrVal = I.getArgOperand(2);
11535 Info.readMem = false;
11536 Info.writeMem = true;
11539 case Intrinsic::arm_ldaexd:
11540 case Intrinsic::arm_ldrexd: {
11541 Info.opc = ISD::INTRINSIC_W_CHAIN;
11542 Info.memVT = MVT::i64;
11543 Info.ptrVal = I.getArgOperand(0);
11547 Info.readMem = true;
11548 Info.writeMem = false;
11558 /// \brief Returns true if it is beneficial to convert a load of a constant
11559 /// to just the constant itself.
11560 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11562 assert(Ty->isIntegerTy());
11564 unsigned Bits = Ty->getPrimitiveSizeInBits();
11565 if (Bits == 0 || Bits > 32)
11570 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11571 ARM_MB::MemBOpt Domain) const {
11572 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11574 // First, if the target has no DMB, see what fallback we can use.
11575 if (!Subtarget->hasDataBarrier()) {
11576 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11577 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11579 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11580 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11581 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11582 Builder.getInt32(0), Builder.getInt32(7),
11583 Builder.getInt32(10), Builder.getInt32(5)};
11584 return Builder.CreateCall(MCR, args);
11586 // Instead of using barriers, atomic accesses on these subtargets use
11588 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11591 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11592 // Only a full system barrier exists in the M-class architectures.
11593 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11594 Constant *CDomain = Builder.getInt32(Domain);
11595 return Builder.CreateCall(DMB, CDomain);
11599 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11600 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11601 AtomicOrdering Ord, bool IsStore,
11602 bool IsLoad) const {
11603 if (!getInsertFencesForAtomic())
11609 llvm_unreachable("Invalid fence: unordered/non-atomic");
11612 return nullptr; // Nothing to do
11613 case SequentiallyConsistent:
11615 return nullptr; // Nothing to do
11618 case AcquireRelease:
11619 if (Subtarget->isSwift())
11620 return makeDMB(Builder, ARM_MB::ISHST);
11621 // FIXME: add a comment with a link to documentation justifying this.
11623 return makeDMB(Builder, ARM_MB::ISH);
11625 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11628 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11629 AtomicOrdering Ord, bool IsStore,
11630 bool IsLoad) const {
11631 if (!getInsertFencesForAtomic())
11637 llvm_unreachable("Invalid fence: unordered/not-atomic");
11640 return nullptr; // Nothing to do
11642 case AcquireRelease:
11643 case SequentiallyConsistent:
11644 return makeDMB(Builder, ARM_MB::ISH);
11646 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11649 // Loads and stores less than 64-bits are already atomic; ones above that
11650 // are doomed anyway, so defer to the default libcall and blame the OS when
11651 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11652 // anything for those.
11653 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11654 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11655 return (Size == 64) && !Subtarget->isMClass();
11658 // Loads and stores less than 64-bits are already atomic; ones above that
11659 // are doomed anyway, so defer to the default libcall and blame the OS when
11660 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11661 // anything for those.
11662 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11663 // guarantee, see DDI0406C ARM architecture reference manual,
11664 // sections A8.8.72-74 LDRD)
11665 TargetLowering::AtomicExpansionKind
11666 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11667 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11668 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11669 : AtomicExpansionKind::None;
11672 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11673 // and up to 64 bits on the non-M profiles
11674 TargetLowering::AtomicExpansionKind
11675 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11676 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11677 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11678 ? AtomicExpansionKind::LLSC
11679 : AtomicExpansionKind::None;
11682 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11683 AtomicCmpXchgInst *AI) const {
11687 // This has so far only been implemented for MachO.
11688 bool ARMTargetLowering::useLoadStackGuardNode() const {
11689 return Subtarget->isTargetMachO();
11692 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11693 unsigned &Cost) const {
11694 // If we do not have NEON, vector types are not natively supported.
11695 if (!Subtarget->hasNEON())
11698 // Floating point values and vector values map to the same register file.
11699 // Therefore, although we could do a store extract of a vector type, this is
11700 // better to leave at float as we have more freedom in the addressing mode for
11702 if (VectorTy->isFPOrFPVectorTy())
11705 // If the index is unknown at compile time, this is very expensive to lower
11706 // and it is not possible to combine the store with the extract.
11707 if (!isa<ConstantInt>(Idx))
11710 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11711 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11712 // We can do a store + vector extract on any vector that fits perfectly in a D
11714 if (BitWidth == 64 || BitWidth == 128) {
11721 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11722 AtomicOrdering Ord) const {
11723 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11724 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11725 bool IsAcquire = isAtLeastAcquire(Ord);
11727 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11728 // intrinsic must return {i32, i32} and we have to recombine them into a
11729 // single i64 here.
11730 if (ValTy->getPrimitiveSizeInBits() == 64) {
11731 Intrinsic::ID Int =
11732 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11733 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11735 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11736 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11738 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11739 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11740 if (!Subtarget->isLittle())
11741 std::swap (Lo, Hi);
11742 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11743 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11744 return Builder.CreateOr(
11745 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11748 Type *Tys[] = { Addr->getType() };
11749 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11750 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11752 return Builder.CreateTruncOrBitCast(
11753 Builder.CreateCall(Ldrex, Addr),
11754 cast<PointerType>(Addr->getType())->getElementType());
11757 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11758 IRBuilder<> &Builder) const {
11759 if (!Subtarget->hasV7Ops())
11761 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11762 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
11765 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11767 AtomicOrdering Ord) const {
11768 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11769 bool IsRelease = isAtLeastRelease(Ord);
11771 // Since the intrinsics must have legal type, the i64 intrinsics take two
11772 // parameters: "i32, i32". We must marshal Val into the appropriate form
11773 // before the call.
11774 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11775 Intrinsic::ID Int =
11776 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11777 Function *Strex = Intrinsic::getDeclaration(M, Int);
11778 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11780 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11781 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11782 if (!Subtarget->isLittle())
11783 std::swap (Lo, Hi);
11784 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11785 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11788 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11789 Type *Tys[] = { Addr->getType() };
11790 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11792 return Builder.CreateCall(
11793 Strex, {Builder.CreateZExtOrBitCast(
11794 Val, Strex->getFunctionType()->getParamType(0)),
11798 /// \brief Lower an interleaved load into a vldN intrinsic.
11800 /// E.g. Lower an interleaved load (Factor = 2):
11801 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11802 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
11803 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
11806 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11807 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11808 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11809 bool ARMTargetLowering::lowerInterleavedLoad(
11810 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11811 ArrayRef<unsigned> Indices, unsigned Factor) const {
11812 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11813 "Invalid interleave factor");
11814 assert(!Shuffles.empty() && "Empty shufflevector input");
11815 assert(Shuffles.size() == Indices.size() &&
11816 "Unmatched number of shufflevectors and indices");
11818 VectorType *VecTy = Shuffles[0]->getType();
11819 Type *EltTy = VecTy->getVectorElementType();
11821 const DataLayout &DL = LI->getModule()->getDataLayout();
11822 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11823 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11825 // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11826 // support i64/f64 element).
11827 if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11830 // A pointer vector can not be the return type of the ldN intrinsics. Need to
11831 // load integer vectors first and then convert to pointer vectors.
11832 if (EltTy->isPointerTy())
11834 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11836 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11837 Intrinsic::arm_neon_vld3,
11838 Intrinsic::arm_neon_vld4};
11840 IRBuilder<> Builder(LI);
11841 SmallVector<Value *, 2> Ops;
11843 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11844 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11845 Ops.push_back(Builder.getInt32(LI->getAlignment()));
11847 Type *Tys[] = { VecTy, Int8Ptr };
11848 Function *VldnFunc =
11849 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
11850 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11852 // Replace uses of each shufflevector with the corresponding vector loaded
11854 for (unsigned i = 0; i < Shuffles.size(); i++) {
11855 ShuffleVectorInst *SV = Shuffles[i];
11856 unsigned Index = Indices[i];
11858 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11860 // Convert the integer vector to pointer vector if the element is pointer.
11861 if (EltTy->isPointerTy())
11862 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11864 SV->replaceAllUsesWith(SubVec);
11870 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11872 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11873 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11874 unsigned NumElts) {
11875 SmallVector<Constant *, 16> Mask;
11876 for (unsigned i = 0; i < NumElts; i++)
11877 Mask.push_back(Builder.getInt32(Start + i));
11879 return ConstantVector::get(Mask);
11882 /// \brief Lower an interleaved store into a vstN intrinsic.
11884 /// E.g. Lower an interleaved store (Factor = 3):
11885 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11886 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11887 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11890 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11891 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11892 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11893 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11895 /// Note that the new shufflevectors will be removed and we'll only generate one
11896 /// vst3 instruction in CodeGen.
11897 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11898 ShuffleVectorInst *SVI,
11899 unsigned Factor) const {
11900 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11901 "Invalid interleave factor");
11903 VectorType *VecTy = SVI->getType();
11904 assert(VecTy->getVectorNumElements() % Factor == 0 &&
11905 "Invalid interleaved store");
11907 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11908 Type *EltTy = VecTy->getVectorElementType();
11909 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11911 const DataLayout &DL = SI->getModule()->getDataLayout();
11912 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11913 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11915 // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11916 // doesn't support i64/f64 element).
11917 if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11920 Value *Op0 = SVI->getOperand(0);
11921 Value *Op1 = SVI->getOperand(1);
11922 IRBuilder<> Builder(SI);
11924 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11925 // vectors to integer vectors.
11926 if (EltTy->isPointerTy()) {
11927 Type *IntTy = DL.getIntPtrType(EltTy);
11929 // Convert to the corresponding integer vector.
11931 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11932 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11933 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11935 SubVecTy = VectorType::get(IntTy, NumSubElts);
11938 static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11939 Intrinsic::arm_neon_vst3,
11940 Intrinsic::arm_neon_vst4};
11941 SmallVector<Value *, 6> Ops;
11943 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11944 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11946 Type *Tys[] = { Int8Ptr, SubVecTy };
11947 Function *VstNFunc = Intrinsic::getDeclaration(
11948 SI->getModule(), StoreInts[Factor - 2], Tys);
11950 // Split the shufflevector operands into sub vectors for the new vstN call.
11951 for (unsigned i = 0; i < Factor; i++)
11952 Ops.push_back(Builder.CreateShuffleVector(
11953 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11955 Ops.push_back(Builder.getInt32(SI->getAlignment()));
11956 Builder.CreateCall(VstNFunc, Ops);
11968 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11969 uint64_t &Members) {
11970 if (auto *ST = dyn_cast<StructType>(Ty)) {
11971 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11972 uint64_t SubMembers = 0;
11973 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11975 Members += SubMembers;
11977 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11978 uint64_t SubMembers = 0;
11979 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11981 Members += SubMembers * AT->getNumElements();
11982 } else if (Ty->isFloatTy()) {
11983 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11987 } else if (Ty->isDoubleTy()) {
11988 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11992 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11999 return VT->getBitWidth() == 64;
12001 return VT->getBitWidth() == 128;
12003 switch (VT->getBitWidth()) {
12016 return (Members > 0 && Members <= 4);
12019 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12020 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12021 /// passing according to AAPCS rules.
12022 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12023 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12024 if (getEffectiveCallingConv(CallConv, isVarArg) !=
12025 CallingConv::ARM_AAPCS_VFP)
12028 HABaseType Base = HA_UNKNOWN;
12029 uint64_t Members = 0;
12030 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12031 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12033 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12034 return IsHA || IsIntArray;