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::VLD2DUP: return "ARMISD::VLD2DUP";
1182 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1183 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1184 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1185 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1186 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1187 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1188 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1189 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1190 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1191 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1192 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1193 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1194 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1195 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1196 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1197 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1198 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1199 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1200 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1205 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1208 return getPointerTy(DL);
1209 return VT.changeVectorElementTypeToInteger();
1212 /// getRegClassFor - Return the register class that should be used for the
1213 /// specified value type.
1214 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1215 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1216 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1217 // load / store 4 to 8 consecutive D registers.
1218 if (Subtarget->hasNEON()) {
1219 if (VT == MVT::v4i64)
1220 return &ARM::QQPRRegClass;
1221 if (VT == MVT::v8i64)
1222 return &ARM::QQQQPRRegClass;
1224 return TargetLowering::getRegClassFor(VT);
1227 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1228 // source/dest is aligned and the copy size is large enough. We therefore want
1229 // to align such objects passed to memory intrinsics.
1230 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1231 unsigned &PrefAlign) const {
1232 if (!isa<MemIntrinsic>(CI))
1235 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1236 // cycle faster than 4-byte aligned LDM.
1237 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1241 // Create a fast isel object.
1243 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1244 const TargetLibraryInfo *libInfo) const {
1245 return ARM::createFastISel(funcInfo, libInfo);
1248 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1249 unsigned NumVals = N->getNumValues();
1251 return Sched::RegPressure;
1253 for (unsigned i = 0; i != NumVals; ++i) {
1254 EVT VT = N->getValueType(i);
1255 if (VT == MVT::Glue || VT == MVT::Other)
1257 if (VT.isFloatingPoint() || VT.isVector())
1261 if (!N->isMachineOpcode())
1262 return Sched::RegPressure;
1264 // Load are scheduled for latency even if there instruction itinerary
1265 // is not available.
1266 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1267 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1269 if (MCID.getNumDefs() == 0)
1270 return Sched::RegPressure;
1271 if (!Itins->isEmpty() &&
1272 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1275 return Sched::RegPressure;
1278 //===----------------------------------------------------------------------===//
1280 //===----------------------------------------------------------------------===//
1282 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1283 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1285 default: llvm_unreachable("Unknown condition code!");
1286 case ISD::SETNE: return ARMCC::NE;
1287 case ISD::SETEQ: return ARMCC::EQ;
1288 case ISD::SETGT: return ARMCC::GT;
1289 case ISD::SETGE: return ARMCC::GE;
1290 case ISD::SETLT: return ARMCC::LT;
1291 case ISD::SETLE: return ARMCC::LE;
1292 case ISD::SETUGT: return ARMCC::HI;
1293 case ISD::SETUGE: return ARMCC::HS;
1294 case ISD::SETULT: return ARMCC::LO;
1295 case ISD::SETULE: return ARMCC::LS;
1299 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1300 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1301 ARMCC::CondCodes &CondCode2) {
1302 CondCode2 = ARMCC::AL;
1304 default: llvm_unreachable("Unknown FP condition!");
1306 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1308 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1310 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1311 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1312 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1313 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1314 case ISD::SETO: CondCode = ARMCC::VC; break;
1315 case ISD::SETUO: CondCode = ARMCC::VS; break;
1316 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1317 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1318 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1320 case ISD::SETULT: CondCode = ARMCC::LT; break;
1322 case ISD::SETULE: CondCode = ARMCC::LE; break;
1324 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1328 //===----------------------------------------------------------------------===//
1329 // Calling Convention Implementation
1330 //===----------------------------------------------------------------------===//
1332 #include "ARMGenCallingConv.inc"
1334 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1335 /// account presence of floating point hardware and calling convention
1336 /// limitations, such as support for variadic functions.
1338 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1339 bool isVarArg) const {
1342 llvm_unreachable("Unsupported calling convention");
1343 case CallingConv::ARM_AAPCS:
1344 case CallingConv::ARM_APCS:
1345 case CallingConv::GHC:
1347 case CallingConv::ARM_AAPCS_VFP:
1348 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1349 case CallingConv::C:
1350 if (!Subtarget->isAAPCS_ABI())
1351 return CallingConv::ARM_APCS;
1352 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1353 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1355 return CallingConv::ARM_AAPCS_VFP;
1357 return CallingConv::ARM_AAPCS;
1358 case CallingConv::Fast:
1359 if (!Subtarget->isAAPCS_ABI()) {
1360 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1361 return CallingConv::Fast;
1362 return CallingConv::ARM_APCS;
1363 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1364 return CallingConv::ARM_AAPCS_VFP;
1366 return CallingConv::ARM_AAPCS;
1370 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1371 /// CallingConvention.
1372 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1374 bool isVarArg) const {
1375 switch (getEffectiveCallingConv(CC, isVarArg)) {
1377 llvm_unreachable("Unsupported calling convention");
1378 case CallingConv::ARM_APCS:
1379 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1380 case CallingConv::ARM_AAPCS:
1381 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1382 case CallingConv::ARM_AAPCS_VFP:
1383 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1384 case CallingConv::Fast:
1385 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1386 case CallingConv::GHC:
1387 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1391 /// LowerCallResult - Lower the result values of a call into the
1392 /// appropriate copies out of appropriate physical registers.
1394 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1395 CallingConv::ID CallConv, bool isVarArg,
1396 const SmallVectorImpl<ISD::InputArg> &Ins,
1397 SDLoc dl, SelectionDAG &DAG,
1398 SmallVectorImpl<SDValue> &InVals,
1399 bool isThisReturn, SDValue ThisVal) const {
1401 // Assign locations to each value returned by this call.
1402 SmallVector<CCValAssign, 16> RVLocs;
1403 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1404 *DAG.getContext(), Call);
1405 CCInfo.AnalyzeCallResult(Ins,
1406 CCAssignFnForNode(CallConv, /* Return*/ true,
1409 // Copy all of the result registers out of their specified physreg.
1410 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1411 CCValAssign VA = RVLocs[i];
1413 // Pass 'this' value directly from the argument to return value, to avoid
1414 // reg unit interference
1415 if (i == 0 && isThisReturn) {
1416 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1417 "unexpected return calling convention register assignment");
1418 InVals.push_back(ThisVal);
1423 if (VA.needsCustom()) {
1424 // Handle f64 or half of a v2f64.
1425 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1427 Chain = Lo.getValue(1);
1428 InFlag = Lo.getValue(2);
1429 VA = RVLocs[++i]; // skip ahead to next loc
1430 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1432 Chain = Hi.getValue(1);
1433 InFlag = Hi.getValue(2);
1434 if (!Subtarget->isLittle())
1436 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1438 if (VA.getLocVT() == MVT::v2f64) {
1439 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1440 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1441 DAG.getConstant(0, dl, MVT::i32));
1443 VA = RVLocs[++i]; // skip ahead to next loc
1444 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1445 Chain = Lo.getValue(1);
1446 InFlag = Lo.getValue(2);
1447 VA = RVLocs[++i]; // skip ahead to next loc
1448 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1449 Chain = Hi.getValue(1);
1450 InFlag = Hi.getValue(2);
1451 if (!Subtarget->isLittle())
1453 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1454 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1455 DAG.getConstant(1, dl, MVT::i32));
1458 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1460 Chain = Val.getValue(1);
1461 InFlag = Val.getValue(2);
1464 switch (VA.getLocInfo()) {
1465 default: llvm_unreachable("Unknown loc info!");
1466 case CCValAssign::Full: break;
1467 case CCValAssign::BCvt:
1468 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1472 InVals.push_back(Val);
1478 /// LowerMemOpCallTo - Store the argument to the stack.
1480 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1481 SDValue StackPtr, SDValue Arg,
1482 SDLoc dl, SelectionDAG &DAG,
1483 const CCValAssign &VA,
1484 ISD::ArgFlagsTy Flags) const {
1485 unsigned LocMemOffset = VA.getLocMemOffset();
1486 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1487 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1489 return DAG.getStore(
1490 Chain, dl, Arg, PtrOff,
1491 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1495 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1496 SDValue Chain, SDValue &Arg,
1497 RegsToPassVector &RegsToPass,
1498 CCValAssign &VA, CCValAssign &NextVA,
1500 SmallVectorImpl<SDValue> &MemOpChains,
1501 ISD::ArgFlagsTy Flags) const {
1503 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1504 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1505 unsigned id = Subtarget->isLittle() ? 0 : 1;
1506 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1508 if (NextVA.isRegLoc())
1509 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1511 assert(NextVA.isMemLoc());
1512 if (!StackPtr.getNode())
1513 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1514 getPointerTy(DAG.getDataLayout()));
1516 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1522 /// LowerCall - Lowering a call into a callseq_start <-
1523 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1526 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1527 SmallVectorImpl<SDValue> &InVals) const {
1528 SelectionDAG &DAG = CLI.DAG;
1530 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1531 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1532 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1533 SDValue Chain = CLI.Chain;
1534 SDValue Callee = CLI.Callee;
1535 bool &isTailCall = CLI.IsTailCall;
1536 CallingConv::ID CallConv = CLI.CallConv;
1537 bool doesNotRet = CLI.DoesNotReturn;
1538 bool isVarArg = CLI.IsVarArg;
1540 MachineFunction &MF = DAG.getMachineFunction();
1541 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1542 bool isThisReturn = false;
1543 bool isSibCall = false;
1544 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1546 // Disable tail calls if they're not supported.
1547 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1551 // Check if it's really possible to do a tail call.
1552 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1553 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1554 Outs, OutVals, Ins, DAG);
1555 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1556 report_fatal_error("failed to perform tail call elimination on a call "
1557 "site marked musttail");
1558 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1559 // detected sibcalls.
1566 // Analyze operands of the call, assigning locations to each operand.
1567 SmallVector<CCValAssign, 16> ArgLocs;
1568 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1569 *DAG.getContext(), Call);
1570 CCInfo.AnalyzeCallOperands(Outs,
1571 CCAssignFnForNode(CallConv, /* Return*/ false,
1574 // Get a count of how many bytes are to be pushed on the stack.
1575 unsigned NumBytes = CCInfo.getNextStackOffset();
1577 // For tail calls, memory operands are available in our caller's stack.
1581 // Adjust the stack pointer for the new arguments...
1582 // These operations are automatically eliminated by the prolog/epilog pass
1584 Chain = DAG.getCALLSEQ_START(Chain,
1585 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1588 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1590 RegsToPassVector RegsToPass;
1591 SmallVector<SDValue, 8> MemOpChains;
1593 // Walk the register/memloc assignments, inserting copies/loads. In the case
1594 // of tail call optimization, arguments are handled later.
1595 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1597 ++i, ++realArgIdx) {
1598 CCValAssign &VA = ArgLocs[i];
1599 SDValue Arg = OutVals[realArgIdx];
1600 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1601 bool isByVal = Flags.isByVal();
1603 // Promote the value if needed.
1604 switch (VA.getLocInfo()) {
1605 default: llvm_unreachable("Unknown loc info!");
1606 case CCValAssign::Full: break;
1607 case CCValAssign::SExt:
1608 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1610 case CCValAssign::ZExt:
1611 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1613 case CCValAssign::AExt:
1614 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1616 case CCValAssign::BCvt:
1617 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1621 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1622 if (VA.needsCustom()) {
1623 if (VA.getLocVT() == MVT::v2f64) {
1624 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1625 DAG.getConstant(0, dl, MVT::i32));
1626 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1627 DAG.getConstant(1, dl, MVT::i32));
1629 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1630 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1632 VA = ArgLocs[++i]; // skip ahead to next loc
1633 if (VA.isRegLoc()) {
1634 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1635 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1637 assert(VA.isMemLoc());
1639 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1640 dl, DAG, VA, Flags));
1643 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1644 StackPtr, MemOpChains, Flags);
1646 } else if (VA.isRegLoc()) {
1647 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1648 assert(VA.getLocVT() == MVT::i32 &&
1649 "unexpected calling convention register assignment");
1650 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1651 "unexpected use of 'returned'");
1652 isThisReturn = true;
1654 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1655 } else if (isByVal) {
1656 assert(VA.isMemLoc());
1657 unsigned offset = 0;
1659 // True if this byval aggregate will be split between registers
1661 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1662 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1664 if (CurByValIdx < ByValArgsCount) {
1666 unsigned RegBegin, RegEnd;
1667 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1670 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1672 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1673 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1674 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1675 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1676 MachinePointerInfo(),
1677 false, false, false,
1678 DAG.InferPtrAlignment(AddArg));
1679 MemOpChains.push_back(Load.getValue(1));
1680 RegsToPass.push_back(std::make_pair(j, Load));
1683 // If parameter size outsides register area, "offset" value
1684 // helps us to calculate stack slot for remained part properly.
1685 offset = RegEnd - RegBegin;
1687 CCInfo.nextInRegsParam();
1690 if (Flags.getByValSize() > 4*offset) {
1691 auto PtrVT = getPointerTy(DAG.getDataLayout());
1692 unsigned LocMemOffset = VA.getLocMemOffset();
1693 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1694 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1695 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1696 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1697 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1699 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1702 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1703 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1704 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1707 } else if (!isSibCall) {
1708 assert(VA.isMemLoc());
1710 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1711 dl, DAG, VA, Flags));
1715 if (!MemOpChains.empty())
1716 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1718 // Build a sequence of copy-to-reg nodes chained together with token chain
1719 // and flag operands which copy the outgoing args into the appropriate regs.
1721 // Tail call byval lowering might overwrite argument registers so in case of
1722 // tail call optimization the copies to registers are lowered later.
1724 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1725 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1726 RegsToPass[i].second, InFlag);
1727 InFlag = Chain.getValue(1);
1730 // For tail calls lower the arguments to the 'real' stack slot.
1732 // Force all the incoming stack arguments to be loaded from the stack
1733 // before any new outgoing arguments are stored to the stack, because the
1734 // outgoing stack slots may alias the incoming argument stack slots, and
1735 // the alias isn't otherwise explicit. This is slightly more conservative
1736 // than necessary, because it means that each store effectively depends
1737 // on every argument instead of just those arguments it would clobber.
1739 // Do not flag preceding copytoreg stuff together with the following stuff.
1741 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1742 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1743 RegsToPass[i].second, InFlag);
1744 InFlag = Chain.getValue(1);
1749 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1750 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1751 // node so that legalize doesn't hack it.
1752 bool isDirect = false;
1753 bool isARMFunc = false;
1754 bool isLocalARMFunc = false;
1755 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1756 auto PtrVt = getPointerTy(DAG.getDataLayout());
1758 if (Subtarget->genLongCalls()) {
1759 assert((Subtarget->isTargetWindows() ||
1760 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1761 "long-calls with non-static relocation model!");
1762 // Handle a global address or an external symbol. If it's not one of
1763 // those, the target's already in a register, so we don't need to do
1765 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1766 const GlobalValue *GV = G->getGlobal();
1767 // Create a constant pool entry for the callee address
1768 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1769 ARMConstantPoolValue *CPV =
1770 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1772 // Get the address of the callee into a register
1773 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1774 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1775 Callee = DAG.getLoad(
1776 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1777 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1779 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1780 const char *Sym = S->getSymbol();
1782 // Create a constant pool entry for the callee address
1783 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1784 ARMConstantPoolValue *CPV =
1785 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1786 ARMPCLabelIndex, 0);
1787 // Get the address of the callee into a register
1788 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1789 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1790 Callee = DAG.getLoad(
1791 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1792 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1795 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1796 const GlobalValue *GV = G->getGlobal();
1798 bool isDef = GV->isStrongDefinitionForLinker();
1799 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1800 getTargetMachine().getRelocationModel() != Reloc::Static;
1801 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1802 // ARM call to a local ARM function is predicable.
1803 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1804 // tBX takes a register source operand.
1805 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1806 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1807 Callee = DAG.getNode(
1808 ARMISD::WrapperPIC, dl, PtrVt,
1809 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1810 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1811 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1812 false, false, true, 0);
1813 } else if (Subtarget->isTargetCOFF()) {
1814 assert(Subtarget->isTargetWindows() &&
1815 "Windows is the only supported COFF target");
1816 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1817 ? ARMII::MO_DLLIMPORT
1818 : ARMII::MO_NO_FLAG;
1820 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1821 if (GV->hasDLLImportStorageClass())
1823 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1824 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1825 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1826 false, false, false, 0);
1828 // On ELF targets for PIC code, direct calls should go through the PLT
1829 unsigned OpFlags = 0;
1830 if (Subtarget->isTargetELF() &&
1831 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1832 OpFlags = ARMII::MO_PLT;
1833 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1835 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1837 bool isStub = Subtarget->isTargetMachO() &&
1838 getTargetMachine().getRelocationModel() != Reloc::Static;
1839 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1840 // tBX takes a register source operand.
1841 const char *Sym = S->getSymbol();
1842 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1843 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1844 ARMConstantPoolValue *CPV =
1845 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1846 ARMPCLabelIndex, 4);
1847 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1848 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1849 Callee = DAG.getLoad(
1850 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1851 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1853 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1854 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1856 unsigned OpFlags = 0;
1857 // On ELF targets for PIC code, direct calls should go through the PLT
1858 if (Subtarget->isTargetELF() &&
1859 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1860 OpFlags = ARMII::MO_PLT;
1861 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1865 // FIXME: handle tail calls differently.
1867 if (Subtarget->isThumb()) {
1868 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1869 CallOpc = ARMISD::CALL_NOLINK;
1871 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1873 if (!isDirect && !Subtarget->hasV5TOps())
1874 CallOpc = ARMISD::CALL_NOLINK;
1875 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1876 // Emit regular call when code size is the priority
1877 !MF.getFunction()->optForMinSize())
1878 // "mov lr, pc; b _foo" to avoid confusing the RSP
1879 CallOpc = ARMISD::CALL_NOLINK;
1881 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1884 std::vector<SDValue> Ops;
1885 Ops.push_back(Chain);
1886 Ops.push_back(Callee);
1888 // Add argument registers to the end of the list so that they are known live
1890 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1891 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1892 RegsToPass[i].second.getValueType()));
1894 // Add a register mask operand representing the call-preserved registers.
1896 const uint32_t *Mask;
1897 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1899 // For 'this' returns, use the R0-preserving mask if applicable
1900 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1902 // Set isThisReturn to false if the calling convention is not one that
1903 // allows 'returned' to be modeled in this way, so LowerCallResult does
1904 // not try to pass 'this' straight through
1905 isThisReturn = false;
1906 Mask = ARI->getCallPreservedMask(MF, CallConv);
1909 Mask = ARI->getCallPreservedMask(MF, CallConv);
1911 assert(Mask && "Missing call preserved mask for calling convention");
1912 Ops.push_back(DAG.getRegisterMask(Mask));
1915 if (InFlag.getNode())
1916 Ops.push_back(InFlag);
1918 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1920 MF.getFrameInfo()->setHasTailCall();
1921 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1924 // Returns a chain and a flag for retval copy to use.
1925 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1926 InFlag = Chain.getValue(1);
1928 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1929 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1931 InFlag = Chain.getValue(1);
1933 // Handle result values, copying them out of physregs into vregs that we
1935 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1936 InVals, isThisReturn,
1937 isThisReturn ? OutVals[0] : SDValue());
1940 /// HandleByVal - Every parameter *after* a byval parameter is passed
1941 /// on the stack. Remember the next parameter register to allocate,
1942 /// and then confiscate the rest of the parameter registers to insure
1944 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1945 unsigned Align) const {
1946 assert((State->getCallOrPrologue() == Prologue ||
1947 State->getCallOrPrologue() == Call) &&
1948 "unhandled ParmContext");
1950 // Byval (as with any stack) slots are always at least 4 byte aligned.
1951 Align = std::max(Align, 4U);
1953 unsigned Reg = State->AllocateReg(GPRArgRegs);
1957 unsigned AlignInRegs = Align / 4;
1958 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1959 for (unsigned i = 0; i < Waste; ++i)
1960 Reg = State->AllocateReg(GPRArgRegs);
1965 unsigned Excess = 4 * (ARM::R4 - Reg);
1967 // Special case when NSAA != SP and parameter size greater than size of
1968 // all remained GPR regs. In that case we can't split parameter, we must
1969 // send it to stack. We also must set NCRN to R4, so waste all
1970 // remained registers.
1971 const unsigned NSAAOffset = State->getNextStackOffset();
1972 if (NSAAOffset != 0 && Size > Excess) {
1973 while (State->AllocateReg(GPRArgRegs))
1978 // First register for byval parameter is the first register that wasn't
1979 // allocated before this method call, so it would be "reg".
1980 // If parameter is small enough to be saved in range [reg, r4), then
1981 // the end (first after last) register would be reg + param-size-in-regs,
1982 // else parameter would be splitted between registers and stack,
1983 // end register would be r4 in this case.
1984 unsigned ByValRegBegin = Reg;
1985 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1986 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1987 // Note, first register is allocated in the beginning of function already,
1988 // allocate remained amount of registers we need.
1989 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1990 State->AllocateReg(GPRArgRegs);
1991 // A byval parameter that is split between registers and memory needs its
1992 // size truncated here.
1993 // In the case where the entire structure fits in registers, we set the
1994 // size in memory to zero.
1995 Size = std::max<int>(Size - Excess, 0);
1998 /// MatchingStackOffset - Return true if the given stack call argument is
1999 /// already available in the same position (relatively) of the caller's
2000 /// incoming argument stack.
2002 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2003 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2004 const TargetInstrInfo *TII) {
2005 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2007 if (Arg.getOpcode() == ISD::CopyFromReg) {
2008 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2009 if (!TargetRegisterInfo::isVirtualRegister(VR))
2011 MachineInstr *Def = MRI->getVRegDef(VR);
2014 if (!Flags.isByVal()) {
2015 if (!TII->isLoadFromStackSlot(Def, FI))
2020 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2021 if (Flags.isByVal())
2022 // ByVal argument is passed in as a pointer but it's now being
2023 // dereferenced. e.g.
2024 // define @foo(%struct.X* %A) {
2025 // tail call @bar(%struct.X* byval %A)
2028 SDValue Ptr = Ld->getBasePtr();
2029 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2032 FI = FINode->getIndex();
2036 assert(FI != INT_MAX);
2037 if (!MFI->isFixedObjectIndex(FI))
2039 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2042 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2043 /// for tail call optimization. Targets which want to do tail call
2044 /// optimization should implement this function.
2046 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2047 CallingConv::ID CalleeCC,
2049 bool isCalleeStructRet,
2050 bool isCallerStructRet,
2051 const SmallVectorImpl<ISD::OutputArg> &Outs,
2052 const SmallVectorImpl<SDValue> &OutVals,
2053 const SmallVectorImpl<ISD::InputArg> &Ins,
2054 SelectionDAG& DAG) const {
2055 const Function *CallerF = DAG.getMachineFunction().getFunction();
2056 CallingConv::ID CallerCC = CallerF->getCallingConv();
2057 bool CCMatch = CallerCC == CalleeCC;
2059 // Look for obvious safe cases to perform tail call optimization that do not
2060 // require ABI changes. This is what gcc calls sibcall.
2062 // Do not sibcall optimize vararg calls unless the call site is not passing
2064 if (isVarArg && !Outs.empty())
2067 // Exception-handling functions need a special set of instructions to indicate
2068 // a return to the hardware. Tail-calling another function would probably
2070 if (CallerF->hasFnAttribute("interrupt"))
2073 // Also avoid sibcall optimization if either caller or callee uses struct
2074 // return semantics.
2075 if (isCalleeStructRet || isCallerStructRet)
2078 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2079 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2080 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2081 // support in the assembler and linker to be used. This would need to be
2082 // fixed to fully support tail calls in Thumb1.
2084 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2085 // LR. This means if we need to reload LR, it takes an extra instructions,
2086 // which outweighs the value of the tail call; but here we don't know yet
2087 // whether LR is going to be used. Probably the right approach is to
2088 // generate the tail call here and turn it back into CALL/RET in
2089 // emitEpilogue if LR is used.
2091 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2092 // but we need to make sure there are enough registers; the only valid
2093 // registers are the 4 used for parameters. We don't currently do this
2095 if (Subtarget->isThumb1Only())
2098 // Externally-defined functions with weak linkage should not be
2099 // tail-called on ARM when the OS does not support dynamic
2100 // pre-emption of symbols, as the AAELF spec requires normal calls
2101 // to undefined weak functions to be replaced with a NOP or jump to the
2102 // next instruction. The behaviour of branch instructions in this
2103 // situation (as used for tail calls) is implementation-defined, so we
2104 // cannot rely on the linker replacing the tail call with a return.
2105 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2106 const GlobalValue *GV = G->getGlobal();
2107 const Triple &TT = getTargetMachine().getTargetTriple();
2108 if (GV->hasExternalWeakLinkage() &&
2109 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2113 // If the calling conventions do not match, then we'd better make sure the
2114 // results are returned in the same way as what the caller expects.
2116 SmallVector<CCValAssign, 16> RVLocs1;
2117 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2118 *DAG.getContext(), Call);
2119 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2121 SmallVector<CCValAssign, 16> RVLocs2;
2122 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2123 *DAG.getContext(), Call);
2124 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2126 if (RVLocs1.size() != RVLocs2.size())
2128 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2129 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2131 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2133 if (RVLocs1[i].isRegLoc()) {
2134 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2137 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2143 // If Caller's vararg or byval argument has been split between registers and
2144 // stack, do not perform tail call, since part of the argument is in caller's
2146 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2147 getInfo<ARMFunctionInfo>();
2148 if (AFI_Caller->getArgRegsSaveSize())
2151 // If the callee takes no arguments then go on to check the results of the
2153 if (!Outs.empty()) {
2154 // Check if stack adjustment is needed. For now, do not do this if any
2155 // argument is passed on the stack.
2156 SmallVector<CCValAssign, 16> ArgLocs;
2157 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2158 *DAG.getContext(), Call);
2159 CCInfo.AnalyzeCallOperands(Outs,
2160 CCAssignFnForNode(CalleeCC, false, isVarArg));
2161 if (CCInfo.getNextStackOffset()) {
2162 MachineFunction &MF = DAG.getMachineFunction();
2164 // Check if the arguments are already laid out in the right way as
2165 // the caller's fixed stack objects.
2166 MachineFrameInfo *MFI = MF.getFrameInfo();
2167 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2168 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2169 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2171 ++i, ++realArgIdx) {
2172 CCValAssign &VA = ArgLocs[i];
2173 EVT RegVT = VA.getLocVT();
2174 SDValue Arg = OutVals[realArgIdx];
2175 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2176 if (VA.getLocInfo() == CCValAssign::Indirect)
2178 if (VA.needsCustom()) {
2179 // f64 and vector types are split into multiple registers or
2180 // register/stack-slot combinations. The types will not match
2181 // the registers; give up on memory f64 refs until we figure
2182 // out what to do about this.
2185 if (!ArgLocs[++i].isRegLoc())
2187 if (RegVT == MVT::v2f64) {
2188 if (!ArgLocs[++i].isRegLoc())
2190 if (!ArgLocs[++i].isRegLoc())
2193 } else if (!VA.isRegLoc()) {
2194 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2206 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2207 MachineFunction &MF, bool isVarArg,
2208 const SmallVectorImpl<ISD::OutputArg> &Outs,
2209 LLVMContext &Context) const {
2210 SmallVector<CCValAssign, 16> RVLocs;
2211 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2212 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2216 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2217 SDLoc DL, SelectionDAG &DAG) {
2218 const MachineFunction &MF = DAG.getMachineFunction();
2219 const Function *F = MF.getFunction();
2221 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2223 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2224 // version of the "preferred return address". These offsets affect the return
2225 // instruction if this is a return from PL1 without hypervisor extensions.
2226 // IRQ/FIQ: +4 "subs pc, lr, #4"
2227 // SWI: 0 "subs pc, lr, #0"
2228 // ABORT: +4 "subs pc, lr, #4"
2229 // UNDEF: +4/+2 "subs pc, lr, #0"
2230 // UNDEF varies depending on where the exception came from ARM or Thumb
2231 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2234 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2237 else if (IntKind == "SWI" || IntKind == "UNDEF")
2240 report_fatal_error("Unsupported interrupt attribute. If present, value "
2241 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2243 RetOps.insert(RetOps.begin() + 1,
2244 DAG.getConstant(LROffset, DL, MVT::i32, false));
2246 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2250 ARMTargetLowering::LowerReturn(SDValue Chain,
2251 CallingConv::ID CallConv, bool isVarArg,
2252 const SmallVectorImpl<ISD::OutputArg> &Outs,
2253 const SmallVectorImpl<SDValue> &OutVals,
2254 SDLoc dl, SelectionDAG &DAG) const {
2256 // CCValAssign - represent the assignment of the return value to a location.
2257 SmallVector<CCValAssign, 16> RVLocs;
2259 // CCState - Info about the registers and stack slots.
2260 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2261 *DAG.getContext(), Call);
2263 // Analyze outgoing return values.
2264 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2268 SmallVector<SDValue, 4> RetOps;
2269 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2270 bool isLittleEndian = Subtarget->isLittle();
2272 MachineFunction &MF = DAG.getMachineFunction();
2273 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2274 AFI->setReturnRegsCount(RVLocs.size());
2276 // Copy the result values into the output registers.
2277 for (unsigned i = 0, realRVLocIdx = 0;
2279 ++i, ++realRVLocIdx) {
2280 CCValAssign &VA = RVLocs[i];
2281 assert(VA.isRegLoc() && "Can only return in registers!");
2283 SDValue Arg = OutVals[realRVLocIdx];
2285 switch (VA.getLocInfo()) {
2286 default: llvm_unreachable("Unknown loc info!");
2287 case CCValAssign::Full: break;
2288 case CCValAssign::BCvt:
2289 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2293 if (VA.needsCustom()) {
2294 if (VA.getLocVT() == MVT::v2f64) {
2295 // Extract the first half and return it in two registers.
2296 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2297 DAG.getConstant(0, dl, MVT::i32));
2298 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2299 DAG.getVTList(MVT::i32, MVT::i32), Half);
2301 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2302 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2304 Flag = Chain.getValue(1);
2305 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2306 VA = RVLocs[++i]; // skip ahead to next loc
2307 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2308 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2310 Flag = Chain.getValue(1);
2311 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2312 VA = RVLocs[++i]; // skip ahead to next loc
2314 // Extract the 2nd half and fall through to handle it as an f64 value.
2315 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2316 DAG.getConstant(1, dl, MVT::i32));
2318 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2320 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2321 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2322 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2323 fmrrd.getValue(isLittleEndian ? 0 : 1),
2325 Flag = Chain.getValue(1);
2326 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2327 VA = RVLocs[++i]; // skip ahead to next loc
2328 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2329 fmrrd.getValue(isLittleEndian ? 1 : 0),
2332 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2334 // Guarantee that all emitted copies are
2335 // stuck together, avoiding something bad.
2336 Flag = Chain.getValue(1);
2337 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2340 // Update chain and glue.
2343 RetOps.push_back(Flag);
2345 // CPUs which aren't M-class use a special sequence to return from
2346 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2347 // though we use "subs pc, lr, #N").
2349 // M-class CPUs actually use a normal return sequence with a special
2350 // (hardware-provided) value in LR, so the normal code path works.
2351 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2352 !Subtarget->isMClass()) {
2353 if (Subtarget->isThumb1Only())
2354 report_fatal_error("interrupt attribute is not supported in Thumb1");
2355 return LowerInterruptReturn(RetOps, dl, DAG);
2358 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2361 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2362 if (N->getNumValues() != 1)
2364 if (!N->hasNUsesOfValue(1, 0))
2367 SDValue TCChain = Chain;
2368 SDNode *Copy = *N->use_begin();
2369 if (Copy->getOpcode() == ISD::CopyToReg) {
2370 // If the copy has a glue operand, we conservatively assume it isn't safe to
2371 // perform a tail call.
2372 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2374 TCChain = Copy->getOperand(0);
2375 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2376 SDNode *VMov = Copy;
2377 // f64 returned in a pair of GPRs.
2378 SmallPtrSet<SDNode*, 2> Copies;
2379 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2381 if (UI->getOpcode() != ISD::CopyToReg)
2385 if (Copies.size() > 2)
2388 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2390 SDValue UseChain = UI->getOperand(0);
2391 if (Copies.count(UseChain.getNode()))
2395 // We are at the top of this chain.
2396 // If the copy has a glue operand, we conservatively assume it
2397 // isn't safe to perform a tail call.
2398 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2404 } else if (Copy->getOpcode() == ISD::BITCAST) {
2405 // f32 returned in a single GPR.
2406 if (!Copy->hasOneUse())
2408 Copy = *Copy->use_begin();
2409 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2411 // If the copy has a glue operand, we conservatively assume it isn't safe to
2412 // perform a tail call.
2413 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2415 TCChain = Copy->getOperand(0);
2420 bool HasRet = false;
2421 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2423 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2424 UI->getOpcode() != ARMISD::INTRET_FLAG)
2436 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2437 if (!Subtarget->supportsTailCall())
2441 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2442 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2445 return !Subtarget->isThumb1Only();
2448 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2449 // and pass the lower and high parts through.
2450 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2452 SDValue WriteValue = Op->getOperand(2);
2454 // This function is only supposed to be called for i64 type argument.
2455 assert(WriteValue.getValueType() == MVT::i64
2456 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2458 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2459 DAG.getConstant(0, DL, MVT::i32));
2460 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2461 DAG.getConstant(1, DL, MVT::i32));
2462 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2463 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2466 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2467 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2468 // one of the above mentioned nodes. It has to be wrapped because otherwise
2469 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2470 // be used to form addressing mode. These wrapped nodes will be selected
2472 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2473 EVT PtrVT = Op.getValueType();
2474 // FIXME there is no actual debug info here
2476 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2478 if (CP->isMachineConstantPoolEntry())
2479 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2480 CP->getAlignment());
2482 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2483 CP->getAlignment());
2484 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2487 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2488 return MachineJumpTableInfo::EK_Inline;
2491 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2492 SelectionDAG &DAG) const {
2493 MachineFunction &MF = DAG.getMachineFunction();
2494 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2495 unsigned ARMPCLabelIndex = 0;
2497 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2498 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2499 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2501 if (RelocM == Reloc::Static) {
2502 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2504 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2505 ARMPCLabelIndex = AFI->createPICLabelUId();
2506 ARMConstantPoolValue *CPV =
2507 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2508 ARMCP::CPBlockAddress, PCAdj);
2509 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2511 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2513 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2514 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2515 false, false, false, 0);
2516 if (RelocM == Reloc::Static)
2518 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2519 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2522 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2524 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2525 SelectionDAG &DAG) const {
2527 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2528 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2529 MachineFunction &MF = DAG.getMachineFunction();
2530 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2531 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2532 ARMConstantPoolValue *CPV =
2533 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2534 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2535 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2536 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2538 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2539 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2540 false, false, false, 0);
2541 SDValue Chain = Argument.getValue(1);
2543 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2544 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2546 // call __tls_get_addr.
2549 Entry.Node = Argument;
2550 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2551 Args.push_back(Entry);
2553 // FIXME: is there useful debug info available here?
2554 TargetLowering::CallLoweringInfo CLI(DAG);
2555 CLI.setDebugLoc(dl).setChain(Chain)
2556 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2557 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2560 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2561 return CallResult.first;
2564 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2565 // "local exec" model.
2567 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2569 TLSModel::Model model) const {
2570 const GlobalValue *GV = GA->getGlobal();
2573 SDValue Chain = DAG.getEntryNode();
2574 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2575 // Get the Thread Pointer
2576 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2578 if (model == TLSModel::InitialExec) {
2579 MachineFunction &MF = DAG.getMachineFunction();
2580 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2581 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2582 // Initial exec model.
2583 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2584 ARMConstantPoolValue *CPV =
2585 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2586 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2588 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2589 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2590 Offset = DAG.getLoad(
2591 PtrVT, dl, Chain, Offset,
2592 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2594 Chain = Offset.getValue(1);
2596 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2597 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2599 Offset = DAG.getLoad(
2600 PtrVT, dl, Chain, Offset,
2601 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2605 assert(model == TLSModel::LocalExec);
2606 ARMConstantPoolValue *CPV =
2607 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2608 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2609 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2610 Offset = DAG.getLoad(
2611 PtrVT, dl, Chain, Offset,
2612 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2616 // The address of the thread local variable is the add of the thread
2617 // pointer with the offset of the variable.
2618 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2622 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2623 // TODO: implement the "local dynamic" model
2624 assert(Subtarget->isTargetELF() &&
2625 "TLS not implemented for non-ELF targets");
2626 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2627 if (DAG.getTarget().Options.EmulatedTLS)
2628 return LowerToTLSEmulatedModel(GA, DAG);
2630 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2633 case TLSModel::GeneralDynamic:
2634 case TLSModel::LocalDynamic:
2635 return LowerToTLSGeneralDynamicModel(GA, DAG);
2636 case TLSModel::InitialExec:
2637 case TLSModel::LocalExec:
2638 return LowerToTLSExecModels(GA, DAG, model);
2640 llvm_unreachable("bogus TLS model");
2643 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2644 SelectionDAG &DAG) const {
2645 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2647 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2648 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2649 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2650 ARMConstantPoolValue *CPV =
2651 ARMConstantPoolConstant::Create(GV,
2652 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2653 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2654 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2655 SDValue Result = DAG.getLoad(
2656 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2657 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2659 SDValue Chain = Result.getValue(1);
2660 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2661 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2663 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2664 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2665 false, false, false, 0);
2669 // If we have T2 ops, we can materialize the address directly via movt/movw
2670 // pair. This is always cheaper.
2671 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2673 // FIXME: Once remat is capable of dealing with instructions with register
2674 // operands, expand this into two nodes.
2675 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2676 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2678 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2679 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2681 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2682 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2687 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2688 SelectionDAG &DAG) const {
2689 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2691 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2692 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2694 if (Subtarget->useMovt(DAG.getMachineFunction()))
2697 // FIXME: Once remat is capable of dealing with instructions with register
2698 // operands, expand this into multiple nodes
2700 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2702 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2703 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2705 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2706 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2707 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2708 false, false, false, 0);
2712 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2713 SelectionDAG &DAG) const {
2714 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2715 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2716 "Windows on ARM expects to use movw/movt");
2718 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2719 const ARMII::TOF TargetFlags =
2720 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2721 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2727 // FIXME: Once remat is capable of dealing with instructions with register
2728 // operands, expand this into two nodes.
2729 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2730 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2732 if (GV->hasDLLImportStorageClass())
2733 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2734 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2735 false, false, false, 0);
2739 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2740 SelectionDAG &DAG) const {
2741 assert(Subtarget->isTargetELF() &&
2742 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2743 MachineFunction &MF = DAG.getMachineFunction();
2744 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2745 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2746 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2748 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2749 ARMConstantPoolValue *CPV =
2750 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2751 ARMPCLabelIndex, PCAdj);
2752 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2753 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2755 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2756 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2757 false, false, false, 0);
2758 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2759 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2763 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2765 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2766 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2767 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2768 Op.getOperand(1), Val);
2772 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2774 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2775 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2778 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2779 SelectionDAG &DAG) const {
2781 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2786 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2787 const ARMSubtarget *Subtarget) const {
2788 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2791 default: return SDValue(); // Don't custom lower most intrinsics.
2792 case Intrinsic::arm_rbit: {
2793 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2794 "RBIT intrinsic must have i32 type!");
2795 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2797 case Intrinsic::arm_thread_pointer: {
2798 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2799 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2801 case Intrinsic::eh_sjlj_lsda: {
2802 MachineFunction &MF = DAG.getMachineFunction();
2803 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2804 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2805 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2806 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2808 unsigned PCAdj = (RelocM != Reloc::PIC_)
2809 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2810 ARMConstantPoolValue *CPV =
2811 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2812 ARMCP::CPLSDA, PCAdj);
2813 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2814 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2815 SDValue Result = DAG.getLoad(
2816 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2817 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2820 if (RelocM == Reloc::PIC_) {
2821 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2822 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2826 case Intrinsic::arm_neon_vmulls:
2827 case Intrinsic::arm_neon_vmullu: {
2828 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2829 ? ARMISD::VMULLs : ARMISD::VMULLu;
2830 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2831 Op.getOperand(1), Op.getOperand(2));
2833 case Intrinsic::arm_neon_vminnm:
2834 case Intrinsic::arm_neon_vmaxnm: {
2835 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2836 ? ISD::FMINNUM : ISD::FMAXNUM;
2837 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2838 Op.getOperand(1), Op.getOperand(2));
2840 case Intrinsic::arm_neon_vminu:
2841 case Intrinsic::arm_neon_vmaxu: {
2842 if (Op.getValueType().isFloatingPoint())
2844 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2845 ? ISD::UMIN : ISD::UMAX;
2846 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2847 Op.getOperand(1), Op.getOperand(2));
2849 case Intrinsic::arm_neon_vmins:
2850 case Intrinsic::arm_neon_vmaxs: {
2851 // v{min,max}s is overloaded between signed integers and floats.
2852 if (!Op.getValueType().isFloatingPoint()) {
2853 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2854 ? ISD::SMIN : ISD::SMAX;
2855 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2856 Op.getOperand(1), Op.getOperand(2));
2858 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2859 ? ISD::FMINNAN : ISD::FMAXNAN;
2860 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2861 Op.getOperand(1), Op.getOperand(2));
2866 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2867 const ARMSubtarget *Subtarget) {
2868 // FIXME: handle "fence singlethread" more efficiently.
2870 if (!Subtarget->hasDataBarrier()) {
2871 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2872 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2874 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2875 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2876 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2877 DAG.getConstant(0, dl, MVT::i32));
2880 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2881 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2882 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2883 if (Subtarget->isMClass()) {
2884 // Only a full system barrier exists in the M-class architectures.
2885 Domain = ARM_MB::SY;
2886 } else if (Subtarget->isSwift() && Ord == Release) {
2887 // Swift happens to implement ISHST barriers in a way that's compatible with
2888 // Release semantics but weaker than ISH so we'd be fools not to use
2889 // it. Beware: other processors probably don't!
2890 Domain = ARM_MB::ISHST;
2893 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2894 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2895 DAG.getConstant(Domain, dl, MVT::i32));
2898 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2899 const ARMSubtarget *Subtarget) {
2900 // ARM pre v5TE and Thumb1 does not have preload instructions.
2901 if (!(Subtarget->isThumb2() ||
2902 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2903 // Just preserve the chain.
2904 return Op.getOperand(0);
2907 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2909 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2910 // ARMv7 with MP extension has PLDW.
2911 return Op.getOperand(0);
2913 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2914 if (Subtarget->isThumb()) {
2916 isRead = ~isRead & 1;
2917 isData = ~isData & 1;
2920 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2921 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2922 DAG.getConstant(isData, dl, MVT::i32));
2925 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2926 MachineFunction &MF = DAG.getMachineFunction();
2927 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2929 // vastart just stores the address of the VarArgsFrameIndex slot into the
2930 // memory location argument.
2932 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2933 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2934 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2935 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2936 MachinePointerInfo(SV), false, false, 0);
2940 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2941 SDValue &Root, SelectionDAG &DAG,
2943 MachineFunction &MF = DAG.getMachineFunction();
2944 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2946 const TargetRegisterClass *RC;
2947 if (AFI->isThumb1OnlyFunction())
2948 RC = &ARM::tGPRRegClass;
2950 RC = &ARM::GPRRegClass;
2952 // Transform the arguments stored in physical registers into virtual ones.
2953 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2954 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2957 if (NextVA.isMemLoc()) {
2958 MachineFrameInfo *MFI = MF.getFrameInfo();
2959 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2961 // Create load node to retrieve arguments from the stack.
2962 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2963 ArgValue2 = DAG.getLoad(
2964 MVT::i32, dl, Root, FIN,
2965 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2968 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2969 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2971 if (!Subtarget->isLittle())
2972 std::swap (ArgValue, ArgValue2);
2973 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2976 // The remaining GPRs hold either the beginning of variable-argument
2977 // data, or the beginning of an aggregate passed by value (usually
2978 // byval). Either way, we allocate stack slots adjacent to the data
2979 // provided by our caller, and store the unallocated registers there.
2980 // If this is a variadic function, the va_list pointer will begin with
2981 // these values; otherwise, this reassembles a (byval) structure that
2982 // was split between registers and memory.
2983 // Return: The frame index registers were stored into.
2985 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2986 SDLoc dl, SDValue &Chain,
2987 const Value *OrigArg,
2988 unsigned InRegsParamRecordIdx,
2990 unsigned ArgSize) const {
2991 // Currently, two use-cases possible:
2992 // Case #1. Non-var-args function, and we meet first byval parameter.
2993 // Setup first unallocated register as first byval register;
2994 // eat all remained registers
2995 // (these two actions are performed by HandleByVal method).
2996 // Then, here, we initialize stack frame with
2997 // "store-reg" instructions.
2998 // Case #2. Var-args function, that doesn't contain byval parameters.
2999 // The same: eat all remained unallocated registers,
3000 // initialize stack frame.
3002 MachineFunction &MF = DAG.getMachineFunction();
3003 MachineFrameInfo *MFI = MF.getFrameInfo();
3004 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3005 unsigned RBegin, REnd;
3006 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3007 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3009 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3010 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3015 ArgOffset = -4 * (ARM::R4 - RBegin);
3017 auto PtrVT = getPointerTy(DAG.getDataLayout());
3018 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3019 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3021 SmallVector<SDValue, 4> MemOps;
3022 const TargetRegisterClass *RC =
3023 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3025 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3026 unsigned VReg = MF.addLiveIn(Reg, RC);
3027 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3029 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3030 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3031 MemOps.push_back(Store);
3032 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3035 if (!MemOps.empty())
3036 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3040 // Setup stack frame, the va_list pointer will start from.
3042 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3043 SDLoc dl, SDValue &Chain,
3045 unsigned TotalArgRegsSaveSize,
3046 bool ForceMutable) const {
3047 MachineFunction &MF = DAG.getMachineFunction();
3048 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3050 // Try to store any remaining integer argument regs
3051 // to their spots on the stack so that they may be loaded by deferencing
3052 // the result of va_next.
3053 // If there is no regs to be stored, just point address after last
3054 // argument passed via stack.
3055 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3056 CCInfo.getInRegsParamsCount(),
3057 CCInfo.getNextStackOffset(), 4);
3058 AFI->setVarArgsFrameIndex(FrameIndex);
3062 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3063 CallingConv::ID CallConv, bool isVarArg,
3064 const SmallVectorImpl<ISD::InputArg>
3066 SDLoc dl, SelectionDAG &DAG,
3067 SmallVectorImpl<SDValue> &InVals)
3069 MachineFunction &MF = DAG.getMachineFunction();
3070 MachineFrameInfo *MFI = MF.getFrameInfo();
3072 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3074 // Assign locations to all of the incoming arguments.
3075 SmallVector<CCValAssign, 16> ArgLocs;
3076 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3077 *DAG.getContext(), Prologue);
3078 CCInfo.AnalyzeFormalArguments(Ins,
3079 CCAssignFnForNode(CallConv, /* Return*/ false,
3082 SmallVector<SDValue, 16> ArgValues;
3084 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3085 unsigned CurArgIdx = 0;
3087 // Initially ArgRegsSaveSize is zero.
3088 // Then we increase this value each time we meet byval parameter.
3089 // We also increase this value in case of varargs function.
3090 AFI->setArgRegsSaveSize(0);
3092 // Calculate the amount of stack space that we need to allocate to store
3093 // byval and variadic arguments that are passed in registers.
3094 // We need to know this before we allocate the first byval or variadic
3095 // argument, as they will be allocated a stack slot below the CFA (Canonical
3096 // Frame Address, the stack pointer at entry to the function).
3097 unsigned ArgRegBegin = ARM::R4;
3098 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3099 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3102 CCValAssign &VA = ArgLocs[i];
3103 unsigned Index = VA.getValNo();
3104 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3105 if (!Flags.isByVal())
3108 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3109 unsigned RBegin, REnd;
3110 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3111 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3113 CCInfo.nextInRegsParam();
3115 CCInfo.rewindByValRegsInfo();
3117 int lastInsIndex = -1;
3118 if (isVarArg && MFI->hasVAStart()) {
3119 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3120 if (RegIdx != array_lengthof(GPRArgRegs))
3121 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3124 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3125 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3126 auto PtrVT = getPointerTy(DAG.getDataLayout());
3128 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3129 CCValAssign &VA = ArgLocs[i];
3130 if (Ins[VA.getValNo()].isOrigArg()) {
3131 std::advance(CurOrigArg,
3132 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3133 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3135 // Arguments stored in registers.
3136 if (VA.isRegLoc()) {
3137 EVT RegVT = VA.getLocVT();
3139 if (VA.needsCustom()) {
3140 // f64 and vector types are split up into multiple registers or
3141 // combinations of registers and stack slots.
3142 if (VA.getLocVT() == MVT::v2f64) {
3143 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3145 VA = ArgLocs[++i]; // skip ahead to next loc
3147 if (VA.isMemLoc()) {
3148 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3149 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3150 ArgValue2 = DAG.getLoad(
3151 MVT::f64, dl, Chain, FIN,
3152 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3153 false, false, false, 0);
3155 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3158 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3159 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3160 ArgValue, ArgValue1,
3161 DAG.getIntPtrConstant(0, dl));
3162 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3163 ArgValue, ArgValue2,
3164 DAG.getIntPtrConstant(1, dl));
3166 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3169 const TargetRegisterClass *RC;
3171 if (RegVT == MVT::f32)
3172 RC = &ARM::SPRRegClass;
3173 else if (RegVT == MVT::f64)
3174 RC = &ARM::DPRRegClass;
3175 else if (RegVT == MVT::v2f64)
3176 RC = &ARM::QPRRegClass;
3177 else if (RegVT == MVT::i32)
3178 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3179 : &ARM::GPRRegClass;
3181 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3183 // Transform the arguments in physical registers into virtual ones.
3184 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3185 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3188 // If this is an 8 or 16-bit value, it is really passed promoted
3189 // to 32 bits. Insert an assert[sz]ext to capture this, then
3190 // truncate to the right size.
3191 switch (VA.getLocInfo()) {
3192 default: llvm_unreachable("Unknown loc info!");
3193 case CCValAssign::Full: break;
3194 case CCValAssign::BCvt:
3195 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3197 case CCValAssign::SExt:
3198 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3199 DAG.getValueType(VA.getValVT()));
3200 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3202 case CCValAssign::ZExt:
3203 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3204 DAG.getValueType(VA.getValVT()));
3205 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3209 InVals.push_back(ArgValue);
3211 } else { // VA.isRegLoc()
3214 assert(VA.isMemLoc());
3215 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3217 int index = VA.getValNo();
3219 // Some Ins[] entries become multiple ArgLoc[] entries.
3220 // Process them only once.
3221 if (index != lastInsIndex)
3223 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3224 // FIXME: For now, all byval parameter objects are marked mutable.
3225 // This can be changed with more analysis.
3226 // In case of tail call optimization mark all arguments mutable.
3227 // Since they could be overwritten by lowering of arguments in case of
3229 if (Flags.isByVal()) {
3230 assert(Ins[index].isOrigArg() &&
3231 "Byval arguments cannot be implicit");
3232 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3234 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3235 CurByValIndex, VA.getLocMemOffset(),
3236 Flags.getByValSize());
3237 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3238 CCInfo.nextInRegsParam();
3240 unsigned FIOffset = VA.getLocMemOffset();
3241 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3244 // Create load nodes to retrieve arguments from the stack.
3245 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3246 InVals.push_back(DAG.getLoad(
3247 VA.getValVT(), dl, Chain, FIN,
3248 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3249 false, false, false, 0));
3251 lastInsIndex = index;
3257 if (isVarArg && MFI->hasVAStart())
3258 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3259 CCInfo.getNextStackOffset(),
3260 TotalArgRegsSaveSize);
3262 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3267 /// isFloatingPointZero - Return true if this is +0.0.
3268 static bool isFloatingPointZero(SDValue Op) {
3269 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3270 return CFP->getValueAPF().isPosZero();
3271 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3272 // Maybe this has already been legalized into the constant pool?
3273 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3274 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3275 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3276 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3277 return CFP->getValueAPF().isPosZero();
3279 } else if (Op->getOpcode() == ISD::BITCAST &&
3280 Op->getValueType(0) == MVT::f64) {
3281 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3282 // created by LowerConstantFP().
3283 SDValue BitcastOp = Op->getOperand(0);
3284 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3285 SDValue MoveOp = BitcastOp->getOperand(0);
3286 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3287 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3295 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3296 /// the given operands.
3298 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3299 SDValue &ARMcc, SelectionDAG &DAG,
3301 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3302 unsigned C = RHSC->getZExtValue();
3303 if (!isLegalICmpImmediate(C)) {
3304 // Constant does not fit, try adjusting it by one?
3309 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3310 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3311 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3316 if (C != 0 && isLegalICmpImmediate(C-1)) {
3317 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3318 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3323 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3324 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3325 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3330 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3331 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3332 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3339 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3340 ARMISD::NodeType CompareType;
3343 CompareType = ARMISD::CMP;
3348 CompareType = ARMISD::CMPZ;
3351 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3352 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3355 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3357 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3359 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3361 if (!isFloatingPointZero(RHS))
3362 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3364 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3365 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3368 /// duplicateCmp - Glue values can have only one use, so this function
3369 /// duplicates a comparison node.
3371 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3372 unsigned Opc = Cmp.getOpcode();
3374 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3375 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3377 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3378 Cmp = Cmp.getOperand(0);
3379 Opc = Cmp.getOpcode();
3380 if (Opc == ARMISD::CMPFP)
3381 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3383 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3384 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3386 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3389 std::pair<SDValue, SDValue>
3390 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3391 SDValue &ARMcc) const {
3392 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3394 SDValue Value, OverflowCmp;
3395 SDValue LHS = Op.getOperand(0);
3396 SDValue RHS = Op.getOperand(1);
3399 // FIXME: We are currently always generating CMPs because we don't support
3400 // generating CMN through the backend. This is not as good as the natural
3401 // CMP case because it causes a register dependency and cannot be folded
3404 switch (Op.getOpcode()) {
3406 llvm_unreachable("Unknown overflow instruction!");
3408 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3409 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3410 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3413 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3414 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3415 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3418 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3419 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3420 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3423 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3424 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3425 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3429 return std::make_pair(Value, OverflowCmp);
3434 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3435 // Let legalize expand this if it isn't a legal type yet.
3436 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3439 SDValue Value, OverflowCmp;
3441 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3442 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3444 // We use 0 and 1 as false and true values.
3445 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3446 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3447 EVT VT = Op.getValueType();
3449 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3450 ARMcc, CCR, OverflowCmp);
3452 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3453 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3457 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3458 SDValue Cond = Op.getOperand(0);
3459 SDValue SelectTrue = Op.getOperand(1);
3460 SDValue SelectFalse = Op.getOperand(2);
3462 unsigned Opc = Cond.getOpcode();
3464 if (Cond.getResNo() == 1 &&
3465 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3466 Opc == ISD::USUBO)) {
3467 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3470 SDValue Value, OverflowCmp;
3472 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3473 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3474 EVT VT = Op.getValueType();
3476 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3482 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3483 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3485 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3486 const ConstantSDNode *CMOVTrue =
3487 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3488 const ConstantSDNode *CMOVFalse =
3489 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3491 if (CMOVTrue && CMOVFalse) {
3492 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3493 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3497 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3499 False = SelectFalse;
3500 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3505 if (True.getNode() && False.getNode()) {
3506 EVT VT = Op.getValueType();
3507 SDValue ARMcc = Cond.getOperand(2);
3508 SDValue CCR = Cond.getOperand(3);
3509 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3510 assert(True.getValueType() == VT);
3511 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3516 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3517 // undefined bits before doing a full-word comparison with zero.
3518 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3519 DAG.getConstant(1, dl, Cond.getValueType()));
3521 return DAG.getSelectCC(dl, Cond,
3522 DAG.getConstant(0, dl, Cond.getValueType()),
3523 SelectTrue, SelectFalse, ISD::SETNE);
3526 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3527 bool &swpCmpOps, bool &swpVselOps) {
3528 // Start by selecting the GE condition code for opcodes that return true for
3530 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3532 CondCode = ARMCC::GE;
3534 // and GT for opcodes that return false for 'equality'.
3535 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3537 CondCode = ARMCC::GT;
3539 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3540 // to swap the compare operands.
3541 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3545 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3546 // If we have an unordered opcode, we need to swap the operands to the VSEL
3547 // instruction (effectively negating the condition).
3549 // This also has the effect of swapping which one of 'less' or 'greater'
3550 // returns true, so we also swap the compare operands. It also switches
3551 // whether we return true for 'equality', so we compensate by picking the
3552 // opposite condition code to our original choice.
3553 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3554 CC == ISD::SETUGT) {
3555 swpCmpOps = !swpCmpOps;
3556 swpVselOps = !swpVselOps;
3557 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3560 // 'ordered' is 'anything but unordered', so use the VS condition code and
3561 // swap the VSEL operands.
3562 if (CC == ISD::SETO) {
3563 CondCode = ARMCC::VS;
3567 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3568 // code and swap the VSEL operands.
3569 if (CC == ISD::SETUNE) {
3570 CondCode = ARMCC::EQ;
3575 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3576 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3577 SDValue Cmp, SelectionDAG &DAG) const {
3578 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3579 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3580 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3581 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3582 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3584 SDValue TrueLow = TrueVal.getValue(0);
3585 SDValue TrueHigh = TrueVal.getValue(1);
3586 SDValue FalseLow = FalseVal.getValue(0);
3587 SDValue FalseHigh = FalseVal.getValue(1);
3589 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3591 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3592 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3594 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3596 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3601 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3602 EVT VT = Op.getValueType();
3603 SDValue LHS = Op.getOperand(0);
3604 SDValue RHS = Op.getOperand(1);
3605 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3606 SDValue TrueVal = Op.getOperand(2);
3607 SDValue FalseVal = Op.getOperand(3);
3610 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3611 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3614 // If softenSetCCOperands only returned one value, we should compare it to
3616 if (!RHS.getNode()) {
3617 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3622 if (LHS.getValueType() == MVT::i32) {
3623 // Try to generate VSEL on ARMv8.
3624 // The VSEL instruction can't use all the usual ARM condition
3625 // codes: it only has two bits to select the condition code, so it's
3626 // constrained to use only GE, GT, VS and EQ.
3628 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3629 // swap the operands of the previous compare instruction (effectively
3630 // inverting the compare condition, swapping 'less' and 'greater') and
3631 // sometimes need to swap the operands to the VSEL (which inverts the
3632 // condition in the sense of firing whenever the previous condition didn't)
3633 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3634 TrueVal.getValueType() == MVT::f64)) {
3635 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3636 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3637 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3638 CC = ISD::getSetCCInverse(CC, true);
3639 std::swap(TrueVal, FalseVal);
3644 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3645 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3646 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3649 ARMCC::CondCodes CondCode, CondCode2;
3650 FPCCToARMCC(CC, CondCode, CondCode2);
3652 // Try to generate VMAXNM/VMINNM on ARMv8.
3653 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3654 TrueVal.getValueType() == MVT::f64)) {
3655 bool swpCmpOps = false;
3656 bool swpVselOps = false;
3657 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3659 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3660 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3662 std::swap(LHS, RHS);
3664 std::swap(TrueVal, FalseVal);
3668 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3669 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3670 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3671 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3672 if (CondCode2 != ARMCC::AL) {
3673 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3674 // FIXME: Needs another CMP because flag can have but one use.
3675 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3676 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3681 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3682 /// to morph to an integer compare sequence.
3683 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3684 const ARMSubtarget *Subtarget) {
3685 SDNode *N = Op.getNode();
3686 if (!N->hasOneUse())
3687 // Otherwise it requires moving the value from fp to integer registers.
3689 if (!N->getNumValues())
3691 EVT VT = Op.getValueType();
3692 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3693 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3694 // vmrs are very slow, e.g. cortex-a8.
3697 if (isFloatingPointZero(Op)) {
3701 return ISD::isNormalLoad(N);
3704 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3705 if (isFloatingPointZero(Op))
3706 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3708 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3709 return DAG.getLoad(MVT::i32, SDLoc(Op),
3710 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3711 Ld->isVolatile(), Ld->isNonTemporal(),
3712 Ld->isInvariant(), Ld->getAlignment());
3714 llvm_unreachable("Unknown VFP cmp argument!");
3717 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3718 SDValue &RetVal1, SDValue &RetVal2) {
3721 if (isFloatingPointZero(Op)) {
3722 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3723 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3727 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3728 SDValue Ptr = Ld->getBasePtr();
3729 RetVal1 = DAG.getLoad(MVT::i32, dl,
3730 Ld->getChain(), Ptr,
3731 Ld->getPointerInfo(),
3732 Ld->isVolatile(), Ld->isNonTemporal(),
3733 Ld->isInvariant(), Ld->getAlignment());
3735 EVT PtrType = Ptr.getValueType();
3736 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3737 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3738 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3739 RetVal2 = DAG.getLoad(MVT::i32, dl,
3740 Ld->getChain(), NewPtr,
3741 Ld->getPointerInfo().getWithOffset(4),
3742 Ld->isVolatile(), Ld->isNonTemporal(),
3743 Ld->isInvariant(), NewAlign);
3747 llvm_unreachable("Unknown VFP cmp argument!");
3750 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3751 /// f32 and even f64 comparisons to integer ones.
3753 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3754 SDValue Chain = Op.getOperand(0);
3755 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3756 SDValue LHS = Op.getOperand(2);
3757 SDValue RHS = Op.getOperand(3);
3758 SDValue Dest = Op.getOperand(4);
3761 bool LHSSeenZero = false;
3762 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3763 bool RHSSeenZero = false;
3764 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3765 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3766 // If unsafe fp math optimization is enabled and there are no other uses of
3767 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3768 // to an integer comparison.
3769 if (CC == ISD::SETOEQ)
3771 else if (CC == ISD::SETUNE)
3774 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3776 if (LHS.getValueType() == MVT::f32) {
3777 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3778 bitcastf32Toi32(LHS, DAG), Mask);
3779 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3780 bitcastf32Toi32(RHS, DAG), Mask);
3781 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3782 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3783 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3784 Chain, Dest, ARMcc, CCR, Cmp);
3789 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3790 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3791 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3792 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3793 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3794 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3795 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3796 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3797 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3803 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3804 SDValue Chain = Op.getOperand(0);
3805 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3806 SDValue LHS = Op.getOperand(2);
3807 SDValue RHS = Op.getOperand(3);
3808 SDValue Dest = Op.getOperand(4);
3811 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3812 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3815 // If softenSetCCOperands only returned one value, we should compare it to
3817 if (!RHS.getNode()) {
3818 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3823 if (LHS.getValueType() == MVT::i32) {
3825 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3826 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3827 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3828 Chain, Dest, ARMcc, CCR, Cmp);
3831 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3833 if (getTargetMachine().Options.UnsafeFPMath &&
3834 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3835 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3836 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3837 if (Result.getNode())
3841 ARMCC::CondCodes CondCode, CondCode2;
3842 FPCCToARMCC(CC, CondCode, CondCode2);
3844 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3845 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3846 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3847 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3848 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3849 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3850 if (CondCode2 != ARMCC::AL) {
3851 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3852 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3853 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3858 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3859 SDValue Chain = Op.getOperand(0);
3860 SDValue Table = Op.getOperand(1);
3861 SDValue Index = Op.getOperand(2);
3864 EVT PTy = getPointerTy(DAG.getDataLayout());
3865 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3866 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3867 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3868 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3869 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3870 if (Subtarget->isThumb2()) {
3871 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3872 // which does another jump to the destination. This also makes it easier
3873 // to translate it to TBB / TBH later.
3874 // FIXME: This might not work if the function is extremely large.
3875 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3876 Addr, Op.getOperand(2), JTI);
3878 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3880 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3881 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3882 false, false, false, 0);
3883 Chain = Addr.getValue(1);
3884 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3885 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3888 DAG.getLoad(PTy, dl, Chain, Addr,
3889 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3890 false, false, false, 0);
3891 Chain = Addr.getValue(1);
3892 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3896 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3897 EVT VT = Op.getValueType();
3900 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3901 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3903 return DAG.UnrollVectorOp(Op.getNode());
3906 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3907 "Invalid type for custom lowering!");
3908 if (VT != MVT::v4i16)
3909 return DAG.UnrollVectorOp(Op.getNode());
3911 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3912 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3915 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3916 EVT VT = Op.getValueType();
3918 return LowerVectorFP_TO_INT(Op, DAG);
3919 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3921 if (Op.getOpcode() == ISD::FP_TO_SINT)
3922 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3925 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3927 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3928 /*isSigned*/ false, SDLoc(Op)).first;
3934 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3935 EVT VT = Op.getValueType();
3938 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3939 if (VT.getVectorElementType() == MVT::f32)
3941 return DAG.UnrollVectorOp(Op.getNode());
3944 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3945 "Invalid type for custom lowering!");
3946 if (VT != MVT::v4f32)
3947 return DAG.UnrollVectorOp(Op.getNode());
3951 switch (Op.getOpcode()) {
3952 default: llvm_unreachable("Invalid opcode!");
3953 case ISD::SINT_TO_FP:
3954 CastOpc = ISD::SIGN_EXTEND;
3955 Opc = ISD::SINT_TO_FP;
3957 case ISD::UINT_TO_FP:
3958 CastOpc = ISD::ZERO_EXTEND;
3959 Opc = ISD::UINT_TO_FP;
3963 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3964 return DAG.getNode(Opc, dl, VT, Op);
3967 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3968 EVT VT = Op.getValueType();
3970 return LowerVectorINT_TO_FP(Op, DAG);
3971 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3973 if (Op.getOpcode() == ISD::SINT_TO_FP)
3974 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3977 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3979 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3980 /*isSigned*/ false, SDLoc(Op)).first;
3986 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3987 // Implement fcopysign with a fabs and a conditional fneg.
3988 SDValue Tmp0 = Op.getOperand(0);
3989 SDValue Tmp1 = Op.getOperand(1);
3991 EVT VT = Op.getValueType();
3992 EVT SrcVT = Tmp1.getValueType();
3993 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3994 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3995 bool UseNEON = !InGPR && Subtarget->hasNEON();
3998 // Use VBSL to copy the sign bit.
3999 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4000 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4001 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4002 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4004 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4005 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4006 DAG.getConstant(32, dl, MVT::i32));
4007 else /*if (VT == MVT::f32)*/
4008 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4009 if (SrcVT == MVT::f32) {
4010 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4012 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4013 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4014 DAG.getConstant(32, dl, MVT::i32));
4015 } else if (VT == MVT::f32)
4016 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4017 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4018 DAG.getConstant(32, dl, MVT::i32));
4019 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4020 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4022 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4024 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4025 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4026 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4028 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4029 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4030 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4031 if (VT == MVT::f32) {
4032 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4033 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4034 DAG.getConstant(0, dl, MVT::i32));
4036 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4042 // Bitcast operand 1 to i32.
4043 if (SrcVT == MVT::f64)
4044 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4046 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4048 // Or in the signbit with integer operations.
4049 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4050 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4051 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4052 if (VT == MVT::f32) {
4053 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4054 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4055 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4056 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4059 // f64: Or the high part with signbit and then combine two parts.
4060 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4062 SDValue Lo = Tmp0.getValue(0);
4063 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4064 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4065 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4068 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4069 MachineFunction &MF = DAG.getMachineFunction();
4070 MachineFrameInfo *MFI = MF.getFrameInfo();
4071 MFI->setReturnAddressIsTaken(true);
4073 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4076 EVT VT = Op.getValueType();
4078 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4080 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4081 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4082 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4083 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4084 MachinePointerInfo(), false, false, false, 0);
4087 // Return LR, which contains the return address. Mark it an implicit live-in.
4088 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4089 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4092 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4093 const ARMBaseRegisterInfo &ARI =
4094 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4095 MachineFunction &MF = DAG.getMachineFunction();
4096 MachineFrameInfo *MFI = MF.getFrameInfo();
4097 MFI->setFrameAddressIsTaken(true);
4099 EVT VT = Op.getValueType();
4100 SDLoc dl(Op); // FIXME probably not meaningful
4101 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4102 unsigned FrameReg = ARI.getFrameRegister(MF);
4103 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4105 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4106 MachinePointerInfo(),
4107 false, false, false, 0);
4111 // FIXME? Maybe this could be a TableGen attribute on some registers and
4112 // this table could be generated automatically from RegInfo.
4113 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4114 SelectionDAG &DAG) const {
4115 unsigned Reg = StringSwitch<unsigned>(RegName)
4116 .Case("sp", ARM::SP)
4120 report_fatal_error(Twine("Invalid register name \""
4121 + StringRef(RegName) + "\"."));
4124 // Result is 64 bit value so split into two 32 bit values and return as a
4126 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4127 SelectionDAG &DAG) {
4130 // This function is only supposed to be called for i64 type destination.
4131 assert(N->getValueType(0) == MVT::i64
4132 && "ExpandREAD_REGISTER called for non-i64 type result.");
4134 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4135 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4139 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4141 Results.push_back(Read.getOperand(0));
4144 /// ExpandBITCAST - If the target supports VFP, this function is called to
4145 /// expand a bit convert where either the source or destination type is i64 to
4146 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4147 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4148 /// vectors), since the legalizer won't know what to do with that.
4149 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4150 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4152 SDValue Op = N->getOperand(0);
4154 // This function is only supposed to be called for i64 types, either as the
4155 // source or destination of the bit convert.
4156 EVT SrcVT = Op.getValueType();
4157 EVT DstVT = N->getValueType(0);
4158 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4159 "ExpandBITCAST called for non-i64 type");
4161 // Turn i64->f64 into VMOVDRR.
4162 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4163 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4164 DAG.getConstant(0, dl, MVT::i32));
4165 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4166 DAG.getConstant(1, dl, MVT::i32));
4167 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4168 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4171 // Turn f64->i64 into VMOVRRD.
4172 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4174 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4175 SrcVT.getVectorNumElements() > 1)
4176 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4177 DAG.getVTList(MVT::i32, MVT::i32),
4178 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4180 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4181 DAG.getVTList(MVT::i32, MVT::i32), Op);
4182 // Merge the pieces into a single i64 value.
4183 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4189 /// getZeroVector - Returns a vector of specified type with all zero elements.
4190 /// Zero vectors are used to represent vector negation and in those cases
4191 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4192 /// not support i64 elements, so sometimes the zero vectors will need to be
4193 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4195 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4196 assert(VT.isVector() && "Expected a vector type");
4197 // The canonical modified immediate encoding of a zero vector is....0!
4198 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4199 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4200 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4201 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4204 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4205 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4206 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4207 SelectionDAG &DAG) const {
4208 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4209 EVT VT = Op.getValueType();
4210 unsigned VTBits = VT.getSizeInBits();
4212 SDValue ShOpLo = Op.getOperand(0);
4213 SDValue ShOpHi = Op.getOperand(1);
4214 SDValue ShAmt = Op.getOperand(2);
4216 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4218 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4220 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4221 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4222 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4223 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4224 DAG.getConstant(VTBits, dl, MVT::i32));
4225 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4226 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4227 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4229 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4230 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4231 ISD::SETGE, ARMcc, DAG, dl);
4232 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4233 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4236 SDValue Ops[2] = { Lo, Hi };
4237 return DAG.getMergeValues(Ops, dl);
4240 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4241 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4242 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4243 SelectionDAG &DAG) const {
4244 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4245 EVT VT = Op.getValueType();
4246 unsigned VTBits = VT.getSizeInBits();
4248 SDValue ShOpLo = Op.getOperand(0);
4249 SDValue ShOpHi = Op.getOperand(1);
4250 SDValue ShAmt = Op.getOperand(2);
4253 assert(Op.getOpcode() == ISD::SHL_PARTS);
4254 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4255 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4256 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4257 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4258 DAG.getConstant(VTBits, dl, MVT::i32));
4259 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4260 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4262 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4263 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4264 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4265 ISD::SETGE, ARMcc, DAG, dl);
4266 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4267 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4270 SDValue Ops[2] = { Lo, Hi };
4271 return DAG.getMergeValues(Ops, dl);
4274 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4275 SelectionDAG &DAG) const {
4276 // The rounding mode is in bits 23:22 of the FPSCR.
4277 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4278 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4279 // so that the shift + and get folded into a bitfield extract.
4281 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4282 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4284 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4285 DAG.getConstant(1U << 22, dl, MVT::i32));
4286 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4287 DAG.getConstant(22, dl, MVT::i32));
4288 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4289 DAG.getConstant(3, dl, MVT::i32));
4292 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4293 const ARMSubtarget *ST) {
4295 EVT VT = N->getValueType(0);
4296 if (VT.isVector()) {
4297 assert(ST->hasNEON());
4299 // Compute the least significant set bit: LSB = X & -X
4300 SDValue X = N->getOperand(0);
4301 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4302 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4304 EVT ElemTy = VT.getVectorElementType();
4306 if (ElemTy == MVT::i8) {
4307 // Compute with: cttz(x) = ctpop(lsb - 1)
4308 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4309 DAG.getTargetConstant(1, dl, ElemTy));
4310 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4311 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4314 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4315 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4316 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4317 unsigned NumBits = ElemTy.getSizeInBits();
4318 SDValue WidthMinus1 =
4319 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4320 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4321 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4322 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4325 // Compute with: cttz(x) = ctpop(lsb - 1)
4327 // Since we can only compute the number of bits in a byte with vcnt.8, we
4328 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4333 if (ElemTy == MVT::i64) {
4334 // Load constant 0xffff'ffff'ffff'ffff to register.
4335 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4336 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4337 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4339 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4340 DAG.getTargetConstant(1, dl, ElemTy));
4341 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4344 // Count #bits with vcnt.8.
4345 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4346 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4347 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4349 // Gather the #bits with vpaddl (pairwise add.)
4350 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4351 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4352 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4354 if (ElemTy == MVT::i16)
4357 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4358 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4359 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4361 if (ElemTy == MVT::i32)
4364 assert(ElemTy == MVT::i64);
4365 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4366 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4371 if (!ST->hasV6T2Ops())
4374 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4375 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4378 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4379 /// for each 16-bit element from operand, repeated. The basic idea is to
4380 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4382 /// Trace for v4i16:
4383 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4384 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4385 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4386 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4387 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4388 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4389 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4390 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4391 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4392 EVT VT = N->getValueType(0);
4395 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4396 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4397 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4398 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4399 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4400 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4403 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4404 /// bit-count for each 16-bit element from the operand. We need slightly
4405 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4406 /// 64/128-bit registers.
4408 /// Trace for v4i16:
4409 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4410 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4411 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4412 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4413 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4414 EVT VT = N->getValueType(0);
4417 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4418 if (VT.is64BitVector()) {
4419 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4420 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4421 DAG.getIntPtrConstant(0, DL));
4423 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4424 BitCounts, DAG.getIntPtrConstant(0, DL));
4425 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4429 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4430 /// bit-count for each 32-bit element from the operand. The idea here is
4431 /// to split the vector into 16-bit elements, leverage the 16-bit count
4432 /// routine, and then combine the results.
4434 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4435 /// input = [v0 v1 ] (vi: 32-bit elements)
4436 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4437 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4438 /// vrev: N0 = [k1 k0 k3 k2 ]
4440 /// N1 =+[k1 k0 k3 k2 ]
4442 /// N2 =+[k1 k3 k0 k2 ]
4444 /// Extended =+[k1 k3 k0 k2 ]
4446 /// Extracted=+[k1 k3 ]
4448 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4449 EVT VT = N->getValueType(0);
4452 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4454 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4455 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4456 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4457 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4458 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4460 if (VT.is64BitVector()) {
4461 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4462 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4463 DAG.getIntPtrConstant(0, DL));
4465 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4466 DAG.getIntPtrConstant(0, DL));
4467 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4471 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4472 const ARMSubtarget *ST) {
4473 EVT VT = N->getValueType(0);
4475 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4476 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4477 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4478 "Unexpected type for custom ctpop lowering");
4480 if (VT.getVectorElementType() == MVT::i32)
4481 return lowerCTPOP32BitElements(N, DAG);
4483 return lowerCTPOP16BitElements(N, DAG);
4486 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4487 const ARMSubtarget *ST) {
4488 EVT VT = N->getValueType(0);
4494 // Lower vector shifts on NEON to use VSHL.
4495 assert(ST->hasNEON() && "unexpected vector shift");
4497 // Left shifts translate directly to the vshiftu intrinsic.
4498 if (N->getOpcode() == ISD::SHL)
4499 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4500 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4502 N->getOperand(0), N->getOperand(1));
4504 assert((N->getOpcode() == ISD::SRA ||
4505 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4507 // NEON uses the same intrinsics for both left and right shifts. For
4508 // right shifts, the shift amounts are negative, so negate the vector of
4510 EVT ShiftVT = N->getOperand(1).getValueType();
4511 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4512 getZeroVector(ShiftVT, DAG, dl),
4514 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4515 Intrinsic::arm_neon_vshifts :
4516 Intrinsic::arm_neon_vshiftu);
4517 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4518 DAG.getConstant(vshiftInt, dl, MVT::i32),
4519 N->getOperand(0), NegatedCount);
4522 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4523 const ARMSubtarget *ST) {
4524 EVT VT = N->getValueType(0);
4527 // We can get here for a node like i32 = ISD::SHL i32, i64
4531 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4532 "Unknown shift to lower!");
4534 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4535 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4536 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4539 // If we are in thumb mode, we don't have RRX.
4540 if (ST->isThumb1Only()) return SDValue();
4542 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4543 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4544 DAG.getConstant(0, dl, MVT::i32));
4545 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4546 DAG.getConstant(1, dl, MVT::i32));
4548 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4549 // captures the result into a carry flag.
4550 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4551 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4553 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4554 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4556 // Merge the pieces into a single i64 value.
4557 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4560 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4561 SDValue TmpOp0, TmpOp1;
4562 bool Invert = false;
4566 SDValue Op0 = Op.getOperand(0);
4567 SDValue Op1 = Op.getOperand(1);
4568 SDValue CC = Op.getOperand(2);
4569 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4570 EVT VT = Op.getValueType();
4571 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4574 if (CmpVT.getVectorElementType() == MVT::i64)
4575 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4576 // but it's possible that our operands are 64-bit but our result is 32-bit.
4577 // Bail in this case.
4580 if (Op1.getValueType().isFloatingPoint()) {
4581 switch (SetCCOpcode) {
4582 default: llvm_unreachable("Illegal FP comparison");
4584 case ISD::SETNE: Invert = true; // Fallthrough
4586 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4588 case ISD::SETLT: Swap = true; // Fallthrough
4590 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4592 case ISD::SETLE: Swap = true; // Fallthrough
4594 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4595 case ISD::SETUGE: Swap = true; // Fallthrough
4596 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4597 case ISD::SETUGT: Swap = true; // Fallthrough
4598 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4599 case ISD::SETUEQ: Invert = true; // Fallthrough
4601 // Expand this to (OLT | OGT).
4605 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4606 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4608 case ISD::SETUO: Invert = true; // Fallthrough
4610 // Expand this to (OLT | OGE).
4614 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4615 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4619 // Integer comparisons.
4620 switch (SetCCOpcode) {
4621 default: llvm_unreachable("Illegal integer comparison");
4622 case ISD::SETNE: Invert = true;
4623 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4624 case ISD::SETLT: Swap = true;
4625 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4626 case ISD::SETLE: Swap = true;
4627 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4628 case ISD::SETULT: Swap = true;
4629 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4630 case ISD::SETULE: Swap = true;
4631 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4634 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4635 if (Opc == ARMISD::VCEQ) {
4638 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4640 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4643 // Ignore bitconvert.
4644 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4645 AndOp = AndOp.getOperand(0);
4647 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4649 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4650 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4657 std::swap(Op0, Op1);
4659 // If one of the operands is a constant vector zero, attempt to fold the
4660 // comparison to a specialized compare-against-zero form.
4662 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4664 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4665 if (Opc == ARMISD::VCGE)
4666 Opc = ARMISD::VCLEZ;
4667 else if (Opc == ARMISD::VCGT)
4668 Opc = ARMISD::VCLTZ;
4673 if (SingleOp.getNode()) {
4676 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4678 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4680 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4682 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4684 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4686 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4689 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4692 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4695 Result = DAG.getNOT(dl, Result, VT);
4700 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4701 /// valid vector constant for a NEON instruction with a "modified immediate"
4702 /// operand (e.g., VMOV). If so, return the encoded value.
4703 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4704 unsigned SplatBitSize, SelectionDAG &DAG,
4705 SDLoc dl, EVT &VT, bool is128Bits,
4706 NEONModImmType type) {
4707 unsigned OpCmode, Imm;
4709 // SplatBitSize is set to the smallest size that splats the vector, so a
4710 // zero vector will always have SplatBitSize == 8. However, NEON modified
4711 // immediate instructions others than VMOV do not support the 8-bit encoding
4712 // of a zero vector, and the default encoding of zero is supposed to be the
4717 switch (SplatBitSize) {
4719 if (type != VMOVModImm)
4721 // Any 1-byte value is OK. Op=0, Cmode=1110.
4722 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4725 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4729 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4730 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4731 if ((SplatBits & ~0xff) == 0) {
4732 // Value = 0x00nn: Op=x, Cmode=100x.
4737 if ((SplatBits & ~0xff00) == 0) {
4738 // Value = 0xnn00: Op=x, Cmode=101x.
4740 Imm = SplatBits >> 8;
4746 // NEON's 32-bit VMOV supports splat values where:
4747 // * only one byte is nonzero, or
4748 // * the least significant byte is 0xff and the second byte is nonzero, or
4749 // * the least significant 2 bytes are 0xff and the third is nonzero.
4750 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4751 if ((SplatBits & ~0xff) == 0) {
4752 // Value = 0x000000nn: Op=x, Cmode=000x.
4757 if ((SplatBits & ~0xff00) == 0) {
4758 // Value = 0x0000nn00: Op=x, Cmode=001x.
4760 Imm = SplatBits >> 8;
4763 if ((SplatBits & ~0xff0000) == 0) {
4764 // Value = 0x00nn0000: Op=x, Cmode=010x.
4766 Imm = SplatBits >> 16;
4769 if ((SplatBits & ~0xff000000) == 0) {
4770 // Value = 0xnn000000: Op=x, Cmode=011x.
4772 Imm = SplatBits >> 24;
4776 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4777 if (type == OtherModImm) return SDValue();
4779 if ((SplatBits & ~0xffff) == 0 &&
4780 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4781 // Value = 0x0000nnff: Op=x, Cmode=1100.
4783 Imm = SplatBits >> 8;
4787 if ((SplatBits & ~0xffffff) == 0 &&
4788 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4789 // Value = 0x00nnffff: Op=x, Cmode=1101.
4791 Imm = SplatBits >> 16;
4795 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4796 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4797 // VMOV.I32. A (very) minor optimization would be to replicate the value
4798 // and fall through here to test for a valid 64-bit splat. But, then the
4799 // caller would also need to check and handle the change in size.
4803 if (type != VMOVModImm)
4805 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4806 uint64_t BitMask = 0xff;
4808 unsigned ImmMask = 1;
4810 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4811 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4814 } else if ((SplatBits & BitMask) != 0) {
4821 if (DAG.getDataLayout().isBigEndian())
4822 // swap higher and lower 32 bit word
4823 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4825 // Op=1, Cmode=1110.
4827 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4832 llvm_unreachable("unexpected size for isNEONModifiedImm");
4835 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4836 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4839 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4840 const ARMSubtarget *ST) const {
4844 bool IsDouble = Op.getValueType() == MVT::f64;
4845 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4847 // Use the default (constant pool) lowering for double constants when we have
4849 if (IsDouble && Subtarget->isFPOnlySP())
4852 // Try splatting with a VMOV.f32...
4853 APFloat FPVal = CFP->getValueAPF();
4854 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4857 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4858 // We have code in place to select a valid ConstantFP already, no need to
4863 // It's a float and we are trying to use NEON operations where
4864 // possible. Lower it to a splat followed by an extract.
4866 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4867 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4869 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4870 DAG.getConstant(0, DL, MVT::i32));
4873 // The rest of our options are NEON only, make sure that's allowed before
4875 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4879 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4881 // It wouldn't really be worth bothering for doubles except for one very
4882 // important value, which does happen to match: 0.0. So make sure we don't do
4884 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4887 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4888 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4889 VMovVT, false, VMOVModImm);
4890 if (NewVal != SDValue()) {
4892 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
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));
4904 // Finally, try a VMVN.i32
4905 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4907 if (NewVal != SDValue()) {
4909 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4912 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4914 // It's a float: cast and extract a vector element.
4915 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4917 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4918 DAG.getConstant(0, DL, MVT::i32));
4924 // check if an VEXT instruction can handle the shuffle mask when the
4925 // vector sources of the shuffle are the same.
4926 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4927 unsigned NumElts = VT.getVectorNumElements();
4929 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4935 // If this is a VEXT shuffle, the immediate value is the index of the first
4936 // element. The other shuffle indices must be the successive elements after
4938 unsigned ExpectedElt = Imm;
4939 for (unsigned i = 1; i < NumElts; ++i) {
4940 // Increment the expected index. If it wraps around, just follow it
4941 // back to index zero and keep going.
4943 if (ExpectedElt == NumElts)
4946 if (M[i] < 0) continue; // ignore UNDEF indices
4947 if (ExpectedElt != static_cast<unsigned>(M[i]))
4955 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4956 bool &ReverseVEXT, unsigned &Imm) {
4957 unsigned NumElts = VT.getVectorNumElements();
4958 ReverseVEXT = false;
4960 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4966 // If this is a VEXT shuffle, the immediate value is the index of the first
4967 // element. The other shuffle indices must be the successive elements after
4969 unsigned ExpectedElt = Imm;
4970 for (unsigned i = 1; i < NumElts; ++i) {
4971 // Increment the expected index. If it wraps around, it may still be
4972 // a VEXT but the source vectors must be swapped.
4974 if (ExpectedElt == NumElts * 2) {
4979 if (M[i] < 0) continue; // ignore UNDEF indices
4980 if (ExpectedElt != static_cast<unsigned>(M[i]))
4984 // Adjust the index value if the source operands will be swapped.
4991 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4992 /// instruction with the specified blocksize. (The order of the elements
4993 /// within each block of the vector is reversed.)
4994 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4995 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4996 "Only possible block sizes for VREV are: 16, 32, 64");
4998 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5002 unsigned NumElts = VT.getVectorNumElements();
5003 unsigned BlockElts = M[0] + 1;
5004 // If the first shuffle index is UNDEF, be optimistic.
5006 BlockElts = BlockSize / EltSz;
5008 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5011 for (unsigned i = 0; i < NumElts; ++i) {
5012 if (M[i] < 0) continue; // ignore UNDEF indices
5013 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5020 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5021 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5022 // range, then 0 is placed into the resulting vector. So pretty much any mask
5023 // of 8 elements can work here.
5024 return VT == MVT::v8i8 && M.size() == 8;
5027 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5028 // checking that pairs of elements in the shuffle mask represent the same index
5029 // in each vector, incrementing the expected index by 2 at each step.
5030 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5031 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5033 // WhichResult gives the offset for each element in the mask based on which
5034 // of the two results it belongs to.
5036 // The transpose can be represented either as:
5037 // result1 = shufflevector v1, v2, result1_shuffle_mask
5038 // result2 = shufflevector v1, v2, result2_shuffle_mask
5039 // where v1/v2 and the shuffle masks have the same number of elements
5040 // (here WhichResult (see below) indicates which result is being checked)
5043 // results = shufflevector v1, v2, shuffle_mask
5044 // where both results are returned in one vector and the shuffle mask has twice
5045 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5046 // want to check the low half and high half of the shuffle mask as if it were
5048 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5049 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5053 unsigned NumElts = VT.getVectorNumElements();
5054 if (M.size() != NumElts && M.size() != NumElts*2)
5057 // If the mask is twice as long as the input vector then we need to check the
5058 // upper and lower parts of the mask with a matching value for WhichResult
5059 // FIXME: A mask with only even values will be rejected in case the first
5060 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5061 // M[0] is used to determine WhichResult
5062 for (unsigned i = 0; i < M.size(); i += NumElts) {
5063 if (M.size() == NumElts * 2)
5064 WhichResult = i / NumElts;
5066 WhichResult = M[i] == 0 ? 0 : 1;
5067 for (unsigned j = 0; j < NumElts; j += 2) {
5068 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5069 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5074 if (M.size() == NumElts*2)
5080 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5081 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5082 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5083 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5084 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5088 unsigned NumElts = VT.getVectorNumElements();
5089 if (M.size() != NumElts && M.size() != NumElts*2)
5092 for (unsigned i = 0; i < M.size(); i += NumElts) {
5093 if (M.size() == NumElts * 2)
5094 WhichResult = i / NumElts;
5096 WhichResult = M[i] == 0 ? 0 : 1;
5097 for (unsigned j = 0; j < NumElts; j += 2) {
5098 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5099 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5104 if (M.size() == NumElts*2)
5110 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5111 // that the mask elements are either all even and in steps of size 2 or all odd
5112 // and in steps of size 2.
5113 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5114 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5116 // Requires similar checks to that of isVTRNMask with
5117 // respect the how results are returned.
5118 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5119 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5123 unsigned NumElts = VT.getVectorNumElements();
5124 if (M.size() != NumElts && M.size() != NumElts*2)
5127 for (unsigned i = 0; i < M.size(); i += NumElts) {
5128 WhichResult = M[i] == 0 ? 0 : 1;
5129 for (unsigned j = 0; j < NumElts; ++j) {
5130 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5135 if (M.size() == NumElts*2)
5138 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5139 if (VT.is64BitVector() && EltSz == 32)
5145 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5146 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5147 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5148 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5149 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5153 unsigned NumElts = VT.getVectorNumElements();
5154 if (M.size() != NumElts && M.size() != NumElts*2)
5157 unsigned Half = NumElts / 2;
5158 for (unsigned i = 0; i < M.size(); i += NumElts) {
5159 WhichResult = M[i] == 0 ? 0 : 1;
5160 for (unsigned j = 0; j < NumElts; j += Half) {
5161 unsigned Idx = WhichResult;
5162 for (unsigned k = 0; k < Half; ++k) {
5163 int MIdx = M[i + j + k];
5164 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5171 if (M.size() == NumElts*2)
5174 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5175 if (VT.is64BitVector() && EltSz == 32)
5181 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5182 // that pairs of elements of the shufflemask represent the same index in each
5183 // vector incrementing sequentially through the vectors.
5184 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5185 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5187 // Requires similar checks to that of isVTRNMask with respect the how results
5189 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5190 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5194 unsigned NumElts = VT.getVectorNumElements();
5195 if (M.size() != NumElts && M.size() != NumElts*2)
5198 for (unsigned i = 0; i < M.size(); i += NumElts) {
5199 WhichResult = M[i] == 0 ? 0 : 1;
5200 unsigned Idx = WhichResult * NumElts / 2;
5201 for (unsigned j = 0; j < NumElts; j += 2) {
5202 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5203 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5209 if (M.size() == NumElts*2)
5212 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5213 if (VT.is64BitVector() && EltSz == 32)
5219 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5220 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5221 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5222 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5223 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5227 unsigned NumElts = VT.getVectorNumElements();
5228 if (M.size() != NumElts && M.size() != NumElts*2)
5231 for (unsigned i = 0; i < M.size(); i += NumElts) {
5232 WhichResult = M[i] == 0 ? 0 : 1;
5233 unsigned Idx = WhichResult * NumElts / 2;
5234 for (unsigned j = 0; j < NumElts; j += 2) {
5235 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5236 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5242 if (M.size() == NumElts*2)
5245 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5246 if (VT.is64BitVector() && EltSz == 32)
5252 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5253 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5254 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5255 unsigned &WhichResult,
5258 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5259 return ARMISD::VTRN;
5260 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5261 return ARMISD::VUZP;
5262 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5263 return ARMISD::VZIP;
5266 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5267 return ARMISD::VTRN;
5268 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5269 return ARMISD::VUZP;
5270 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5271 return ARMISD::VZIP;
5276 /// \return true if this is a reverse operation on an vector.
5277 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5278 unsigned NumElts = VT.getVectorNumElements();
5279 // Make sure the mask has the right size.
5280 if (NumElts != M.size())
5283 // Look for <15, ..., 3, -1, 1, 0>.
5284 for (unsigned i = 0; i != NumElts; ++i)
5285 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5291 // If N is an integer constant that can be moved into a register in one
5292 // instruction, return an SDValue of such a constant (will become a MOV
5293 // instruction). Otherwise return null.
5294 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5295 const ARMSubtarget *ST, SDLoc dl) {
5297 if (!isa<ConstantSDNode>(N))
5299 Val = cast<ConstantSDNode>(N)->getZExtValue();
5301 if (ST->isThumb1Only()) {
5302 if (Val <= 255 || ~Val <= 255)
5303 return DAG.getConstant(Val, dl, MVT::i32);
5305 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5306 return DAG.getConstant(Val, dl, MVT::i32);
5311 // If this is a case we can't handle, return null and let the default
5312 // expansion code take care of it.
5313 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5314 const ARMSubtarget *ST) const {
5315 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5317 EVT VT = Op.getValueType();
5319 APInt SplatBits, SplatUndef;
5320 unsigned SplatBitSize;
5322 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5323 if (SplatBitSize <= 64) {
5324 // Check if an immediate VMOV works.
5326 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5327 SplatUndef.getZExtValue(), SplatBitSize,
5328 DAG, dl, VmovVT, VT.is128BitVector(),
5330 if (Val.getNode()) {
5331 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5332 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5335 // Try an immediate VMVN.
5336 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5337 Val = isNEONModifiedImm(NegatedImm,
5338 SplatUndef.getZExtValue(), SplatBitSize,
5339 DAG, dl, VmovVT, VT.is128BitVector(),
5341 if (Val.getNode()) {
5342 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5343 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5346 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5347 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5348 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5350 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5351 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5357 // Scan through the operands to see if only one value is used.
5359 // As an optimisation, even if more than one value is used it may be more
5360 // profitable to splat with one value then change some lanes.
5362 // Heuristically we decide to do this if the vector has a "dominant" value,
5363 // defined as splatted to more than half of the lanes.
5364 unsigned NumElts = VT.getVectorNumElements();
5365 bool isOnlyLowElement = true;
5366 bool usesOnlyOneValue = true;
5367 bool hasDominantValue = false;
5368 bool isConstant = true;
5370 // Map of the number of times a particular SDValue appears in the
5372 DenseMap<SDValue, unsigned> ValueCounts;
5374 for (unsigned i = 0; i < NumElts; ++i) {
5375 SDValue V = Op.getOperand(i);
5376 if (V.getOpcode() == ISD::UNDEF)
5379 isOnlyLowElement = false;
5380 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5383 ValueCounts.insert(std::make_pair(V, 0));
5384 unsigned &Count = ValueCounts[V];
5386 // Is this value dominant? (takes up more than half of the lanes)
5387 if (++Count > (NumElts / 2)) {
5388 hasDominantValue = true;
5392 if (ValueCounts.size() != 1)
5393 usesOnlyOneValue = false;
5394 if (!Value.getNode() && ValueCounts.size() > 0)
5395 Value = ValueCounts.begin()->first;
5397 if (ValueCounts.size() == 0)
5398 return DAG.getUNDEF(VT);
5400 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5401 // Keep going if we are hitting this case.
5402 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5403 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5405 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5407 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5408 // i32 and try again.
5409 if (hasDominantValue && EltSize <= 32) {
5413 // If we are VDUPing a value that comes directly from a vector, that will
5414 // cause an unnecessary move to and from a GPR, where instead we could
5415 // just use VDUPLANE. We can only do this if the lane being extracted
5416 // is at a constant index, as the VDUP from lane instructions only have
5417 // constant-index forms.
5418 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5419 isa<ConstantSDNode>(Value->getOperand(1))) {
5420 // We need to create a new undef vector to use for the VDUPLANE if the
5421 // size of the vector from which we get the value is different than the
5422 // size of the vector that we need to create. We will insert the element
5423 // such that the register coalescer will remove unnecessary copies.
5424 if (VT != Value->getOperand(0).getValueType()) {
5425 ConstantSDNode *constIndex;
5426 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5427 assert(constIndex && "The index is not a constant!");
5428 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5429 VT.getVectorNumElements();
5430 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5431 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5432 Value, DAG.getConstant(index, dl, MVT::i32)),
5433 DAG.getConstant(index, dl, MVT::i32));
5435 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5436 Value->getOperand(0), Value->getOperand(1));
5438 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5440 if (!usesOnlyOneValue) {
5441 // The dominant value was splatted as 'N', but we now have to insert
5442 // all differing elements.
5443 for (unsigned I = 0; I < NumElts; ++I) {
5444 if (Op.getOperand(I) == Value)
5446 SmallVector<SDValue, 3> Ops;
5448 Ops.push_back(Op.getOperand(I));
5449 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5450 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5455 if (VT.getVectorElementType().isFloatingPoint()) {
5456 SmallVector<SDValue, 8> Ops;
5457 for (unsigned i = 0; i < NumElts; ++i)
5458 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5460 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5461 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5462 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5464 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5466 if (usesOnlyOneValue) {
5467 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5468 if (isConstant && Val.getNode())
5469 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5473 // If all elements are constants and the case above didn't get hit, fall back
5474 // to the default expansion, which will generate a load from the constant
5479 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5481 SDValue shuffle = ReconstructShuffle(Op, DAG);
5482 if (shuffle != SDValue())
5486 // Vectors with 32- or 64-bit elements can be built by directly assigning
5487 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5488 // will be legalized.
5489 if (EltSize >= 32) {
5490 // Do the expansion with floating-point types, since that is what the VFP
5491 // registers are defined to use, and since i64 is not legal.
5492 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5493 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5494 SmallVector<SDValue, 8> Ops;
5495 for (unsigned i = 0; i < NumElts; ++i)
5496 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5497 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5498 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5501 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5502 // know the default expansion would otherwise fall back on something even
5503 // worse. For a vector with one or two non-undef values, that's
5504 // scalar_to_vector for the elements followed by a shuffle (provided the
5505 // shuffle is valid for the target) and materialization element by element
5506 // on the stack followed by a load for everything else.
5507 if (!isConstant && !usesOnlyOneValue) {
5508 SDValue Vec = DAG.getUNDEF(VT);
5509 for (unsigned i = 0 ; i < NumElts; ++i) {
5510 SDValue V = Op.getOperand(i);
5511 if (V.getOpcode() == ISD::UNDEF)
5513 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5514 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5522 // Gather data to see if the operation can be modelled as a
5523 // shuffle in combination with VEXTs.
5524 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5525 SelectionDAG &DAG) const {
5526 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5528 EVT VT = Op.getValueType();
5529 unsigned NumElts = VT.getVectorNumElements();
5531 struct ShuffleSourceInfo {
5536 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5537 // be compatible with the shuffle we intend to construct. As a result
5538 // ShuffleVec will be some sliding window into the original Vec.
5541 // Code should guarantee that element i in Vec starts at element "WindowBase
5542 // + i * WindowScale in ShuffleVec".
5546 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5547 ShuffleSourceInfo(SDValue Vec)
5548 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5552 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5554 SmallVector<ShuffleSourceInfo, 2> Sources;
5555 for (unsigned i = 0; i < NumElts; ++i) {
5556 SDValue V = Op.getOperand(i);
5557 if (V.getOpcode() == ISD::UNDEF)
5559 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5560 // A shuffle can only come from building a vector from various
5561 // elements of other vectors.
5563 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5564 // Furthermore, shuffles require a constant mask, whereas extractelts
5565 // accept variable indices.
5569 // Add this element source to the list if it's not already there.
5570 SDValue SourceVec = V.getOperand(0);
5571 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5572 if (Source == Sources.end())
5573 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5575 // Update the minimum and maximum lane number seen.
5576 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5577 Source->MinElt = std::min(Source->MinElt, EltNo);
5578 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5581 // Currently only do something sane when at most two source vectors
5583 if (Sources.size() > 2)
5586 // Find out the smallest element size among result and two sources, and use
5587 // it as element size to build the shuffle_vector.
5588 EVT SmallestEltTy = VT.getVectorElementType();
5589 for (auto &Source : Sources) {
5590 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5591 if (SrcEltTy.bitsLT(SmallestEltTy))
5592 SmallestEltTy = SrcEltTy;
5594 unsigned ResMultiplier =
5595 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5596 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5597 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5599 // If the source vector is too wide or too narrow, we may nevertheless be able
5600 // to construct a compatible shuffle either by concatenating it with UNDEF or
5601 // extracting a suitable range of elements.
5602 for (auto &Src : Sources) {
5603 EVT SrcVT = Src.ShuffleVec.getValueType();
5605 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5608 // This stage of the search produces a source with the same element type as
5609 // the original, but with a total width matching the BUILD_VECTOR output.
5610 EVT EltVT = SrcVT.getVectorElementType();
5611 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5612 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5614 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5615 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5617 // We can pad out the smaller vector for free, so if it's part of a
5620 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5621 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5625 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5628 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5629 // Span too large for a VEXT to cope
5633 if (Src.MinElt >= NumSrcElts) {
5634 // The extraction can just take the second half
5636 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5637 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5638 Src.WindowBase = -NumSrcElts;
5639 } else if (Src.MaxElt < NumSrcElts) {
5640 // The extraction can just take the first half
5642 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5643 DAG.getConstant(0, dl, MVT::i32));
5645 // An actual VEXT is needed
5647 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5648 DAG.getConstant(0, dl, MVT::i32));
5650 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5651 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5653 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5655 DAG.getConstant(Src.MinElt, dl, MVT::i32));
5656 Src.WindowBase = -Src.MinElt;
5660 // Another possible incompatibility occurs from the vector element types. We
5661 // can fix this by bitcasting the source vectors to the same type we intend
5663 for (auto &Src : Sources) {
5664 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5665 if (SrcEltTy == SmallestEltTy)
5667 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5668 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5669 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5670 Src.WindowBase *= Src.WindowScale;
5673 // Final sanity check before we try to actually produce a shuffle.
5675 for (auto Src : Sources)
5676 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5679 // The stars all align, our next step is to produce the mask for the shuffle.
5680 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5681 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5682 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5683 SDValue Entry = Op.getOperand(i);
5684 if (Entry.getOpcode() == ISD::UNDEF)
5687 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5688 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5690 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5691 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5693 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5694 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5695 VT.getVectorElementType().getSizeInBits());
5696 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5698 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5699 // starting at the appropriate offset.
5700 int *LaneMask = &Mask[i * ResMultiplier];
5702 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5703 ExtractBase += NumElts * (Src - Sources.begin());
5704 for (int j = 0; j < LanesDefined; ++j)
5705 LaneMask[j] = ExtractBase + j;
5708 // Final check before we try to produce nonsense...
5709 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5712 // We can't handle more than two sources. This should have already
5713 // been checked before this point.
5714 assert(Sources.size() <= 2 && "Too many sources!");
5716 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5717 for (unsigned i = 0; i < Sources.size(); ++i)
5718 ShuffleOps[i] = Sources[i].ShuffleVec;
5720 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5721 ShuffleOps[1], &Mask[0]);
5722 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5725 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5726 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5727 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5728 /// are assumed to be legal.
5730 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5732 if (VT.getVectorNumElements() == 4 &&
5733 (VT.is128BitVector() || VT.is64BitVector())) {
5734 unsigned PFIndexes[4];
5735 for (unsigned i = 0; i != 4; ++i) {
5739 PFIndexes[i] = M[i];
5742 // Compute the index in the perfect shuffle table.
5743 unsigned PFTableIndex =
5744 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5745 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5746 unsigned Cost = (PFEntry >> 30);
5752 bool ReverseVEXT, isV_UNDEF;
5753 unsigned Imm, WhichResult;
5755 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5756 return (EltSize >= 32 ||
5757 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5758 isVREVMask(M, VT, 64) ||
5759 isVREVMask(M, VT, 32) ||
5760 isVREVMask(M, VT, 16) ||
5761 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5762 isVTBLMask(M, VT) ||
5763 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5764 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5767 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5768 /// the specified operations to build the shuffle.
5769 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5770 SDValue RHS, SelectionDAG &DAG,
5772 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5773 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5774 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5777 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5786 OP_VUZPL, // VUZP, left result
5787 OP_VUZPR, // VUZP, right result
5788 OP_VZIPL, // VZIP, left result
5789 OP_VZIPR, // VZIP, right result
5790 OP_VTRNL, // VTRN, left result
5791 OP_VTRNR // VTRN, right result
5794 if (OpNum == OP_COPY) {
5795 if (LHSID == (1*9+2)*9+3) return LHS;
5796 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5800 SDValue OpLHS, OpRHS;
5801 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5802 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5803 EVT VT = OpLHS.getValueType();
5806 default: llvm_unreachable("Unknown shuffle opcode!");
5808 // VREV divides the vector in half and swaps within the half.
5809 if (VT.getVectorElementType() == MVT::i32 ||
5810 VT.getVectorElementType() == MVT::f32)
5811 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5812 // vrev <4 x i16> -> VREV32
5813 if (VT.getVectorElementType() == MVT::i16)
5814 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5815 // vrev <4 x i8> -> VREV16
5816 assert(VT.getVectorElementType() == MVT::i8);
5817 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5822 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5823 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5827 return DAG.getNode(ARMISD::VEXT, dl, VT,
5829 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5832 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5833 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5836 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5837 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5840 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5841 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5845 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5846 ArrayRef<int> ShuffleMask,
5847 SelectionDAG &DAG) {
5848 // Check to see if we can use the VTBL instruction.
5849 SDValue V1 = Op.getOperand(0);
5850 SDValue V2 = Op.getOperand(1);
5853 SmallVector<SDValue, 8> VTBLMask;
5854 for (ArrayRef<int>::iterator
5855 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5856 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5858 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5859 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5860 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5862 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5863 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5866 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5867 SelectionDAG &DAG) {
5869 SDValue OpLHS = Op.getOperand(0);
5870 EVT VT = OpLHS.getValueType();
5872 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5873 "Expect an v8i16/v16i8 type");
5874 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5875 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5876 // extract the first 8 bytes into the top double word and the last 8 bytes
5877 // into the bottom double word. The v8i16 case is similar.
5878 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5879 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5880 DAG.getConstant(ExtractNum, DL, MVT::i32));
5883 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5884 SDValue V1 = Op.getOperand(0);
5885 SDValue V2 = Op.getOperand(1);
5887 EVT VT = Op.getValueType();
5888 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5890 // Convert shuffles that are directly supported on NEON to target-specific
5891 // DAG nodes, instead of keeping them as shuffles and matching them again
5892 // during code selection. This is more efficient and avoids the possibility
5893 // of inconsistencies between legalization and selection.
5894 // FIXME: floating-point vectors should be canonicalized to integer vectors
5895 // of the same time so that they get CSEd properly.
5896 ArrayRef<int> ShuffleMask = SVN->getMask();
5898 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5899 if (EltSize <= 32) {
5900 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5901 int Lane = SVN->getSplatIndex();
5902 // If this is undef splat, generate it via "just" vdup, if possible.
5903 if (Lane == -1) Lane = 0;
5905 // Test if V1 is a SCALAR_TO_VECTOR.
5906 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5907 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5909 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5910 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5912 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5913 !isa<ConstantSDNode>(V1.getOperand(0))) {
5914 bool IsScalarToVector = true;
5915 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5916 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5917 IsScalarToVector = false;
5920 if (IsScalarToVector)
5921 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5923 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5924 DAG.getConstant(Lane, dl, MVT::i32));
5929 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5932 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5933 DAG.getConstant(Imm, dl, MVT::i32));
5936 if (isVREVMask(ShuffleMask, VT, 64))
5937 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5938 if (isVREVMask(ShuffleMask, VT, 32))
5939 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5940 if (isVREVMask(ShuffleMask, VT, 16))
5941 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5943 if (V2->getOpcode() == ISD::UNDEF &&
5944 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5945 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5946 DAG.getConstant(Imm, dl, MVT::i32));
5949 // Check for Neon shuffles that modify both input vectors in place.
5950 // If both results are used, i.e., if there are two shuffles with the same
5951 // source operands and with masks corresponding to both results of one of
5952 // these operations, DAG memoization will ensure that a single node is
5953 // used for both shuffles.
5954 unsigned WhichResult;
5956 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5957 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5960 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5961 .getValue(WhichResult);
5964 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5965 // shuffles that produce a result larger than their operands with:
5966 // shuffle(concat(v1, undef), concat(v2, undef))
5968 // shuffle(concat(v1, v2), undef)
5969 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5971 // This is useful in the general case, but there are special cases where
5972 // native shuffles produce larger results: the two-result ops.
5974 // Look through the concat when lowering them:
5975 // shuffle(concat(v1, v2), undef)
5977 // concat(VZIP(v1, v2):0, :1)
5979 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5980 V2->getOpcode() == ISD::UNDEF) {
5981 SDValue SubV1 = V1->getOperand(0);
5982 SDValue SubV2 = V1->getOperand(1);
5983 EVT SubVT = SubV1.getValueType();
5985 // We expect these to have been canonicalized to -1.
5986 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5987 return i < (int)VT.getVectorNumElements();
5988 }) && "Unexpected shuffle index into UNDEF operand!");
5990 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5991 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5994 assert((WhichResult == 0) &&
5995 "In-place shuffle of concat can only have one result!");
5996 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5998 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6004 // If the shuffle is not directly supported and it has 4 elements, use
6005 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6006 unsigned NumElts = VT.getVectorNumElements();
6008 unsigned PFIndexes[4];
6009 for (unsigned i = 0; i != 4; ++i) {
6010 if (ShuffleMask[i] < 0)
6013 PFIndexes[i] = ShuffleMask[i];
6016 // Compute the index in the perfect shuffle table.
6017 unsigned PFTableIndex =
6018 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6019 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6020 unsigned Cost = (PFEntry >> 30);
6023 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6026 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6027 if (EltSize >= 32) {
6028 // Do the expansion with floating-point types, since that is what the VFP
6029 // registers are defined to use, and since i64 is not legal.
6030 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6031 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6032 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6033 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6034 SmallVector<SDValue, 8> Ops;
6035 for (unsigned i = 0; i < NumElts; ++i) {
6036 if (ShuffleMask[i] < 0)
6037 Ops.push_back(DAG.getUNDEF(EltVT));
6039 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6040 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6041 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6044 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6045 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6048 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6049 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6051 if (VT == MVT::v8i8) {
6052 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6053 if (NewOp.getNode())
6060 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6061 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6062 SDValue Lane = Op.getOperand(2);
6063 if (!isa<ConstantSDNode>(Lane))
6069 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6070 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6071 SDValue Lane = Op.getOperand(1);
6072 if (!isa<ConstantSDNode>(Lane))
6075 SDValue Vec = Op.getOperand(0);
6076 if (Op.getValueType() == MVT::i32 &&
6077 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6079 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6085 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6086 // The only time a CONCAT_VECTORS operation can have legal types is when
6087 // two 64-bit vectors are concatenated to a 128-bit vector.
6088 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6089 "unexpected CONCAT_VECTORS");
6091 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6092 SDValue Op0 = Op.getOperand(0);
6093 SDValue Op1 = Op.getOperand(1);
6094 if (Op0.getOpcode() != ISD::UNDEF)
6095 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6096 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6097 DAG.getIntPtrConstant(0, dl));
6098 if (Op1.getOpcode() != ISD::UNDEF)
6099 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6100 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6101 DAG.getIntPtrConstant(1, dl));
6102 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6105 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6106 /// element has been zero/sign-extended, depending on the isSigned parameter,
6107 /// from an integer type half its size.
6108 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6110 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6111 EVT VT = N->getValueType(0);
6112 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6113 SDNode *BVN = N->getOperand(0).getNode();
6114 if (BVN->getValueType(0) != MVT::v4i32 ||
6115 BVN->getOpcode() != ISD::BUILD_VECTOR)
6117 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6118 unsigned HiElt = 1 - LoElt;
6119 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6120 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6121 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6122 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6123 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6126 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6127 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6130 if (Hi0->isNullValue() && Hi1->isNullValue())
6136 if (N->getOpcode() != ISD::BUILD_VECTOR)
6139 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6140 SDNode *Elt = N->getOperand(i).getNode();
6141 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6142 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6143 unsigned HalfSize = EltSize / 2;
6145 if (!isIntN(HalfSize, C->getSExtValue()))
6148 if (!isUIntN(HalfSize, C->getZExtValue()))
6159 /// isSignExtended - Check if a node is a vector value that is sign-extended
6160 /// or a constant BUILD_VECTOR with sign-extended elements.
6161 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6162 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6164 if (isExtendedBUILD_VECTOR(N, DAG, true))
6169 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6170 /// or a constant BUILD_VECTOR with zero-extended elements.
6171 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6172 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6174 if (isExtendedBUILD_VECTOR(N, DAG, false))
6179 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6180 if (OrigVT.getSizeInBits() >= 64)
6183 assert(OrigVT.isSimple() && "Expecting a simple value type");
6185 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6186 switch (OrigSimpleTy) {
6187 default: llvm_unreachable("Unexpected Vector Type");
6196 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6197 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6198 /// We insert the required extension here to get the vector to fill a D register.
6199 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6202 unsigned ExtOpcode) {
6203 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6204 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6205 // 64-bits we need to insert a new extension so that it will be 64-bits.
6206 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6207 if (OrigTy.getSizeInBits() >= 64)
6210 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6211 EVT NewVT = getExtensionTo64Bits(OrigTy);
6213 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6216 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6217 /// does not do any sign/zero extension. If the original vector is less
6218 /// than 64 bits, an appropriate extension will be added after the load to
6219 /// reach a total size of 64 bits. We have to add the extension separately
6220 /// because ARM does not have a sign/zero extending load for vectors.
6221 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6222 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6224 // The load already has the right type.
6225 if (ExtendedTy == LD->getMemoryVT())
6226 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6227 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6228 LD->isNonTemporal(), LD->isInvariant(),
6229 LD->getAlignment());
6231 // We need to create a zextload/sextload. We cannot just create a load
6232 // followed by a zext/zext node because LowerMUL is also run during normal
6233 // operation legalization where we can't create illegal types.
6234 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6235 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6236 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6237 LD->isNonTemporal(), LD->getAlignment());
6240 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6241 /// extending load, or BUILD_VECTOR with extended elements, return the
6242 /// unextended value. The unextended vector should be 64 bits so that it can
6243 /// be used as an operand to a VMULL instruction. If the original vector size
6244 /// before extension is less than 64 bits we add a an extension to resize
6245 /// the vector to 64 bits.
6246 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6247 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6248 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6249 N->getOperand(0)->getValueType(0),
6253 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6254 return SkipLoadExtensionForVMULL(LD, DAG);
6256 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6257 // have been legalized as a BITCAST from v4i32.
6258 if (N->getOpcode() == ISD::BITCAST) {
6259 SDNode *BVN = N->getOperand(0).getNode();
6260 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6261 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6262 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6263 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6264 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6266 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6267 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6268 EVT VT = N->getValueType(0);
6269 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6270 unsigned NumElts = VT.getVectorNumElements();
6271 MVT TruncVT = MVT::getIntegerVT(EltSize);
6272 SmallVector<SDValue, 8> Ops;
6274 for (unsigned i = 0; i != NumElts; ++i) {
6275 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6276 const APInt &CInt = C->getAPIntValue();
6277 // Element types smaller than 32 bits are not legal, so use i32 elements.
6278 // The values are implicitly truncated so sext vs. zext doesn't matter.
6279 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6281 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6282 MVT::getVectorVT(TruncVT, NumElts), Ops);
6285 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6286 unsigned Opcode = N->getOpcode();
6287 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6288 SDNode *N0 = N->getOperand(0).getNode();
6289 SDNode *N1 = N->getOperand(1).getNode();
6290 return N0->hasOneUse() && N1->hasOneUse() &&
6291 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6296 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6297 unsigned Opcode = N->getOpcode();
6298 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6299 SDNode *N0 = N->getOperand(0).getNode();
6300 SDNode *N1 = N->getOperand(1).getNode();
6301 return N0->hasOneUse() && N1->hasOneUse() &&
6302 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6307 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6308 // Multiplications are only custom-lowered for 128-bit vectors so that
6309 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6310 EVT VT = Op.getValueType();
6311 assert(VT.is128BitVector() && VT.isInteger() &&
6312 "unexpected type for custom-lowering ISD::MUL");
6313 SDNode *N0 = Op.getOperand(0).getNode();
6314 SDNode *N1 = Op.getOperand(1).getNode();
6315 unsigned NewOpc = 0;
6317 bool isN0SExt = isSignExtended(N0, DAG);
6318 bool isN1SExt = isSignExtended(N1, DAG);
6319 if (isN0SExt && isN1SExt)
6320 NewOpc = ARMISD::VMULLs;
6322 bool isN0ZExt = isZeroExtended(N0, DAG);
6323 bool isN1ZExt = isZeroExtended(N1, DAG);
6324 if (isN0ZExt && isN1ZExt)
6325 NewOpc = ARMISD::VMULLu;
6326 else if (isN1SExt || isN1ZExt) {
6327 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6328 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6329 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6330 NewOpc = ARMISD::VMULLs;
6332 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6333 NewOpc = ARMISD::VMULLu;
6335 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6337 NewOpc = ARMISD::VMULLu;
6343 if (VT == MVT::v2i64)
6344 // Fall through to expand this. It is not legal.
6347 // Other vector multiplications are legal.
6352 // Legalize to a VMULL instruction.
6355 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6357 Op0 = SkipExtensionForVMULL(N0, DAG);
6358 assert(Op0.getValueType().is64BitVector() &&
6359 Op1.getValueType().is64BitVector() &&
6360 "unexpected types for extended operands to VMULL");
6361 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6364 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6365 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6372 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6373 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6374 EVT Op1VT = Op1.getValueType();
6375 return DAG.getNode(N0->getOpcode(), DL, VT,
6376 DAG.getNode(NewOpc, DL, VT,
6377 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6378 DAG.getNode(NewOpc, DL, VT,
6379 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6383 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6384 // TODO: Should this propagate fast-math-flags?
6387 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6388 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6389 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6390 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6391 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6392 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6393 // Get reciprocal estimate.
6394 // float4 recip = vrecpeq_f32(yf);
6395 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6396 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6398 // Because char has a smaller range than uchar, we can actually get away
6399 // without any newton steps. This requires that we use a weird bias
6400 // of 0xb000, however (again, this has been exhaustively tested).
6401 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6402 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6403 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6404 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6405 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6406 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6407 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6408 // Convert back to short.
6409 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6410 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6415 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6416 // TODO: Should this propagate fast-math-flags?
6419 // Convert to float.
6420 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6421 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6422 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6423 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6424 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6425 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6427 // Use reciprocal estimate and one refinement step.
6428 // float4 recip = vrecpeq_f32(yf);
6429 // recip *= vrecpsq_f32(yf, recip);
6430 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6431 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6433 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6434 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6436 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6437 // Because short has a smaller range than ushort, we can actually get away
6438 // with only a single newton step. This requires that we use a weird bias
6439 // of 89, however (again, this has been exhaustively tested).
6440 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6441 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6442 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6443 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6444 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6445 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6446 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6447 // Convert back to integer and return.
6448 // return vmovn_s32(vcvt_s32_f32(result));
6449 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6450 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6454 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6455 EVT VT = Op.getValueType();
6456 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6457 "unexpected type for custom-lowering ISD::SDIV");
6460 SDValue N0 = Op.getOperand(0);
6461 SDValue N1 = Op.getOperand(1);
6464 if (VT == MVT::v8i8) {
6465 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6466 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6468 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6469 DAG.getIntPtrConstant(4, dl));
6470 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6471 DAG.getIntPtrConstant(4, dl));
6472 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6473 DAG.getIntPtrConstant(0, dl));
6474 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6475 DAG.getIntPtrConstant(0, dl));
6477 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6478 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6480 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6481 N0 = LowerCONCAT_VECTORS(N0, DAG);
6483 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6486 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6489 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6490 // TODO: Should this propagate fast-math-flags?
6491 EVT VT = Op.getValueType();
6492 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6493 "unexpected type for custom-lowering ISD::UDIV");
6496 SDValue N0 = Op.getOperand(0);
6497 SDValue N1 = Op.getOperand(1);
6500 if (VT == MVT::v8i8) {
6501 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6502 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6504 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6505 DAG.getIntPtrConstant(4, dl));
6506 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6507 DAG.getIntPtrConstant(4, dl));
6508 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6509 DAG.getIntPtrConstant(0, dl));
6510 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6511 DAG.getIntPtrConstant(0, dl));
6513 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6514 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6516 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6517 N0 = LowerCONCAT_VECTORS(N0, DAG);
6519 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6520 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6526 // v4i16 sdiv ... Convert to float.
6527 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6528 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6529 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6530 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6531 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6532 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6534 // Use reciprocal estimate and two refinement steps.
6535 // float4 recip = vrecpeq_f32(yf);
6536 // recip *= vrecpsq_f32(yf, recip);
6537 // recip *= vrecpsq_f32(yf, recip);
6538 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6539 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6541 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6542 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6544 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6545 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6546 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6548 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6549 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6550 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6551 // and that it will never cause us to return an answer too large).
6552 // float4 result = as_float4(as_int4(xf*recip) + 2);
6553 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6554 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6555 N1 = DAG.getConstant(2, dl, MVT::i32);
6556 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6557 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6558 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6559 // Convert back to integer and return.
6560 // return vmovn_u32(vcvt_s32_f32(result));
6561 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6562 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6566 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6567 EVT VT = Op.getNode()->getValueType(0);
6568 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6571 bool ExtraOp = false;
6572 switch (Op.getOpcode()) {
6573 default: llvm_unreachable("Invalid code");
6574 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6575 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6576 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6577 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6581 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6583 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6584 Op.getOperand(1), Op.getOperand(2));
6587 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6588 assert(Subtarget->isTargetDarwin());
6590 // For iOS, we want to call an alternative entry point: __sincos_stret,
6591 // return values are passed via sret.
6593 SDValue Arg = Op.getOperand(0);
6594 EVT ArgVT = Arg.getValueType();
6595 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6596 auto PtrVT = getPointerTy(DAG.getDataLayout());
6598 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6600 // Pair of floats / doubles used to pass the result.
6601 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6603 // Create stack object for sret.
6604 auto &DL = DAG.getDataLayout();
6605 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6606 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6607 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6608 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6614 Entry.Ty = RetTy->getPointerTo();
6615 Entry.isSExt = false;
6616 Entry.isZExt = false;
6617 Entry.isSRet = true;
6618 Args.push_back(Entry);
6622 Entry.isSExt = false;
6623 Entry.isZExt = false;
6624 Args.push_back(Entry);
6626 const char *LibcallName =
6627 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6628 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6630 TargetLowering::CallLoweringInfo CLI(DAG);
6631 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6632 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6634 .setDiscardResult();
6636 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6638 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6639 MachinePointerInfo(), false, false, false, 0);
6641 // Address of cos field.
6642 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6643 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6644 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6645 MachinePointerInfo(), false, false, false, 0);
6647 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6648 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6649 LoadSin.getValue(0), LoadCos.getValue(0));
6652 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6654 SDValue &Chain) const {
6655 EVT VT = Op.getValueType();
6656 assert((VT == MVT::i32 || VT == MVT::i64) &&
6657 "unexpected type for custom lowering DIV");
6660 const auto &DL = DAG.getDataLayout();
6661 const auto &TLI = DAG.getTargetLoweringInfo();
6663 const char *Name = nullptr;
6665 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6667 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6669 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6671 ARMTargetLowering::ArgListTy Args;
6673 for (auto AI : {1, 0}) {
6675 Arg.Node = Op.getOperand(AI);
6676 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6677 Args.push_back(Arg);
6680 CallLoweringInfo CLI(DAG);
6683 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6684 ES, std::move(Args), 0);
6686 return LowerCallTo(CLI).first;
6689 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6690 bool Signed) const {
6691 assert(Op.getValueType() == MVT::i32 &&
6692 "unexpected type for custom lowering DIV");
6695 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6696 DAG.getEntryNode(), Op.getOperand(1));
6698 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6701 void ARMTargetLowering::ExpandDIV_Windows(
6702 SDValue Op, SelectionDAG &DAG, bool Signed,
6703 SmallVectorImpl<SDValue> &Results) const {
6704 const auto &DL = DAG.getDataLayout();
6705 const auto &TLI = DAG.getTargetLoweringInfo();
6707 assert(Op.getValueType() == MVT::i64 &&
6708 "unexpected type for custom lowering DIV");
6711 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6712 DAG.getConstant(0, dl, MVT::i32));
6713 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6714 DAG.getConstant(1, dl, MVT::i32));
6715 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6718 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6720 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6722 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6723 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6724 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6725 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6727 Results.push_back(Lower);
6728 Results.push_back(Upper);
6731 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6732 // Monotonic load/store is legal for all targets
6733 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6736 // Acquire/Release load/store is not legal for targets without a
6737 // dmb or equivalent available.
6741 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6742 SmallVectorImpl<SDValue> &Results,
6744 const ARMSubtarget *Subtarget) {
6746 // Under Power Management extensions, the cycle-count is:
6747 // mrc p15, #0, <Rt>, c9, c13, #0
6748 SDValue Ops[] = { N->getOperand(0), // Chain
6749 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6750 DAG.getConstant(15, DL, MVT::i32),
6751 DAG.getConstant(0, DL, MVT::i32),
6752 DAG.getConstant(9, DL, MVT::i32),
6753 DAG.getConstant(13, DL, MVT::i32),
6754 DAG.getConstant(0, DL, MVT::i32)
6757 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6758 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6759 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6760 DAG.getConstant(0, DL, MVT::i32)));
6761 Results.push_back(Cycles32.getValue(1));
6764 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6765 switch (Op.getOpcode()) {
6766 default: llvm_unreachable("Don't know how to custom lower this!");
6767 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6768 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6769 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6770 case ISD::GlobalAddress:
6771 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6772 default: llvm_unreachable("unknown object format");
6774 return LowerGlobalAddressWindows(Op, DAG);
6776 return LowerGlobalAddressELF(Op, DAG);
6778 return LowerGlobalAddressDarwin(Op, DAG);
6780 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6781 case ISD::SELECT: return LowerSELECT(Op, DAG);
6782 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6783 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6784 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6785 case ISD::VASTART: return LowerVASTART(Op, DAG);
6786 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6787 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6788 case ISD::SINT_TO_FP:
6789 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6790 case ISD::FP_TO_SINT:
6791 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6792 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6793 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6794 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6795 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6796 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6797 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6798 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6799 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6801 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6804 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6805 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
6806 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
6807 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6808 case ISD::SRL_PARTS:
6809 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6811 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6812 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6813 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6814 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6815 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6816 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6817 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6818 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6819 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6820 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6821 case ISD::MUL: return LowerMUL(Op, DAG);
6823 if (Subtarget->isTargetWindows())
6824 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
6825 return LowerSDIV(Op, DAG);
6827 if (Subtarget->isTargetWindows())
6828 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
6829 return LowerUDIV(Op, DAG);
6833 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6838 return LowerXALUO(Op, DAG);
6839 case ISD::ATOMIC_LOAD:
6840 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6841 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6843 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6844 case ISD::DYNAMIC_STACKALLOC:
6845 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6846 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6847 llvm_unreachable("Don't know how to custom lower this!");
6848 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6849 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6850 case ARMISD::WIN__DBZCHK: return SDValue();
6854 /// ReplaceNodeResults - Replace the results of node with an illegal result
6855 /// type with new values built out of custom code.
6856 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6857 SmallVectorImpl<SDValue> &Results,
6858 SelectionDAG &DAG) const {
6860 switch (N->getOpcode()) {
6862 llvm_unreachable("Don't know how to custom expand this!");
6863 case ISD::READ_REGISTER:
6864 ExpandREAD_REGISTER(N, Results, DAG);
6867 Res = ExpandBITCAST(N, DAG);
6871 Res = Expand64BitShift(N, DAG, Subtarget);
6875 Res = LowerREM(N, DAG);
6877 case ISD::READCYCLECOUNTER:
6878 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6882 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6883 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6887 Results.push_back(Res);
6890 //===----------------------------------------------------------------------===//
6891 // ARM Scheduler Hooks
6892 //===----------------------------------------------------------------------===//
6894 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6895 /// registers the function context.
6896 void ARMTargetLowering::
6897 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6898 MachineBasicBlock *DispatchBB, int FI) const {
6899 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6900 DebugLoc dl = MI->getDebugLoc();
6901 MachineFunction *MF = MBB->getParent();
6902 MachineRegisterInfo *MRI = &MF->getRegInfo();
6903 MachineConstantPool *MCP = MF->getConstantPool();
6904 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6905 const Function *F = MF->getFunction();
6907 bool isThumb = Subtarget->isThumb();
6908 bool isThumb2 = Subtarget->isThumb2();
6910 unsigned PCLabelId = AFI->createPICLabelUId();
6911 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6912 ARMConstantPoolValue *CPV =
6913 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6914 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6916 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6917 : &ARM::GPRRegClass;
6919 // Grab constant pool and fixed stack memory operands.
6920 MachineMemOperand *CPMMO =
6921 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6922 MachineMemOperand::MOLoad, 4, 4);
6924 MachineMemOperand *FIMMOSt =
6925 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6926 MachineMemOperand::MOStore, 4, 4);
6928 // Load the address of the dispatch MBB into the jump buffer.
6930 // Incoming value: jbuf
6931 // ldr.n r5, LCPI1_1
6934 // str r5, [$jbuf, #+4] ; &jbuf[1]
6935 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6936 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6937 .addConstantPoolIndex(CPI)
6938 .addMemOperand(CPMMO));
6939 // Set the low bit because of thumb mode.
6940 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6942 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6943 .addReg(NewVReg1, RegState::Kill)
6945 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6946 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6947 .addReg(NewVReg2, RegState::Kill)
6949 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6950 .addReg(NewVReg3, RegState::Kill)
6952 .addImm(36) // &jbuf[1] :: pc
6953 .addMemOperand(FIMMOSt));
6954 } else if (isThumb) {
6955 // Incoming value: jbuf
6956 // ldr.n r1, LCPI1_4
6960 // add r2, $jbuf, #+4 ; &jbuf[1]
6962 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6963 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6964 .addConstantPoolIndex(CPI)
6965 .addMemOperand(CPMMO));
6966 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6967 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6968 .addReg(NewVReg1, RegState::Kill)
6970 // Set the low bit because of thumb mode.
6971 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6972 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6973 .addReg(ARM::CPSR, RegState::Define)
6975 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6976 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6977 .addReg(ARM::CPSR, RegState::Define)
6978 .addReg(NewVReg2, RegState::Kill)
6979 .addReg(NewVReg3, RegState::Kill));
6980 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6981 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6983 .addImm(36); // &jbuf[1] :: pc
6984 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6985 .addReg(NewVReg4, RegState::Kill)
6986 .addReg(NewVReg5, RegState::Kill)
6988 .addMemOperand(FIMMOSt));
6990 // Incoming value: jbuf
6993 // str r1, [$jbuf, #+4] ; &jbuf[1]
6994 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6995 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6996 .addConstantPoolIndex(CPI)
6998 .addMemOperand(CPMMO));
6999 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7000 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7001 .addReg(NewVReg1, RegState::Kill)
7002 .addImm(PCLabelId));
7003 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7004 .addReg(NewVReg2, RegState::Kill)
7006 .addImm(36) // &jbuf[1] :: pc
7007 .addMemOperand(FIMMOSt));
7011 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7012 MachineBasicBlock *MBB) const {
7013 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7014 DebugLoc dl = MI->getDebugLoc();
7015 MachineFunction *MF = MBB->getParent();
7016 MachineRegisterInfo *MRI = &MF->getRegInfo();
7017 MachineFrameInfo *MFI = MF->getFrameInfo();
7018 int FI = MFI->getFunctionContextIndex();
7020 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7021 : &ARM::GPRnopcRegClass;
7023 // Get a mapping of the call site numbers to all of the landing pads they're
7025 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7026 unsigned MaxCSNum = 0;
7027 MachineModuleInfo &MMI = MF->getMMI();
7028 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7030 if (!BB->isEHPad()) continue;
7032 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7034 for (MachineBasicBlock::iterator
7035 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7036 if (!II->isEHLabel()) continue;
7038 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7039 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7041 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7042 for (SmallVectorImpl<unsigned>::iterator
7043 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7044 CSI != CSE; ++CSI) {
7045 CallSiteNumToLPad[*CSI].push_back(BB);
7046 MaxCSNum = std::max(MaxCSNum, *CSI);
7052 // Get an ordered list of the machine basic blocks for the jump table.
7053 std::vector<MachineBasicBlock*> LPadList;
7054 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7055 LPadList.reserve(CallSiteNumToLPad.size());
7056 for (unsigned I = 1; I <= MaxCSNum; ++I) {
7057 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7058 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7059 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7060 LPadList.push_back(*II);
7061 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7065 assert(!LPadList.empty() &&
7066 "No landing pad destinations for the dispatch jump table!");
7068 // Create the jump table and associated information.
7069 MachineJumpTableInfo *JTI =
7070 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7071 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7072 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7074 // Create the MBBs for the dispatch code.
7076 // Shove the dispatch's address into the return slot in the function context.
7077 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7078 DispatchBB->setIsEHPad();
7080 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7081 unsigned trap_opcode;
7082 if (Subtarget->isThumb())
7083 trap_opcode = ARM::tTRAP;
7085 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7087 BuildMI(TrapBB, dl, TII->get(trap_opcode));
7088 DispatchBB->addSuccessor(TrapBB);
7090 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7091 DispatchBB->addSuccessor(DispContBB);
7094 MF->insert(MF->end(), DispatchBB);
7095 MF->insert(MF->end(), DispContBB);
7096 MF->insert(MF->end(), TrapBB);
7098 // Insert code into the entry block that creates and registers the function
7100 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7102 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7103 MachinePointerInfo::getFixedStack(*MF, FI),
7104 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7106 MachineInstrBuilder MIB;
7107 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7109 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7110 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7112 // Add a register mask with no preserved registers. This results in all
7113 // registers being marked as clobbered.
7114 MIB.addRegMask(RI.getNoPreservedMask());
7116 unsigned NumLPads = LPadList.size();
7117 if (Subtarget->isThumb2()) {
7118 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7119 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7122 .addMemOperand(FIMMOLd));
7124 if (NumLPads < 256) {
7125 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7127 .addImm(LPadList.size()));
7129 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7130 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7131 .addImm(NumLPads & 0xFFFF));
7133 unsigned VReg2 = VReg1;
7134 if ((NumLPads & 0xFFFF0000) != 0) {
7135 VReg2 = MRI->createVirtualRegister(TRC);
7136 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7138 .addImm(NumLPads >> 16));
7141 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7146 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7151 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7152 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7153 .addJumpTableIndex(MJTI));
7155 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7158 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7159 .addReg(NewVReg3, RegState::Kill)
7161 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7163 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7164 .addReg(NewVReg4, RegState::Kill)
7166 .addJumpTableIndex(MJTI);
7167 } else if (Subtarget->isThumb()) {
7168 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7169 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7172 .addMemOperand(FIMMOLd));
7174 if (NumLPads < 256) {
7175 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7179 MachineConstantPool *ConstantPool = MF->getConstantPool();
7180 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7181 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7183 // MachineConstantPool wants an explicit alignment.
7184 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7186 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7187 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7189 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7190 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7191 .addReg(VReg1, RegState::Define)
7192 .addConstantPoolIndex(Idx));
7193 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7198 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7203 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7204 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7205 .addReg(ARM::CPSR, RegState::Define)
7209 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7210 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7211 .addJumpTableIndex(MJTI));
7213 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7214 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7215 .addReg(ARM::CPSR, RegState::Define)
7216 .addReg(NewVReg2, RegState::Kill)
7219 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7220 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7222 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7223 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7224 .addReg(NewVReg4, RegState::Kill)
7226 .addMemOperand(JTMMOLd));
7228 unsigned NewVReg6 = NewVReg5;
7229 if (RelocM == Reloc::PIC_) {
7230 NewVReg6 = MRI->createVirtualRegister(TRC);
7231 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7232 .addReg(ARM::CPSR, RegState::Define)
7233 .addReg(NewVReg5, RegState::Kill)
7237 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7238 .addReg(NewVReg6, RegState::Kill)
7239 .addJumpTableIndex(MJTI);
7241 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7242 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7245 .addMemOperand(FIMMOLd));
7247 if (NumLPads < 256) {
7248 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7251 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7252 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7253 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7254 .addImm(NumLPads & 0xFFFF));
7256 unsigned VReg2 = VReg1;
7257 if ((NumLPads & 0xFFFF0000) != 0) {
7258 VReg2 = MRI->createVirtualRegister(TRC);
7259 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7261 .addImm(NumLPads >> 16));
7264 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7268 MachineConstantPool *ConstantPool = MF->getConstantPool();
7269 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7270 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7272 // MachineConstantPool wants an explicit alignment.
7273 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7275 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7276 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7278 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7279 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7280 .addReg(VReg1, RegState::Define)
7281 .addConstantPoolIndex(Idx)
7283 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7285 .addReg(VReg1, RegState::Kill));
7288 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7293 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7295 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7297 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7298 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7299 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7300 .addJumpTableIndex(MJTI));
7302 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7303 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7304 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7306 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7307 .addReg(NewVReg3, RegState::Kill)
7310 .addMemOperand(JTMMOLd));
7312 if (RelocM == Reloc::PIC_) {
7313 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7314 .addReg(NewVReg5, RegState::Kill)
7316 .addJumpTableIndex(MJTI);
7318 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7319 .addReg(NewVReg5, RegState::Kill)
7320 .addJumpTableIndex(MJTI);
7324 // Add the jump table entries as successors to the MBB.
7325 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7326 for (std::vector<MachineBasicBlock*>::iterator
7327 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7328 MachineBasicBlock *CurMBB = *I;
7329 if (SeenMBBs.insert(CurMBB).second)
7330 DispContBB->addSuccessor(CurMBB);
7333 // N.B. the order the invoke BBs are processed in doesn't matter here.
7334 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7335 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7336 for (MachineBasicBlock *BB : InvokeBBs) {
7338 // Remove the landing pad successor from the invoke block and replace it
7339 // with the new dispatch block.
7340 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7342 while (!Successors.empty()) {
7343 MachineBasicBlock *SMBB = Successors.pop_back_val();
7344 if (SMBB->isEHPad()) {
7345 BB->removeSuccessor(SMBB);
7346 MBBLPads.push_back(SMBB);
7350 BB->addSuccessor(DispatchBB);
7352 // Find the invoke call and mark all of the callee-saved registers as
7353 // 'implicit defined' so that they're spilled. This prevents code from
7354 // moving instructions to before the EH block, where they will never be
7356 for (MachineBasicBlock::reverse_iterator
7357 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7358 if (!II->isCall()) continue;
7360 DenseMap<unsigned, bool> DefRegs;
7361 for (MachineInstr::mop_iterator
7362 OI = II->operands_begin(), OE = II->operands_end();
7364 if (!OI->isReg()) continue;
7365 DefRegs[OI->getReg()] = true;
7368 MachineInstrBuilder MIB(*MF, &*II);
7370 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7371 unsigned Reg = SavedRegs[i];
7372 if (Subtarget->isThumb2() &&
7373 !ARM::tGPRRegClass.contains(Reg) &&
7374 !ARM::hGPRRegClass.contains(Reg))
7376 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7378 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7381 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7388 // Mark all former landing pads as non-landing pads. The dispatch is the only
7390 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7391 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7392 (*I)->setIsEHPad(false);
7394 // The instruction is gone now.
7395 MI->eraseFromParent();
7399 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7400 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7401 E = MBB->succ_end(); I != E; ++I)
7404 llvm_unreachable("Expecting a BB with two successors!");
7407 /// Return the load opcode for a given load size. If load size >= 8,
7408 /// neon opcode will be returned.
7409 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7411 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7412 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7414 return LdSize == 4 ? ARM::tLDRi
7415 : LdSize == 2 ? ARM::tLDRHi
7416 : LdSize == 1 ? ARM::tLDRBi : 0;
7418 return LdSize == 4 ? ARM::t2LDR_POST
7419 : LdSize == 2 ? ARM::t2LDRH_POST
7420 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7421 return LdSize == 4 ? ARM::LDR_POST_IMM
7422 : LdSize == 2 ? ARM::LDRH_POST
7423 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7426 /// Return the store opcode for a given store size. If store size >= 8,
7427 /// neon opcode will be returned.
7428 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7430 return StSize == 16 ? ARM::VST1q32wb_fixed
7431 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7433 return StSize == 4 ? ARM::tSTRi
7434 : StSize == 2 ? ARM::tSTRHi
7435 : StSize == 1 ? ARM::tSTRBi : 0;
7437 return StSize == 4 ? ARM::t2STR_POST
7438 : StSize == 2 ? ARM::t2STRH_POST
7439 : StSize == 1 ? ARM::t2STRB_POST : 0;
7440 return StSize == 4 ? ARM::STR_POST_IMM
7441 : StSize == 2 ? ARM::STRH_POST
7442 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7445 /// Emit a post-increment load operation with given size. The instructions
7446 /// will be added to BB at Pos.
7447 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7448 const TargetInstrInfo *TII, DebugLoc dl,
7449 unsigned LdSize, unsigned Data, unsigned AddrIn,
7450 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7451 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7452 assert(LdOpc != 0 && "Should have a load opcode");
7454 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7455 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7457 } else if (IsThumb1) {
7458 // load + update AddrIn
7459 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7460 .addReg(AddrIn).addImm(0));
7461 MachineInstrBuilder MIB =
7462 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7463 MIB = AddDefaultT1CC(MIB);
7464 MIB.addReg(AddrIn).addImm(LdSize);
7465 AddDefaultPred(MIB);
7466 } else if (IsThumb2) {
7467 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7468 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7471 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7472 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7473 .addReg(0).addImm(LdSize));
7477 /// Emit a post-increment store operation with given size. The instructions
7478 /// will be added to BB at Pos.
7479 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7480 const TargetInstrInfo *TII, DebugLoc dl,
7481 unsigned StSize, unsigned Data, unsigned AddrIn,
7482 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7483 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7484 assert(StOpc != 0 && "Should have a store opcode");
7486 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7487 .addReg(AddrIn).addImm(0).addReg(Data));
7488 } else if (IsThumb1) {
7489 // store + update AddrIn
7490 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7491 .addReg(AddrIn).addImm(0));
7492 MachineInstrBuilder MIB =
7493 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7494 MIB = AddDefaultT1CC(MIB);
7495 MIB.addReg(AddrIn).addImm(StSize);
7496 AddDefaultPred(MIB);
7497 } else if (IsThumb2) {
7498 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7499 .addReg(Data).addReg(AddrIn).addImm(StSize));
7501 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7502 .addReg(Data).addReg(AddrIn).addReg(0)
7508 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7509 MachineBasicBlock *BB) const {
7510 // This pseudo instruction has 3 operands: dst, src, size
7511 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7512 // Otherwise, we will generate unrolled scalar copies.
7513 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7514 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7515 MachineFunction::iterator It = BB;
7518 unsigned dest = MI->getOperand(0).getReg();
7519 unsigned src = MI->getOperand(1).getReg();
7520 unsigned SizeVal = MI->getOperand(2).getImm();
7521 unsigned Align = MI->getOperand(3).getImm();
7522 DebugLoc dl = MI->getDebugLoc();
7524 MachineFunction *MF = BB->getParent();
7525 MachineRegisterInfo &MRI = MF->getRegInfo();
7526 unsigned UnitSize = 0;
7527 const TargetRegisterClass *TRC = nullptr;
7528 const TargetRegisterClass *VecTRC = nullptr;
7530 bool IsThumb1 = Subtarget->isThumb1Only();
7531 bool IsThumb2 = Subtarget->isThumb2();
7535 } else if (Align & 2) {
7538 // Check whether we can use NEON instructions.
7539 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7540 Subtarget->hasNEON()) {
7541 if ((Align % 16 == 0) && SizeVal >= 16)
7543 else if ((Align % 8 == 0) && SizeVal >= 8)
7546 // Can't use NEON instructions.
7551 // Select the correct opcode and register class for unit size load/store
7552 bool IsNeon = UnitSize >= 8;
7553 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7555 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7556 : UnitSize == 8 ? &ARM::DPRRegClass
7559 unsigned BytesLeft = SizeVal % UnitSize;
7560 unsigned LoopSize = SizeVal - BytesLeft;
7562 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7563 // Use LDR and STR to copy.
7564 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7565 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7566 unsigned srcIn = src;
7567 unsigned destIn = dest;
7568 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7569 unsigned srcOut = MRI.createVirtualRegister(TRC);
7570 unsigned destOut = MRI.createVirtualRegister(TRC);
7571 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7572 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7573 IsThumb1, IsThumb2);
7574 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7575 IsThumb1, IsThumb2);
7580 // Handle the leftover bytes with LDRB and STRB.
7581 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7582 // [destOut] = STRB_POST(scratch, destIn, 1)
7583 for (unsigned i = 0; i < BytesLeft; i++) {
7584 unsigned srcOut = MRI.createVirtualRegister(TRC);
7585 unsigned destOut = MRI.createVirtualRegister(TRC);
7586 unsigned scratch = MRI.createVirtualRegister(TRC);
7587 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7588 IsThumb1, IsThumb2);
7589 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7590 IsThumb1, IsThumb2);
7594 MI->eraseFromParent(); // The instruction is gone now.
7598 // Expand the pseudo op to a loop.
7601 // movw varEnd, # --> with thumb2
7603 // ldrcp varEnd, idx --> without thumb2
7604 // fallthrough --> loopMBB
7606 // PHI varPhi, varEnd, varLoop
7607 // PHI srcPhi, src, srcLoop
7608 // PHI destPhi, dst, destLoop
7609 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7610 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7611 // subs varLoop, varPhi, #UnitSize
7613 // fallthrough --> exitMBB
7615 // epilogue to handle left-over bytes
7616 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7617 // [destOut] = STRB_POST(scratch, destLoop, 1)
7618 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7619 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7620 MF->insert(It, loopMBB);
7621 MF->insert(It, exitMBB);
7623 // Transfer the remainder of BB and its successor edges to exitMBB.
7624 exitMBB->splice(exitMBB->begin(), BB,
7625 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7626 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7628 // Load an immediate to varEnd.
7629 unsigned varEnd = MRI.createVirtualRegister(TRC);
7630 if (Subtarget->useMovt(*MF)) {
7631 unsigned Vtmp = varEnd;
7632 if ((LoopSize & 0xFFFF0000) != 0)
7633 Vtmp = MRI.createVirtualRegister(TRC);
7634 AddDefaultPred(BuildMI(BB, dl,
7635 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7636 Vtmp).addImm(LoopSize & 0xFFFF));
7638 if ((LoopSize & 0xFFFF0000) != 0)
7639 AddDefaultPred(BuildMI(BB, dl,
7640 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7643 .addImm(LoopSize >> 16));
7645 MachineConstantPool *ConstantPool = MF->getConstantPool();
7646 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7647 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7649 // MachineConstantPool wants an explicit alignment.
7650 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7652 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7653 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7656 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7657 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7659 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7660 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7662 BB->addSuccessor(loopMBB);
7664 // Generate the loop body:
7665 // varPhi = PHI(varLoop, varEnd)
7666 // srcPhi = PHI(srcLoop, src)
7667 // destPhi = PHI(destLoop, dst)
7668 MachineBasicBlock *entryBB = BB;
7670 unsigned varLoop = MRI.createVirtualRegister(TRC);
7671 unsigned varPhi = MRI.createVirtualRegister(TRC);
7672 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7673 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7674 unsigned destLoop = MRI.createVirtualRegister(TRC);
7675 unsigned destPhi = MRI.createVirtualRegister(TRC);
7677 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7678 .addReg(varLoop).addMBB(loopMBB)
7679 .addReg(varEnd).addMBB(entryBB);
7680 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7681 .addReg(srcLoop).addMBB(loopMBB)
7682 .addReg(src).addMBB(entryBB);
7683 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7684 .addReg(destLoop).addMBB(loopMBB)
7685 .addReg(dest).addMBB(entryBB);
7687 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7688 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7689 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7690 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7691 IsThumb1, IsThumb2);
7692 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7693 IsThumb1, IsThumb2);
7695 // Decrement loop variable by UnitSize.
7697 MachineInstrBuilder MIB =
7698 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7699 MIB = AddDefaultT1CC(MIB);
7700 MIB.addReg(varPhi).addImm(UnitSize);
7701 AddDefaultPred(MIB);
7703 MachineInstrBuilder MIB =
7704 BuildMI(*BB, BB->end(), dl,
7705 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7706 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7707 MIB->getOperand(5).setReg(ARM::CPSR);
7708 MIB->getOperand(5).setIsDef(true);
7710 BuildMI(*BB, BB->end(), dl,
7711 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7712 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7714 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7715 BB->addSuccessor(loopMBB);
7716 BB->addSuccessor(exitMBB);
7718 // Add epilogue to handle BytesLeft.
7720 MachineInstr *StartOfExit = exitMBB->begin();
7722 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7723 // [destOut] = STRB_POST(scratch, destLoop, 1)
7724 unsigned srcIn = srcLoop;
7725 unsigned destIn = destLoop;
7726 for (unsigned i = 0; i < BytesLeft; i++) {
7727 unsigned srcOut = MRI.createVirtualRegister(TRC);
7728 unsigned destOut = MRI.createVirtualRegister(TRC);
7729 unsigned scratch = MRI.createVirtualRegister(TRC);
7730 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7731 IsThumb1, IsThumb2);
7732 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7733 IsThumb1, IsThumb2);
7738 MI->eraseFromParent(); // The instruction is gone now.
7743 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7744 MachineBasicBlock *MBB) const {
7745 const TargetMachine &TM = getTargetMachine();
7746 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7747 DebugLoc DL = MI->getDebugLoc();
7749 assert(Subtarget->isTargetWindows() &&
7750 "__chkstk is only supported on Windows");
7751 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7753 // __chkstk takes the number of words to allocate on the stack in R4, and
7754 // returns the stack adjustment in number of bytes in R4. This will not
7755 // clober any other registers (other than the obvious lr).
7757 // Although, technically, IP should be considered a register which may be
7758 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7759 // thumb-2 environment, so there is no interworking required. As a result, we
7760 // do not expect a veneer to be emitted by the linker, clobbering IP.
7762 // Each module receives its own copy of __chkstk, so no import thunk is
7763 // required, again, ensuring that IP is not clobbered.
7765 // Finally, although some linkers may theoretically provide a trampoline for
7766 // out of range calls (which is quite common due to a 32M range limitation of
7767 // branches for Thumb), we can generate the long-call version via
7768 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7771 switch (TM.getCodeModel()) {
7772 case CodeModel::Small:
7773 case CodeModel::Medium:
7774 case CodeModel::Default:
7775 case CodeModel::Kernel:
7776 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7777 .addImm((unsigned)ARMCC::AL).addReg(0)
7778 .addExternalSymbol("__chkstk")
7779 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7780 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7781 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7783 case CodeModel::Large:
7784 case CodeModel::JITDefault: {
7785 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7786 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7788 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7789 .addExternalSymbol("__chkstk");
7790 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7791 .addImm((unsigned)ARMCC::AL).addReg(0)
7792 .addReg(Reg, RegState::Kill)
7793 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7794 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7795 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7800 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7802 .addReg(ARM::SP).addReg(ARM::R4)));
7804 MI->eraseFromParent();
7809 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7810 MachineBasicBlock *MBB) const {
7811 DebugLoc DL = MI->getDebugLoc();
7812 MachineFunction *MF = MBB->getParent();
7813 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7815 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7816 MF->push_back(ContBB);
7817 ContBB->splice(ContBB->begin(), MBB,
7818 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7819 MBB->addSuccessor(ContBB);
7821 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7822 MF->push_back(TrapBB);
7823 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7824 MBB->addSuccessor(TrapBB);
7826 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7827 .addReg(MI->getOperand(0).getReg())
7830 MI->eraseFromParent();
7835 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7836 MachineBasicBlock *BB) const {
7837 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7838 DebugLoc dl = MI->getDebugLoc();
7839 bool isThumb2 = Subtarget->isThumb2();
7840 switch (MI->getOpcode()) {
7843 llvm_unreachable("Unexpected instr type to insert");
7845 // The Thumb2 pre-indexed stores have the same MI operands, they just
7846 // define them differently in the .td files from the isel patterns, so
7847 // they need pseudos.
7848 case ARM::t2STR_preidx:
7849 MI->setDesc(TII->get(ARM::t2STR_PRE));
7851 case ARM::t2STRB_preidx:
7852 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7854 case ARM::t2STRH_preidx:
7855 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7858 case ARM::STRi_preidx:
7859 case ARM::STRBi_preidx: {
7860 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7861 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7862 // Decode the offset.
7863 unsigned Offset = MI->getOperand(4).getImm();
7864 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7865 Offset = ARM_AM::getAM2Offset(Offset);
7869 MachineMemOperand *MMO = *MI->memoperands_begin();
7870 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7871 .addOperand(MI->getOperand(0)) // Rn_wb
7872 .addOperand(MI->getOperand(1)) // Rt
7873 .addOperand(MI->getOperand(2)) // Rn
7874 .addImm(Offset) // offset (skip GPR==zero_reg)
7875 .addOperand(MI->getOperand(5)) // pred
7876 .addOperand(MI->getOperand(6))
7877 .addMemOperand(MMO);
7878 MI->eraseFromParent();
7881 case ARM::STRr_preidx:
7882 case ARM::STRBr_preidx:
7883 case ARM::STRH_preidx: {
7885 switch (MI->getOpcode()) {
7886 default: llvm_unreachable("unexpected opcode!");
7887 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7888 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7889 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7891 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7892 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7893 MIB.addOperand(MI->getOperand(i));
7894 MI->eraseFromParent();
7898 case ARM::tMOVCCr_pseudo: {
7899 // To "insert" a SELECT_CC instruction, we actually have to insert the
7900 // diamond control-flow pattern. The incoming instruction knows the
7901 // destination vreg to set, the condition code register to branch on, the
7902 // true/false values to select between, and a branch opcode to use.
7903 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7904 MachineFunction::iterator It = BB;
7910 // cmpTY ccX, r1, r2
7912 // fallthrough --> copy0MBB
7913 MachineBasicBlock *thisMBB = BB;
7914 MachineFunction *F = BB->getParent();
7915 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7916 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7917 F->insert(It, copy0MBB);
7918 F->insert(It, sinkMBB);
7920 // Transfer the remainder of BB and its successor edges to sinkMBB.
7921 sinkMBB->splice(sinkMBB->begin(), BB,
7922 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7923 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7925 BB->addSuccessor(copy0MBB);
7926 BB->addSuccessor(sinkMBB);
7928 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7929 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7932 // %FalseValue = ...
7933 // # fallthrough to sinkMBB
7936 // Update machine-CFG edges
7937 BB->addSuccessor(sinkMBB);
7940 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7943 BuildMI(*BB, BB->begin(), dl,
7944 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7945 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7946 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7948 MI->eraseFromParent(); // The pseudo instruction is gone now.
7953 case ARM::BCCZi64: {
7954 // If there is an unconditional branch to the other successor, remove it.
7955 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7957 // Compare both parts that make up the double comparison separately for
7959 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7961 unsigned LHS1 = MI->getOperand(1).getReg();
7962 unsigned LHS2 = MI->getOperand(2).getReg();
7964 AddDefaultPred(BuildMI(BB, dl,
7965 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7966 .addReg(LHS1).addImm(0));
7967 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7968 .addReg(LHS2).addImm(0)
7969 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7971 unsigned RHS1 = MI->getOperand(3).getReg();
7972 unsigned RHS2 = MI->getOperand(4).getReg();
7973 AddDefaultPred(BuildMI(BB, dl,
7974 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7975 .addReg(LHS1).addReg(RHS1));
7976 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7977 .addReg(LHS2).addReg(RHS2)
7978 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7981 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7982 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7983 if (MI->getOperand(0).getImm() == ARMCC::NE)
7984 std::swap(destMBB, exitMBB);
7986 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7987 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7989 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7991 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7993 MI->eraseFromParent(); // The pseudo instruction is gone now.
7997 case ARM::Int_eh_sjlj_setjmp:
7998 case ARM::Int_eh_sjlj_setjmp_nofp:
7999 case ARM::tInt_eh_sjlj_setjmp:
8000 case ARM::t2Int_eh_sjlj_setjmp:
8001 case ARM::t2Int_eh_sjlj_setjmp_nofp:
8004 case ARM::Int_eh_sjlj_setup_dispatch:
8005 EmitSjLjDispatchBlock(MI, BB);
8010 // To insert an ABS instruction, we have to insert the
8011 // diamond control-flow pattern. The incoming instruction knows the
8012 // source vreg to test against 0, the destination vreg to set,
8013 // the condition code register to branch on, the
8014 // true/false values to select between, and a branch opcode to use.
8019 // BCC (branch to SinkBB if V0 >= 0)
8020 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
8021 // SinkBB: V1 = PHI(V2, V3)
8022 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8023 MachineFunction::iterator BBI = BB;
8025 MachineFunction *Fn = BB->getParent();
8026 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8027 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8028 Fn->insert(BBI, RSBBB);
8029 Fn->insert(BBI, SinkBB);
8031 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8032 unsigned int ABSDstReg = MI->getOperand(0).getReg();
8033 bool ABSSrcKIll = MI->getOperand(1).isKill();
8034 bool isThumb2 = Subtarget->isThumb2();
8035 MachineRegisterInfo &MRI = Fn->getRegInfo();
8036 // In Thumb mode S must not be specified if source register is the SP or
8037 // PC and if destination register is the SP, so restrict register class
8038 unsigned NewRsbDstReg =
8039 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8041 // Transfer the remainder of BB and its successor edges to sinkMBB.
8042 SinkBB->splice(SinkBB->begin(), BB,
8043 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8044 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8046 BB->addSuccessor(RSBBB);
8047 BB->addSuccessor(SinkBB);
8049 // fall through to SinkMBB
8050 RSBBB->addSuccessor(SinkBB);
8052 // insert a cmp at the end of BB
8053 AddDefaultPred(BuildMI(BB, dl,
8054 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8055 .addReg(ABSSrcReg).addImm(0));
8057 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8059 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8060 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8062 // insert rsbri in RSBBB
8063 // Note: BCC and rsbri will be converted into predicated rsbmi
8064 // by if-conversion pass
8065 BuildMI(*RSBBB, RSBBB->begin(), dl,
8066 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8067 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8068 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8070 // insert PHI in SinkBB,
8071 // reuse ABSDstReg to not change uses of ABS instruction
8072 BuildMI(*SinkBB, SinkBB->begin(), dl,
8073 TII->get(ARM::PHI), ABSDstReg)
8074 .addReg(NewRsbDstReg).addMBB(RSBBB)
8075 .addReg(ABSSrcReg).addMBB(BB);
8077 // remove ABS instruction
8078 MI->eraseFromParent();
8080 // return last added BB
8083 case ARM::COPY_STRUCT_BYVAL_I32:
8085 return EmitStructByval(MI, BB);
8086 case ARM::WIN__CHKSTK:
8087 return EmitLowered__chkstk(MI, BB);
8088 case ARM::WIN__DBZCHK:
8089 return EmitLowered__dbzchk(MI, BB);
8093 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8094 SDNode *Node) const {
8095 const MCInstrDesc *MCID = &MI->getDesc();
8096 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8097 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8098 // operand is still set to noreg. If needed, set the optional operand's
8099 // register to CPSR, and remove the redundant implicit def.
8101 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8103 // Rename pseudo opcodes.
8104 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8106 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8107 MCID = &TII->get(NewOpc);
8109 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8110 "converted opcode should be the same except for cc_out");
8114 // Add the optional cc_out operand
8115 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8117 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8119 // Any ARM instruction that sets the 's' bit should specify an optional
8120 // "cc_out" operand in the last operand position.
8121 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8122 assert(!NewOpc && "Optional cc_out operand required");
8125 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8126 // since we already have an optional CPSR def.
8127 bool definesCPSR = false;
8128 bool deadCPSR = false;
8129 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8131 const MachineOperand &MO = MI->getOperand(i);
8132 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8136 MI->RemoveOperand(i);
8141 assert(!NewOpc && "Optional cc_out operand required");
8144 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8146 assert(!MI->getOperand(ccOutIdx).getReg() &&
8147 "expect uninitialized optional cc_out operand");
8151 // If this instruction was defined with an optional CPSR def and its dag node
8152 // had a live implicit CPSR def, then activate the optional CPSR def.
8153 MachineOperand &MO = MI->getOperand(ccOutIdx);
8154 MO.setReg(ARM::CPSR);
8158 //===----------------------------------------------------------------------===//
8159 // ARM Optimization Hooks
8160 //===----------------------------------------------------------------------===//
8162 // Helper function that checks if N is a null or all ones constant.
8163 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8164 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8167 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8170 // Return true if N is conditionally 0 or all ones.
8171 // Detects these expressions where cc is an i1 value:
8173 // (select cc 0, y) [AllOnes=0]
8174 // (select cc y, 0) [AllOnes=0]
8175 // (zext cc) [AllOnes=0]
8176 // (sext cc) [AllOnes=0/1]
8177 // (select cc -1, y) [AllOnes=1]
8178 // (select cc y, -1) [AllOnes=1]
8180 // Invert is set when N is the null/all ones constant when CC is false.
8181 // OtherOp is set to the alternative value of N.
8182 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8183 SDValue &CC, bool &Invert,
8185 SelectionDAG &DAG) {
8186 switch (N->getOpcode()) {
8187 default: return false;
8189 CC = N->getOperand(0);
8190 SDValue N1 = N->getOperand(1);
8191 SDValue N2 = N->getOperand(2);
8192 if (isZeroOrAllOnes(N1, AllOnes)) {
8197 if (isZeroOrAllOnes(N2, AllOnes)) {
8204 case ISD::ZERO_EXTEND:
8205 // (zext cc) can never be the all ones value.
8209 case ISD::SIGN_EXTEND: {
8211 EVT VT = N->getValueType(0);
8212 CC = N->getOperand(0);
8213 if (CC.getValueType() != MVT::i1)
8217 // When looking for an AllOnes constant, N is an sext, and the 'other'
8219 OtherOp = DAG.getConstant(0, dl, VT);
8220 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8221 // When looking for a 0 constant, N can be zext or sext.
8222 OtherOp = DAG.getConstant(1, dl, VT);
8224 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8231 // Combine a constant select operand into its use:
8233 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8234 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8235 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8236 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8237 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8239 // The transform is rejected if the select doesn't have a constant operand that
8240 // is null, or all ones when AllOnes is set.
8242 // Also recognize sext/zext from i1:
8244 // (add (zext cc), x) -> (select cc (add x, 1), x)
8245 // (add (sext cc), x) -> (select cc (add x, -1), x)
8247 // These transformations eventually create predicated instructions.
8249 // @param N The node to transform.
8250 // @param Slct The N operand that is a select.
8251 // @param OtherOp The other N operand (x above).
8252 // @param DCI Context.
8253 // @param AllOnes Require the select constant to be all ones instead of null.
8254 // @returns The new node, or SDValue() on failure.
8256 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8257 TargetLowering::DAGCombinerInfo &DCI,
8258 bool AllOnes = false) {
8259 SelectionDAG &DAG = DCI.DAG;
8260 EVT VT = N->getValueType(0);
8261 SDValue NonConstantVal;
8264 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8265 NonConstantVal, DAG))
8268 // Slct is now know to be the desired identity constant when CC is true.
8269 SDValue TrueVal = OtherOp;
8270 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8271 OtherOp, NonConstantVal);
8272 // Unless SwapSelectOps says CC should be false.
8274 std::swap(TrueVal, FalseVal);
8276 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8277 CCOp, TrueVal, FalseVal);
8280 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8282 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8283 TargetLowering::DAGCombinerInfo &DCI) {
8284 SDValue N0 = N->getOperand(0);
8285 SDValue N1 = N->getOperand(1);
8286 if (N0.getNode()->hasOneUse()) {
8287 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8288 if (Result.getNode())
8291 if (N1.getNode()->hasOneUse()) {
8292 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8293 if (Result.getNode())
8299 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8300 // (only after legalization).
8301 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8302 TargetLowering::DAGCombinerInfo &DCI,
8303 const ARMSubtarget *Subtarget) {
8305 // Only perform optimization if after legalize, and if NEON is available. We
8306 // also expected both operands to be BUILD_VECTORs.
8307 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8308 || N0.getOpcode() != ISD::BUILD_VECTOR
8309 || N1.getOpcode() != ISD::BUILD_VECTOR)
8312 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8313 EVT VT = N->getValueType(0);
8314 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8317 // Check that the vector operands are of the right form.
8318 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8319 // operands, where N is the size of the formed vector.
8320 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8321 // index such that we have a pair wise add pattern.
8323 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8324 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8326 SDValue Vec = N0->getOperand(0)->getOperand(0);
8327 SDNode *V = Vec.getNode();
8328 unsigned nextIndex = 0;
8330 // For each operands to the ADD which are BUILD_VECTORs,
8331 // check to see if each of their operands are an EXTRACT_VECTOR with
8332 // the same vector and appropriate index.
8333 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8334 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8335 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8337 SDValue ExtVec0 = N0->getOperand(i);
8338 SDValue ExtVec1 = N1->getOperand(i);
8340 // First operand is the vector, verify its the same.
8341 if (V != ExtVec0->getOperand(0).getNode() ||
8342 V != ExtVec1->getOperand(0).getNode())
8345 // Second is the constant, verify its correct.
8346 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8347 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8349 // For the constant, we want to see all the even or all the odd.
8350 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8351 || C1->getZExtValue() != nextIndex+1)
8360 // Create VPADDL node.
8361 SelectionDAG &DAG = DCI.DAG;
8362 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8366 // Build operand list.
8367 SmallVector<SDValue, 8> Ops;
8368 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8369 TLI.getPointerTy(DAG.getDataLayout())));
8371 // Input is the vector.
8374 // Get widened type and narrowed type.
8376 unsigned numElem = VT.getVectorNumElements();
8378 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8379 switch (inputLaneType.getSimpleVT().SimpleTy) {
8380 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8381 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8382 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8384 llvm_unreachable("Invalid vector element type for padd optimization.");
8387 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8388 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8389 return DAG.getNode(ExtOp, dl, VT, tmp);
8392 static SDValue findMUL_LOHI(SDValue V) {
8393 if (V->getOpcode() == ISD::UMUL_LOHI ||
8394 V->getOpcode() == ISD::SMUL_LOHI)
8399 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8400 TargetLowering::DAGCombinerInfo &DCI,
8401 const ARMSubtarget *Subtarget) {
8403 if (Subtarget->isThumb1Only()) return SDValue();
8405 // Only perform the checks after legalize when the pattern is available.
8406 if (DCI.isBeforeLegalize()) return SDValue();
8408 // Look for multiply add opportunities.
8409 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8410 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8411 // a glue link from the first add to the second add.
8412 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8413 // a S/UMLAL instruction.
8416 // / \ [no multiline comment]
8422 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8423 SDValue AddcOp0 = AddcNode->getOperand(0);
8424 SDValue AddcOp1 = AddcNode->getOperand(1);
8426 // Check if the two operands are from the same mul_lohi node.
8427 if (AddcOp0.getNode() == AddcOp1.getNode())
8430 assert(AddcNode->getNumValues() == 2 &&
8431 AddcNode->getValueType(0) == MVT::i32 &&
8432 "Expect ADDC with two result values. First: i32");
8434 // Check that we have a glued ADDC node.
8435 if (AddcNode->getValueType(1) != MVT::Glue)
8438 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8439 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8440 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8441 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8442 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8445 // Look for the glued ADDE.
8446 SDNode* AddeNode = AddcNode->getGluedUser();
8450 // Make sure it is really an ADDE.
8451 if (AddeNode->getOpcode() != ISD::ADDE)
8454 assert(AddeNode->getNumOperands() == 3 &&
8455 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8456 "ADDE node has the wrong inputs");
8458 // Check for the triangle shape.
8459 SDValue AddeOp0 = AddeNode->getOperand(0);
8460 SDValue AddeOp1 = AddeNode->getOperand(1);
8462 // Make sure that the ADDE operands are not coming from the same node.
8463 if (AddeOp0.getNode() == AddeOp1.getNode())
8466 // Find the MUL_LOHI node walking up ADDE's operands.
8467 bool IsLeftOperandMUL = false;
8468 SDValue MULOp = findMUL_LOHI(AddeOp0);
8469 if (MULOp == SDValue())
8470 MULOp = findMUL_LOHI(AddeOp1);
8472 IsLeftOperandMUL = true;
8473 if (MULOp == SDValue())
8476 // Figure out the right opcode.
8477 unsigned Opc = MULOp->getOpcode();
8478 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8480 // Figure out the high and low input values to the MLAL node.
8481 SDValue* HiAdd = nullptr;
8482 SDValue* LoMul = nullptr;
8483 SDValue* LowAdd = nullptr;
8485 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8486 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8489 if (IsLeftOperandMUL)
8495 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8496 // whose low result is fed to the ADDC we are checking.
8498 if (AddcOp0 == MULOp.getValue(0)) {
8502 if (AddcOp1 == MULOp.getValue(0)) {
8510 // Create the merged node.
8511 SelectionDAG &DAG = DCI.DAG;
8513 // Build operand list.
8514 SmallVector<SDValue, 8> Ops;
8515 Ops.push_back(LoMul->getOperand(0));
8516 Ops.push_back(LoMul->getOperand(1));
8517 Ops.push_back(*LowAdd);
8518 Ops.push_back(*HiAdd);
8520 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8521 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8523 // Replace the ADDs' nodes uses by the MLA node's values.
8524 SDValue HiMLALResult(MLALNode.getNode(), 1);
8525 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8527 SDValue LoMLALResult(MLALNode.getNode(), 0);
8528 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8530 // Return original node to notify the driver to stop replacing.
8531 SDValue resNode(AddcNode, 0);
8535 /// PerformADDCCombine - Target-specific dag combine transform from
8536 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8537 static SDValue PerformADDCCombine(SDNode *N,
8538 TargetLowering::DAGCombinerInfo &DCI,
8539 const ARMSubtarget *Subtarget) {
8541 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8545 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8546 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8547 /// called with the default operands, and if that fails, with commuted
8549 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8550 TargetLowering::DAGCombinerInfo &DCI,
8551 const ARMSubtarget *Subtarget){
8553 // Attempt to create vpaddl for this add.
8554 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8555 if (Result.getNode())
8558 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8559 if (N0.getNode()->hasOneUse()) {
8560 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8561 if (Result.getNode()) return Result;
8566 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8568 static SDValue PerformADDCombine(SDNode *N,
8569 TargetLowering::DAGCombinerInfo &DCI,
8570 const ARMSubtarget *Subtarget) {
8571 SDValue N0 = N->getOperand(0);
8572 SDValue N1 = N->getOperand(1);
8574 // First try with the default operand order.
8575 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8576 if (Result.getNode())
8579 // If that didn't work, try again with the operands commuted.
8580 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8583 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8585 static SDValue PerformSUBCombine(SDNode *N,
8586 TargetLowering::DAGCombinerInfo &DCI) {
8587 SDValue N0 = N->getOperand(0);
8588 SDValue N1 = N->getOperand(1);
8590 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8591 if (N1.getNode()->hasOneUse()) {
8592 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8593 if (Result.getNode()) return Result;
8599 /// PerformVMULCombine
8600 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8601 /// special multiplier accumulator forwarding.
8607 // However, for (A + B) * (A + B),
8614 static SDValue PerformVMULCombine(SDNode *N,
8615 TargetLowering::DAGCombinerInfo &DCI,
8616 const ARMSubtarget *Subtarget) {
8617 if (!Subtarget->hasVMLxForwarding())
8620 SelectionDAG &DAG = DCI.DAG;
8621 SDValue N0 = N->getOperand(0);
8622 SDValue N1 = N->getOperand(1);
8623 unsigned Opcode = N0.getOpcode();
8624 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8625 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8626 Opcode = N1.getOpcode();
8627 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8628 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8636 EVT VT = N->getValueType(0);
8638 SDValue N00 = N0->getOperand(0);
8639 SDValue N01 = N0->getOperand(1);
8640 return DAG.getNode(Opcode, DL, VT,
8641 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8642 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8645 static SDValue PerformMULCombine(SDNode *N,
8646 TargetLowering::DAGCombinerInfo &DCI,
8647 const ARMSubtarget *Subtarget) {
8648 SelectionDAG &DAG = DCI.DAG;
8650 if (Subtarget->isThumb1Only())
8653 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8656 EVT VT = N->getValueType(0);
8657 if (VT.is64BitVector() || VT.is128BitVector())
8658 return PerformVMULCombine(N, DCI, Subtarget);
8662 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8666 int64_t MulAmt = C->getSExtValue();
8667 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8669 ShiftAmt = ShiftAmt & (32 - 1);
8670 SDValue V = N->getOperand(0);
8674 MulAmt >>= ShiftAmt;
8677 if (isPowerOf2_32(MulAmt - 1)) {
8678 // (mul x, 2^N + 1) => (add (shl x, N), x)
8679 Res = DAG.getNode(ISD::ADD, DL, VT,
8681 DAG.getNode(ISD::SHL, DL, VT,
8683 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8685 } else if (isPowerOf2_32(MulAmt + 1)) {
8686 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8687 Res = DAG.getNode(ISD::SUB, DL, VT,
8688 DAG.getNode(ISD::SHL, DL, VT,
8690 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8696 uint64_t MulAmtAbs = -MulAmt;
8697 if (isPowerOf2_32(MulAmtAbs + 1)) {
8698 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8699 Res = DAG.getNode(ISD::SUB, DL, VT,
8701 DAG.getNode(ISD::SHL, DL, VT,
8703 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8705 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8706 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8707 Res = DAG.getNode(ISD::ADD, DL, VT,
8709 DAG.getNode(ISD::SHL, DL, VT,
8711 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8713 Res = DAG.getNode(ISD::SUB, DL, VT,
8714 DAG.getConstant(0, DL, MVT::i32), Res);
8721 Res = DAG.getNode(ISD::SHL, DL, VT,
8722 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8724 // Do not add new nodes to DAG combiner worklist.
8725 DCI.CombineTo(N, Res, false);
8729 static SDValue PerformANDCombine(SDNode *N,
8730 TargetLowering::DAGCombinerInfo &DCI,
8731 const ARMSubtarget *Subtarget) {
8733 // Attempt to use immediate-form VBIC
8734 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8736 EVT VT = N->getValueType(0);
8737 SelectionDAG &DAG = DCI.DAG;
8739 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8742 APInt SplatBits, SplatUndef;
8743 unsigned SplatBitSize;
8746 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8747 if (SplatBitSize <= 64) {
8749 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8750 SplatUndef.getZExtValue(), SplatBitSize,
8751 DAG, dl, VbicVT, VT.is128BitVector(),
8753 if (Val.getNode()) {
8755 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8756 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8757 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8762 if (!Subtarget->isThumb1Only()) {
8763 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8764 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8765 if (Result.getNode())
8772 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8773 static SDValue PerformORCombine(SDNode *N,
8774 TargetLowering::DAGCombinerInfo &DCI,
8775 const ARMSubtarget *Subtarget) {
8776 // Attempt to use immediate-form VORR
8777 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8779 EVT VT = N->getValueType(0);
8780 SelectionDAG &DAG = DCI.DAG;
8782 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8785 APInt SplatBits, SplatUndef;
8786 unsigned SplatBitSize;
8788 if (BVN && Subtarget->hasNEON() &&
8789 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8790 if (SplatBitSize <= 64) {
8792 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8793 SplatUndef.getZExtValue(), SplatBitSize,
8794 DAG, dl, VorrVT, VT.is128BitVector(),
8796 if (Val.getNode()) {
8798 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8799 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8800 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8805 if (!Subtarget->isThumb1Only()) {
8806 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8807 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8808 if (Result.getNode())
8812 // The code below optimizes (or (and X, Y), Z).
8813 // The AND operand needs to have a single user to make these optimizations
8815 SDValue N0 = N->getOperand(0);
8816 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8818 SDValue N1 = N->getOperand(1);
8820 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8821 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8822 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8824 unsigned SplatBitSize;
8827 APInt SplatBits0, SplatBits1;
8828 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8829 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8830 // Ensure that the second operand of both ands are constants
8831 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8832 HasAnyUndefs) && !HasAnyUndefs) {
8833 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8834 HasAnyUndefs) && !HasAnyUndefs) {
8835 // Ensure that the bit width of the constants are the same and that
8836 // the splat arguments are logical inverses as per the pattern we
8837 // are trying to simplify.
8838 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8839 SplatBits0 == ~SplatBits1) {
8840 // Canonicalize the vector type to make instruction selection
8842 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8843 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8847 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8853 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8856 // BFI is only available on V6T2+
8857 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8861 // 1) or (and A, mask), val => ARMbfi A, val, mask
8862 // iff (val & mask) == val
8864 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8865 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8866 // && mask == ~mask2
8867 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8868 // && ~mask == mask2
8869 // (i.e., copy a bitfield value into another bitfield of the same width)
8874 SDValue N00 = N0.getOperand(0);
8876 // The value and the mask need to be constants so we can verify this is
8877 // actually a bitfield set. If the mask is 0xffff, we can do better
8878 // via a movt instruction, so don't use BFI in that case.
8879 SDValue MaskOp = N0.getOperand(1);
8880 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8883 unsigned Mask = MaskC->getZExtValue();
8887 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8888 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8890 unsigned Val = N1C->getZExtValue();
8891 if ((Val & ~Mask) != Val)
8894 if (ARM::isBitFieldInvertedMask(Mask)) {
8895 Val >>= countTrailingZeros(~Mask);
8897 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8898 DAG.getConstant(Val, DL, MVT::i32),
8899 DAG.getConstant(Mask, DL, MVT::i32));
8901 // Do not add new nodes to DAG combiner worklist.
8902 DCI.CombineTo(N, Res, false);
8905 } else if (N1.getOpcode() == ISD::AND) {
8906 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8907 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8910 unsigned Mask2 = N11C->getZExtValue();
8912 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8914 if (ARM::isBitFieldInvertedMask(Mask) &&
8916 // The pack halfword instruction works better for masks that fit it,
8917 // so use that when it's available.
8918 if (Subtarget->hasT2ExtractPack() &&
8919 (Mask == 0xffff || Mask == 0xffff0000))
8922 unsigned amt = countTrailingZeros(Mask2);
8923 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8924 DAG.getConstant(amt, DL, MVT::i32));
8925 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8926 DAG.getConstant(Mask, DL, MVT::i32));
8927 // Do not add new nodes to DAG combiner worklist.
8928 DCI.CombineTo(N, Res, false);
8930 } else 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 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8938 unsigned lsb = countTrailingZeros(Mask);
8939 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8940 DAG.getConstant(lsb, DL, MVT::i32));
8941 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8942 DAG.getConstant(Mask2, DL, MVT::i32));
8943 // Do not add new nodes to DAG combiner worklist.
8944 DCI.CombineTo(N, Res, false);
8949 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8950 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8951 ARM::isBitFieldInvertedMask(~Mask)) {
8952 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8953 // where lsb(mask) == #shamt and masked bits of B are known zero.
8954 SDValue ShAmt = N00.getOperand(1);
8955 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8956 unsigned LSB = countTrailingZeros(Mask);
8960 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8961 DAG.getConstant(~Mask, DL, MVT::i32));
8963 // Do not add new nodes to DAG combiner worklist.
8964 DCI.CombineTo(N, Res, false);
8970 static SDValue PerformXORCombine(SDNode *N,
8971 TargetLowering::DAGCombinerInfo &DCI,
8972 const ARMSubtarget *Subtarget) {
8973 EVT VT = N->getValueType(0);
8974 SelectionDAG &DAG = DCI.DAG;
8976 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8979 if (!Subtarget->isThumb1Only()) {
8980 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8981 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8982 if (Result.getNode())
8989 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8990 /// the bits being cleared by the AND are not demanded by the BFI.
8991 static SDValue PerformBFICombine(SDNode *N,
8992 TargetLowering::DAGCombinerInfo &DCI) {
8993 SDValue N1 = N->getOperand(1);
8994 if (N1.getOpcode() == ISD::AND) {
8995 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8998 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8999 unsigned LSB = countTrailingZeros(~InvMask);
9000 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9002 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9003 "undefined behavior");
9004 unsigned Mask = (1u << Width) - 1;
9005 unsigned Mask2 = N11C->getZExtValue();
9006 if ((Mask & (~Mask2)) == 0)
9007 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9008 N->getOperand(0), N1.getOperand(0),
9014 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9015 /// ARMISD::VMOVRRD.
9016 static SDValue PerformVMOVRRDCombine(SDNode *N,
9017 TargetLowering::DAGCombinerInfo &DCI,
9018 const ARMSubtarget *Subtarget) {
9019 // vmovrrd(vmovdrr x, y) -> x,y
9020 SDValue InDouble = N->getOperand(0);
9021 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9022 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9024 // vmovrrd(load f64) -> (load i32), (load i32)
9025 SDNode *InNode = InDouble.getNode();
9026 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9027 InNode->getValueType(0) == MVT::f64 &&
9028 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9029 !cast<LoadSDNode>(InNode)->isVolatile()) {
9030 // TODO: Should this be done for non-FrameIndex operands?
9031 LoadSDNode *LD = cast<LoadSDNode>(InNode);
9033 SelectionDAG &DAG = DCI.DAG;
9035 SDValue BasePtr = LD->getBasePtr();
9036 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9037 LD->getPointerInfo(), LD->isVolatile(),
9038 LD->isNonTemporal(), LD->isInvariant(),
9039 LD->getAlignment());
9041 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9042 DAG.getConstant(4, DL, MVT::i32));
9043 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9044 LD->getPointerInfo(), LD->isVolatile(),
9045 LD->isNonTemporal(), LD->isInvariant(),
9046 std::min(4U, LD->getAlignment() / 2));
9048 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9049 if (DCI.DAG.getDataLayout().isBigEndian())
9050 std::swap (NewLD1, NewLD2);
9051 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9058 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9059 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
9060 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9061 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9062 SDValue Op0 = N->getOperand(0);
9063 SDValue Op1 = N->getOperand(1);
9064 if (Op0.getOpcode() == ISD::BITCAST)
9065 Op0 = Op0.getOperand(0);
9066 if (Op1.getOpcode() == ISD::BITCAST)
9067 Op1 = Op1.getOperand(0);
9068 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9069 Op0.getNode() == Op1.getNode() &&
9070 Op0.getResNo() == 0 && Op1.getResNo() == 1)
9071 return DAG.getNode(ISD::BITCAST, SDLoc(N),
9072 N->getValueType(0), Op0.getOperand(0));
9076 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9077 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9078 /// i64 vector to have f64 elements, since the value can then be loaded
9079 /// directly into a VFP register.
9080 static bool hasNormalLoadOperand(SDNode *N) {
9081 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9082 for (unsigned i = 0; i < NumElts; ++i) {
9083 SDNode *Elt = N->getOperand(i).getNode();
9084 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9090 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9091 /// ISD::BUILD_VECTOR.
9092 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9093 TargetLowering::DAGCombinerInfo &DCI,
9094 const ARMSubtarget *Subtarget) {
9095 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9096 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9097 // into a pair of GPRs, which is fine when the value is used as a scalar,
9098 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9099 SelectionDAG &DAG = DCI.DAG;
9100 if (N->getNumOperands() == 2) {
9101 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9106 // Load i64 elements as f64 values so that type legalization does not split
9107 // them up into i32 values.
9108 EVT VT = N->getValueType(0);
9109 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9112 SmallVector<SDValue, 8> Ops;
9113 unsigned NumElts = VT.getVectorNumElements();
9114 for (unsigned i = 0; i < NumElts; ++i) {
9115 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9117 // Make the DAGCombiner fold the bitcast.
9118 DCI.AddToWorklist(V.getNode());
9120 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9121 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9122 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9125 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9127 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9128 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9129 // At that time, we may have inserted bitcasts from integer to float.
9130 // If these bitcasts have survived DAGCombine, change the lowering of this
9131 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9132 // force to use floating point types.
9134 // Make sure we can change the type of the vector.
9135 // This is possible iff:
9136 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9137 // 1.1. Vector is used only once.
9138 // 1.2. Use is a bit convert to an integer type.
9139 // 2. The size of its operands are 32-bits (64-bits are not legal).
9140 EVT VT = N->getValueType(0);
9141 EVT EltVT = VT.getVectorElementType();
9143 // Check 1.1. and 2.
9144 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9147 // By construction, the input type must be float.
9148 assert(EltVT == MVT::f32 && "Unexpected type!");
9151 SDNode *Use = *N->use_begin();
9152 if (Use->getOpcode() != ISD::BITCAST ||
9153 Use->getValueType(0).isFloatingPoint())
9156 // Check profitability.
9157 // Model is, if more than half of the relevant operands are bitcast from
9158 // i32, turn the build_vector into a sequence of insert_vector_elt.
9159 // Relevant operands are everything that is not statically
9160 // (i.e., at compile time) bitcasted.
9161 unsigned NumOfBitCastedElts = 0;
9162 unsigned NumElts = VT.getVectorNumElements();
9163 unsigned NumOfRelevantElts = NumElts;
9164 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9165 SDValue Elt = N->getOperand(Idx);
9166 if (Elt->getOpcode() == ISD::BITCAST) {
9167 // Assume only bit cast to i32 will go away.
9168 if (Elt->getOperand(0).getValueType() == MVT::i32)
9169 ++NumOfBitCastedElts;
9170 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9171 // Constants are statically casted, thus do not count them as
9172 // relevant operands.
9173 --NumOfRelevantElts;
9176 // Check if more than half of the elements require a non-free bitcast.
9177 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9180 SelectionDAG &DAG = DCI.DAG;
9181 // Create the new vector type.
9182 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9183 // Check if the type is legal.
9184 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9185 if (!TLI.isTypeLegal(VecVT))
9189 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9190 // => BITCAST INSERT_VECTOR_ELT
9191 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9193 SDValue Vec = DAG.getUNDEF(VecVT);
9195 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9196 SDValue V = N->getOperand(Idx);
9197 if (V.getOpcode() == ISD::UNDEF)
9199 if (V.getOpcode() == ISD::BITCAST &&
9200 V->getOperand(0).getValueType() == MVT::i32)
9201 // Fold obvious case.
9202 V = V.getOperand(0);
9204 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9205 // Make the DAGCombiner fold the bitcasts.
9206 DCI.AddToWorklist(V.getNode());
9208 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9209 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9211 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9212 // Make the DAGCombiner fold the bitcasts.
9213 DCI.AddToWorklist(Vec.getNode());
9217 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9218 /// ISD::INSERT_VECTOR_ELT.
9219 static SDValue PerformInsertEltCombine(SDNode *N,
9220 TargetLowering::DAGCombinerInfo &DCI) {
9221 // Bitcast an i64 load inserted into a vector to f64.
9222 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9223 EVT VT = N->getValueType(0);
9224 SDNode *Elt = N->getOperand(1).getNode();
9225 if (VT.getVectorElementType() != MVT::i64 ||
9226 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9229 SelectionDAG &DAG = DCI.DAG;
9231 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9232 VT.getVectorNumElements());
9233 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9234 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9235 // Make the DAGCombiner fold the bitcasts.
9236 DCI.AddToWorklist(Vec.getNode());
9237 DCI.AddToWorklist(V.getNode());
9238 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9239 Vec, V, N->getOperand(2));
9240 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9243 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9244 /// ISD::VECTOR_SHUFFLE.
9245 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9246 // The LLVM shufflevector instruction does not require the shuffle mask
9247 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9248 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9249 // operands do not match the mask length, they are extended by concatenating
9250 // them with undef vectors. That is probably the right thing for other
9251 // targets, but for NEON it is better to concatenate two double-register
9252 // size vector operands into a single quad-register size vector. Do that
9253 // transformation here:
9254 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9255 // shuffle(concat(v1, v2), undef)
9256 SDValue Op0 = N->getOperand(0);
9257 SDValue Op1 = N->getOperand(1);
9258 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9259 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9260 Op0.getNumOperands() != 2 ||
9261 Op1.getNumOperands() != 2)
9263 SDValue Concat0Op1 = Op0.getOperand(1);
9264 SDValue Concat1Op1 = Op1.getOperand(1);
9265 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9266 Concat1Op1.getOpcode() != ISD::UNDEF)
9268 // Skip the transformation if any of the types are illegal.
9269 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9270 EVT VT = N->getValueType(0);
9271 if (!TLI.isTypeLegal(VT) ||
9272 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9273 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9276 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9277 Op0.getOperand(0), Op1.getOperand(0));
9278 // Translate the shuffle mask.
9279 SmallVector<int, 16> NewMask;
9280 unsigned NumElts = VT.getVectorNumElements();
9281 unsigned HalfElts = NumElts/2;
9282 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9283 for (unsigned n = 0; n < NumElts; ++n) {
9284 int MaskElt = SVN->getMaskElt(n);
9286 if (MaskElt < (int)HalfElts)
9288 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9289 NewElt = HalfElts + MaskElt - NumElts;
9290 NewMask.push_back(NewElt);
9292 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9293 DAG.getUNDEF(VT), NewMask.data());
9296 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9297 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9298 /// base address updates.
9299 /// For generic load/stores, the memory type is assumed to be a vector.
9300 /// The caller is assumed to have checked legality.
9301 static SDValue CombineBaseUpdate(SDNode *N,
9302 TargetLowering::DAGCombinerInfo &DCI) {
9303 SelectionDAG &DAG = DCI.DAG;
9304 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9305 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9306 const bool isStore = N->getOpcode() == ISD::STORE;
9307 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9308 SDValue Addr = N->getOperand(AddrOpIdx);
9309 MemSDNode *MemN = cast<MemSDNode>(N);
9312 // Search for a use of the address operand that is an increment.
9313 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9314 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9316 if (User->getOpcode() != ISD::ADD ||
9317 UI.getUse().getResNo() != Addr.getResNo())
9320 // Check that the add is independent of the load/store. Otherwise, folding
9321 // it would create a cycle.
9322 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9325 // Find the new opcode for the updating load/store.
9326 bool isLoadOp = true;
9327 bool isLaneOp = false;
9328 unsigned NewOpc = 0;
9329 unsigned NumVecs = 0;
9331 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9333 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9334 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9336 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9338 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9340 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9342 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9343 NumVecs = 2; isLaneOp = true; break;
9344 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9345 NumVecs = 3; isLaneOp = true; break;
9346 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9347 NumVecs = 4; isLaneOp = true; break;
9348 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9349 NumVecs = 1; isLoadOp = false; break;
9350 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9351 NumVecs = 2; isLoadOp = false; break;
9352 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9353 NumVecs = 3; isLoadOp = false; break;
9354 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9355 NumVecs = 4; isLoadOp = false; break;
9356 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9357 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9358 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9359 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9360 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9361 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9365 switch (N->getOpcode()) {
9366 default: llvm_unreachable("unexpected opcode for Neon base update");
9367 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9368 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9369 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9370 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9371 NumVecs = 1; isLaneOp = false; break;
9372 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9373 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9377 // Find the size of memory referenced by the load/store.
9380 VecTy = N->getValueType(0);
9381 } else if (isIntrinsic) {
9382 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9384 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9385 VecTy = N->getOperand(1).getValueType();
9388 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9390 NumBytes /= VecTy.getVectorNumElements();
9392 // If the increment is a constant, it must match the memory ref size.
9393 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9394 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9395 uint64_t IncVal = CInc->getZExtValue();
9396 if (IncVal != NumBytes)
9398 } else if (NumBytes >= 3 * 16) {
9399 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9400 // separate instructions that make it harder to use a non-constant update.
9404 // OK, we found an ADD we can fold into the base update.
9405 // Now, create a _UPD node, taking care of not breaking alignment.
9407 EVT AlignedVecTy = VecTy;
9408 unsigned Alignment = MemN->getAlignment();
9410 // If this is a less-than-standard-aligned load/store, change the type to
9411 // match the standard alignment.
9412 // The alignment is overlooked when selecting _UPD variants; and it's
9413 // easier to introduce bitcasts here than fix that.
9414 // There are 3 ways to get to this base-update combine:
9415 // - intrinsics: they are assumed to be properly aligned (to the standard
9416 // alignment of the memory type), so we don't need to do anything.
9417 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9418 // intrinsics, so, likewise, there's nothing to do.
9419 // - generic load/store instructions: the alignment is specified as an
9420 // explicit operand, rather than implicitly as the standard alignment
9421 // of the memory type (like the intrisics). We need to change the
9422 // memory type to match the explicit alignment. That way, we don't
9423 // generate non-standard-aligned ARMISD::VLDx nodes.
9424 if (isa<LSBaseSDNode>(N)) {
9427 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9428 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9429 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9430 assert(!isLaneOp && "Unexpected generic load/store lane.");
9431 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9432 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9434 // Don't set an explicit alignment on regular load/stores that we want
9435 // to transform to VLD/VST 1_UPD nodes.
9436 // This matches the behavior of regular load/stores, which only get an
9437 // explicit alignment if the MMO alignment is larger than the standard
9438 // alignment of the memory type.
9439 // Intrinsics, however, always get an explicit alignment, set to the
9440 // alignment of the MMO.
9444 // Create the new updating load/store node.
9445 // First, create an SDVTList for the new updating node's results.
9447 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9449 for (n = 0; n < NumResultVecs; ++n)
9450 Tys[n] = AlignedVecTy;
9451 Tys[n++] = MVT::i32;
9452 Tys[n] = MVT::Other;
9453 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9455 // Then, gather the new node's operands.
9456 SmallVector<SDValue, 8> Ops;
9457 Ops.push_back(N->getOperand(0)); // incoming chain
9458 Ops.push_back(N->getOperand(AddrOpIdx));
9461 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9462 // Try to match the intrinsic's signature
9463 Ops.push_back(StN->getValue());
9465 // Loads (and of course intrinsics) match the intrinsics' signature,
9466 // so just add all but the alignment operand.
9467 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9468 Ops.push_back(N->getOperand(i));
9471 // For all node types, the alignment operand is always the last one.
9472 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9474 // If this is a non-standard-aligned STORE, the penultimate operand is the
9475 // stored value. Bitcast it to the aligned type.
9476 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9477 SDValue &StVal = Ops[Ops.size()-2];
9478 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9481 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9483 MemN->getMemOperand());
9486 SmallVector<SDValue, 5> NewResults;
9487 for (unsigned i = 0; i < NumResultVecs; ++i)
9488 NewResults.push_back(SDValue(UpdN.getNode(), i));
9490 // If this is an non-standard-aligned LOAD, the first result is the loaded
9491 // value. Bitcast it to the expected result type.
9492 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9493 SDValue &LdVal = NewResults[0];
9494 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9497 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9498 DCI.CombineTo(N, NewResults);
9499 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9506 static SDValue PerformVLDCombine(SDNode *N,
9507 TargetLowering::DAGCombinerInfo &DCI) {
9508 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9511 return CombineBaseUpdate(N, DCI);
9514 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9515 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9516 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9518 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9519 SelectionDAG &DAG = DCI.DAG;
9520 EVT VT = N->getValueType(0);
9521 // vldN-dup instructions only support 64-bit vectors for N > 1.
9522 if (!VT.is64BitVector())
9525 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9526 SDNode *VLD = N->getOperand(0).getNode();
9527 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9529 unsigned NumVecs = 0;
9530 unsigned NewOpc = 0;
9531 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9532 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9534 NewOpc = ARMISD::VLD2DUP;
9535 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9537 NewOpc = ARMISD::VLD3DUP;
9538 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9540 NewOpc = ARMISD::VLD4DUP;
9545 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9546 // numbers match the load.
9547 unsigned VLDLaneNo =
9548 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9549 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9551 // Ignore uses of the chain result.
9552 if (UI.getUse().getResNo() == NumVecs)
9555 if (User->getOpcode() != ARMISD::VDUPLANE ||
9556 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9560 // Create the vldN-dup node.
9563 for (n = 0; n < NumVecs; ++n)
9565 Tys[n] = MVT::Other;
9566 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9567 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9568 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9569 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9570 Ops, VLDMemInt->getMemoryVT(),
9571 VLDMemInt->getMemOperand());
9574 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9576 unsigned ResNo = UI.getUse().getResNo();
9577 // Ignore uses of the chain result.
9578 if (ResNo == NumVecs)
9581 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9584 // Now the vldN-lane intrinsic is dead except for its chain result.
9585 // Update uses of the chain.
9586 std::vector<SDValue> VLDDupResults;
9587 for (unsigned n = 0; n < NumVecs; ++n)
9588 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9589 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9590 DCI.CombineTo(VLD, VLDDupResults);
9595 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9596 /// ARMISD::VDUPLANE.
9597 static SDValue PerformVDUPLANECombine(SDNode *N,
9598 TargetLowering::DAGCombinerInfo &DCI) {
9599 SDValue Op = N->getOperand(0);
9601 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9602 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9603 if (CombineVLDDUP(N, DCI))
9604 return SDValue(N, 0);
9606 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9607 // redundant. Ignore bit_converts for now; element sizes are checked below.
9608 while (Op.getOpcode() == ISD::BITCAST)
9609 Op = Op.getOperand(0);
9610 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9613 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9614 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9615 // The canonical VMOV for a zero vector uses a 32-bit element size.
9616 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9618 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9620 EVT VT = N->getValueType(0);
9621 if (EltSize > VT.getVectorElementType().getSizeInBits())
9624 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9627 static SDValue PerformLOADCombine(SDNode *N,
9628 TargetLowering::DAGCombinerInfo &DCI) {
9629 EVT VT = N->getValueType(0);
9631 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9632 if (ISD::isNormalLoad(N) && VT.isVector() &&
9633 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9634 return CombineBaseUpdate(N, DCI);
9639 /// PerformSTORECombine - Target-specific dag combine xforms for
9641 static SDValue PerformSTORECombine(SDNode *N,
9642 TargetLowering::DAGCombinerInfo &DCI) {
9643 StoreSDNode *St = cast<StoreSDNode>(N);
9644 if (St->isVolatile())
9647 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9648 // pack all of the elements in one place. Next, store to memory in fewer
9650 SDValue StVal = St->getValue();
9651 EVT VT = StVal.getValueType();
9652 if (St->isTruncatingStore() && VT.isVector()) {
9653 SelectionDAG &DAG = DCI.DAG;
9654 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9655 EVT StVT = St->getMemoryVT();
9656 unsigned NumElems = VT.getVectorNumElements();
9657 assert(StVT != VT && "Cannot truncate to the same type");
9658 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9659 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9661 // From, To sizes and ElemCount must be pow of two
9662 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9664 // We are going to use the original vector elt for storing.
9665 // Accumulated smaller vector elements must be a multiple of the store size.
9666 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9668 unsigned SizeRatio = FromEltSz / ToEltSz;
9669 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9671 // Create a type on which we perform the shuffle.
9672 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9673 NumElems*SizeRatio);
9674 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9677 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9678 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9679 for (unsigned i = 0; i < NumElems; ++i)
9680 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9681 ? (i + 1) * SizeRatio - 1
9684 // Can't shuffle using an illegal type.
9685 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9687 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9688 DAG.getUNDEF(WideVec.getValueType()),
9690 // At this point all of the data is stored at the bottom of the
9691 // register. We now need to save it to mem.
9693 // Find the largest store unit
9694 MVT StoreType = MVT::i8;
9695 for (MVT Tp : MVT::integer_valuetypes()) {
9696 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9699 // Didn't find a legal store type.
9700 if (!TLI.isTypeLegal(StoreType))
9703 // Bitcast the original vector into a vector of store-size units
9704 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9705 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9706 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9707 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9708 SmallVector<SDValue, 8> Chains;
9709 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9710 TLI.getPointerTy(DAG.getDataLayout()));
9711 SDValue BasePtr = St->getBasePtr();
9713 // Perform one or more big stores into memory.
9714 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9715 for (unsigned I = 0; I < E; I++) {
9716 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9717 StoreType, ShuffWide,
9718 DAG.getIntPtrConstant(I, DL));
9719 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9720 St->getPointerInfo(), St->isVolatile(),
9721 St->isNonTemporal(), St->getAlignment());
9722 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9724 Chains.push_back(Ch);
9726 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9729 if (!ISD::isNormalStore(St))
9732 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9733 // ARM stores of arguments in the same cache line.
9734 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9735 StVal.getNode()->hasOneUse()) {
9736 SelectionDAG &DAG = DCI.DAG;
9737 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9739 SDValue BasePtr = St->getBasePtr();
9740 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9741 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9742 BasePtr, St->getPointerInfo(), St->isVolatile(),
9743 St->isNonTemporal(), St->getAlignment());
9745 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9746 DAG.getConstant(4, DL, MVT::i32));
9747 return DAG.getStore(NewST1.getValue(0), DL,
9748 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9749 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9750 St->isNonTemporal(),
9751 std::min(4U, St->getAlignment() / 2));
9754 if (StVal.getValueType() == MVT::i64 &&
9755 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9757 // Bitcast an i64 store extracted from a vector to f64.
9758 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9759 SelectionDAG &DAG = DCI.DAG;
9761 SDValue IntVec = StVal.getOperand(0);
9762 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9763 IntVec.getValueType().getVectorNumElements());
9764 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9765 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9766 Vec, StVal.getOperand(1));
9768 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9769 // Make the DAGCombiner fold the bitcasts.
9770 DCI.AddToWorklist(Vec.getNode());
9771 DCI.AddToWorklist(ExtElt.getNode());
9772 DCI.AddToWorklist(V.getNode());
9773 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9774 St->getPointerInfo(), St->isVolatile(),
9775 St->isNonTemporal(), St->getAlignment(),
9779 // If this is a legal vector store, try to combine it into a VST1_UPD.
9780 if (ISD::isNormalStore(N) && VT.isVector() &&
9781 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9782 return CombineBaseUpdate(N, DCI);
9787 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9788 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9789 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9793 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9795 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9800 APFloat APF = C->getValueAPF();
9801 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9802 != APFloat::opOK || !isExact)
9805 c0 = (I == 0) ? cN : c0;
9806 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9813 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9814 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9815 /// when the VMUL has a constant operand that is a power of 2.
9817 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9818 /// vmul.f32 d16, d17, d16
9819 /// vcvt.s32.f32 d16, d16
9821 /// vcvt.s32.f32 d16, d16, #3
9822 static SDValue PerformVCVTCombine(SDNode *N,
9823 TargetLowering::DAGCombinerInfo &DCI,
9824 const ARMSubtarget *Subtarget) {
9825 SelectionDAG &DAG = DCI.DAG;
9826 SDValue Op = N->getOperand(0);
9828 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9829 Op.getOpcode() != ISD::FMUL)
9833 SDValue N0 = Op->getOperand(0);
9834 SDValue ConstVec = Op->getOperand(1);
9835 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9837 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9838 !isConstVecPow2(ConstVec, isSigned, C))
9841 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9842 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9843 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9844 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9846 // These instructions only exist converting from f32 to i32. We can handle
9847 // smaller integers by generating an extra truncate, but larger ones would
9848 // be lossy. We also can't handle more then 4 lanes, since these intructions
9849 // only support v2i32/v4i32 types.
9854 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9855 Intrinsic::arm_neon_vcvtfp2fxu;
9856 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9857 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9858 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9860 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9862 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9863 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9868 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9869 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9870 /// when the VDIV has a constant operand that is a power of 2.
9872 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9873 /// vcvt.f32.s32 d16, d16
9874 /// vdiv.f32 d16, d17, d16
9876 /// vcvt.f32.s32 d16, d16, #3
9877 static SDValue PerformVDIVCombine(SDNode *N,
9878 TargetLowering::DAGCombinerInfo &DCI,
9879 const ARMSubtarget *Subtarget) {
9880 SelectionDAG &DAG = DCI.DAG;
9881 SDValue Op = N->getOperand(0);
9882 unsigned OpOpcode = Op.getNode()->getOpcode();
9884 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9885 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9889 SDValue ConstVec = N->getOperand(1);
9890 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9892 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9893 !isConstVecPow2(ConstVec, isSigned, C))
9896 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9897 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9898 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9899 // These instructions only exist converting from i32 to f32. We can handle
9900 // smaller integers by generating an extra extend, but larger ones would
9906 SDValue ConvInput = Op.getOperand(0);
9907 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9908 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9909 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9910 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9913 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9914 Intrinsic::arm_neon_vcvtfxu2fp;
9915 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9917 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9918 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9921 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9922 /// operand of a vector shift operation, where all the elements of the
9923 /// build_vector must have the same constant integer value.
9924 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9925 // Ignore bit_converts.
9926 while (Op.getOpcode() == ISD::BITCAST)
9927 Op = Op.getOperand(0);
9928 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9929 APInt SplatBits, SplatUndef;
9930 unsigned SplatBitSize;
9932 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9933 HasAnyUndefs, ElementBits) ||
9934 SplatBitSize > ElementBits)
9936 Cnt = SplatBits.getSExtValue();
9940 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9941 /// operand of a vector shift left operation. That value must be in the range:
9942 /// 0 <= Value < ElementBits for a left shift; or
9943 /// 0 <= Value <= ElementBits for a long left shift.
9944 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9945 assert(VT.isVector() && "vector shift count is not a vector type");
9946 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9947 if (! getVShiftImm(Op, ElementBits, Cnt))
9949 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9952 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9953 /// operand of a vector shift right operation. For a shift opcode, the value
9954 /// is positive, but for an intrinsic the value count must be negative. The
9955 /// absolute value must be in the range:
9956 /// 1 <= |Value| <= ElementBits for a right shift; or
9957 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9958 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
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))
9965 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9966 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9973 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9974 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9975 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9978 // Don't do anything for most intrinsics.
9981 case Intrinsic::arm_neon_vabds:
9982 if (!N->getValueType(0).isInteger())
9984 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9985 N->getOperand(1), N->getOperand(2));
9986 case Intrinsic::arm_neon_vabdu:
9987 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9988 N->getOperand(1), N->getOperand(2));
9990 // Vector shifts: check for immediate versions and lower them.
9991 // Note: This is done during DAG combining instead of DAG legalizing because
9992 // the build_vectors for 64-bit vector element shift counts are generally
9993 // not legal, and it is hard to see their values after they get legalized to
9994 // loads from a constant pool.
9995 case Intrinsic::arm_neon_vshifts:
9996 case Intrinsic::arm_neon_vshiftu:
9997 case Intrinsic::arm_neon_vrshifts:
9998 case Intrinsic::arm_neon_vrshiftu:
9999 case Intrinsic::arm_neon_vrshiftn:
10000 case Intrinsic::arm_neon_vqshifts:
10001 case Intrinsic::arm_neon_vqshiftu:
10002 case Intrinsic::arm_neon_vqshiftsu:
10003 case Intrinsic::arm_neon_vqshiftns:
10004 case Intrinsic::arm_neon_vqshiftnu:
10005 case Intrinsic::arm_neon_vqshiftnsu:
10006 case Intrinsic::arm_neon_vqrshiftns:
10007 case Intrinsic::arm_neon_vqrshiftnu:
10008 case Intrinsic::arm_neon_vqrshiftnsu: {
10009 EVT VT = N->getOperand(1).getValueType();
10011 unsigned VShiftOpc = 0;
10014 case Intrinsic::arm_neon_vshifts:
10015 case Intrinsic::arm_neon_vshiftu:
10016 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10017 VShiftOpc = ARMISD::VSHL;
10020 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10021 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10022 ARMISD::VSHRs : ARMISD::VSHRu);
10027 case Intrinsic::arm_neon_vrshifts:
10028 case Intrinsic::arm_neon_vrshiftu:
10029 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10033 case Intrinsic::arm_neon_vqshifts:
10034 case Intrinsic::arm_neon_vqshiftu:
10035 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10039 case Intrinsic::arm_neon_vqshiftsu:
10040 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10042 llvm_unreachable("invalid shift count for vqshlu intrinsic");
10044 case Intrinsic::arm_neon_vrshiftn:
10045 case Intrinsic::arm_neon_vqshiftns:
10046 case Intrinsic::arm_neon_vqshiftnu:
10047 case Intrinsic::arm_neon_vqshiftnsu:
10048 case Intrinsic::arm_neon_vqrshiftns:
10049 case Intrinsic::arm_neon_vqrshiftnu:
10050 case Intrinsic::arm_neon_vqrshiftnsu:
10051 // Narrowing shifts require an immediate right shift.
10052 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10054 llvm_unreachable("invalid shift count for narrowing vector shift "
10058 llvm_unreachable("unhandled vector shift");
10062 case Intrinsic::arm_neon_vshifts:
10063 case Intrinsic::arm_neon_vshiftu:
10064 // Opcode already set above.
10066 case Intrinsic::arm_neon_vrshifts:
10067 VShiftOpc = ARMISD::VRSHRs; break;
10068 case Intrinsic::arm_neon_vrshiftu:
10069 VShiftOpc = ARMISD::VRSHRu; break;
10070 case Intrinsic::arm_neon_vrshiftn:
10071 VShiftOpc = ARMISD::VRSHRN; break;
10072 case Intrinsic::arm_neon_vqshifts:
10073 VShiftOpc = ARMISD::VQSHLs; break;
10074 case Intrinsic::arm_neon_vqshiftu:
10075 VShiftOpc = ARMISD::VQSHLu; break;
10076 case Intrinsic::arm_neon_vqshiftsu:
10077 VShiftOpc = ARMISD::VQSHLsu; break;
10078 case Intrinsic::arm_neon_vqshiftns:
10079 VShiftOpc = ARMISD::VQSHRNs; break;
10080 case Intrinsic::arm_neon_vqshiftnu:
10081 VShiftOpc = ARMISD::VQSHRNu; break;
10082 case Intrinsic::arm_neon_vqshiftnsu:
10083 VShiftOpc = ARMISD::VQSHRNsu; break;
10084 case Intrinsic::arm_neon_vqrshiftns:
10085 VShiftOpc = ARMISD::VQRSHRNs; break;
10086 case Intrinsic::arm_neon_vqrshiftnu:
10087 VShiftOpc = ARMISD::VQRSHRNu; break;
10088 case Intrinsic::arm_neon_vqrshiftnsu:
10089 VShiftOpc = ARMISD::VQRSHRNsu; break;
10093 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10094 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10097 case Intrinsic::arm_neon_vshiftins: {
10098 EVT VT = N->getOperand(1).getValueType();
10100 unsigned VShiftOpc = 0;
10102 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10103 VShiftOpc = ARMISD::VSLI;
10104 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10105 VShiftOpc = ARMISD::VSRI;
10107 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10111 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10112 N->getOperand(1), N->getOperand(2),
10113 DAG.getConstant(Cnt, dl, MVT::i32));
10116 case Intrinsic::arm_neon_vqrshifts:
10117 case Intrinsic::arm_neon_vqrshiftu:
10118 // No immediate versions of these to check for.
10125 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10126 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10127 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10128 /// vector element shift counts are generally not legal, and it is hard to see
10129 /// their values after they get legalized to loads from a constant pool.
10130 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10131 const ARMSubtarget *ST) {
10132 EVT VT = N->getValueType(0);
10133 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10134 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10135 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10136 SDValue N1 = N->getOperand(1);
10137 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10138 SDValue N0 = N->getOperand(0);
10139 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10140 DAG.MaskedValueIsZero(N0.getOperand(0),
10141 APInt::getHighBitsSet(32, 16)))
10142 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10146 // Nothing to be done for scalar shifts.
10147 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10148 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10151 assert(ST->hasNEON() && "unexpected vector shift");
10154 switch (N->getOpcode()) {
10155 default: llvm_unreachable("unexpected shift opcode");
10158 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10160 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10161 DAG.getConstant(Cnt, dl, MVT::i32));
10167 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10168 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10169 ARMISD::VSHRs : ARMISD::VSHRu);
10171 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10172 DAG.getConstant(Cnt, dl, MVT::i32));
10178 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10179 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10180 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10181 const ARMSubtarget *ST) {
10182 SDValue N0 = N->getOperand(0);
10184 // Check for sign- and zero-extensions of vector extract operations of 8-
10185 // and 16-bit vector elements. NEON supports these directly. They are
10186 // handled during DAG combining because type legalization will promote them
10187 // to 32-bit types and it is messy to recognize the operations after that.
10188 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10189 SDValue Vec = N0.getOperand(0);
10190 SDValue Lane = N0.getOperand(1);
10191 EVT VT = N->getValueType(0);
10192 EVT EltVT = N0.getValueType();
10193 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10195 if (VT == MVT::i32 &&
10196 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10197 TLI.isTypeLegal(Vec.getValueType()) &&
10198 isa<ConstantSDNode>(Lane)) {
10201 switch (N->getOpcode()) {
10202 default: llvm_unreachable("unexpected opcode");
10203 case ISD::SIGN_EXTEND:
10204 Opc = ARMISD::VGETLANEs;
10206 case ISD::ZERO_EXTEND:
10207 case ISD::ANY_EXTEND:
10208 Opc = ARMISD::VGETLANEu;
10211 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10218 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10220 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10221 SDValue Cmp = N->getOperand(4);
10222 if (Cmp.getOpcode() != ARMISD::CMPZ)
10223 // Only looking at EQ and NE cases.
10226 EVT VT = N->getValueType(0);
10228 SDValue LHS = Cmp.getOperand(0);
10229 SDValue RHS = Cmp.getOperand(1);
10230 SDValue FalseVal = N->getOperand(0);
10231 SDValue TrueVal = N->getOperand(1);
10232 SDValue ARMcc = N->getOperand(2);
10233 ARMCC::CondCodes CC =
10234 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10252 /// FIXME: Turn this into a target neutral optimization?
10254 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10255 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10256 N->getOperand(3), Cmp);
10257 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10259 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10260 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10261 N->getOperand(3), NewCmp);
10264 if (Res.getNode()) {
10265 APInt KnownZero, KnownOne;
10266 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10267 // Capture demanded bits information that would be otherwise lost.
10268 if (KnownZero == 0xfffffffe)
10269 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10270 DAG.getValueType(MVT::i1));
10271 else if (KnownZero == 0xffffff00)
10272 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10273 DAG.getValueType(MVT::i8));
10274 else if (KnownZero == 0xffff0000)
10275 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10276 DAG.getValueType(MVT::i16));
10282 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10283 DAGCombinerInfo &DCI) const {
10284 switch (N->getOpcode()) {
10286 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10287 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10288 case ISD::SUB: return PerformSUBCombine(N, DCI);
10289 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10290 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10291 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10292 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10293 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10294 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10295 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10296 case ISD::STORE: return PerformSTORECombine(N, DCI);
10297 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10298 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10299 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10300 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10301 case ISD::FP_TO_SINT:
10302 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10303 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10304 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10307 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10308 case ISD::SIGN_EXTEND:
10309 case ISD::ZERO_EXTEND:
10310 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10311 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10312 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10313 case ARMISD::VLD2DUP:
10314 case ARMISD::VLD3DUP:
10315 case ARMISD::VLD4DUP:
10316 return PerformVLDCombine(N, DCI);
10317 case ARMISD::BUILD_VECTOR:
10318 return PerformARMBUILD_VECTORCombine(N, DCI);
10319 case ISD::INTRINSIC_VOID:
10320 case ISD::INTRINSIC_W_CHAIN:
10321 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10322 case Intrinsic::arm_neon_vld1:
10323 case Intrinsic::arm_neon_vld2:
10324 case Intrinsic::arm_neon_vld3:
10325 case Intrinsic::arm_neon_vld4:
10326 case Intrinsic::arm_neon_vld2lane:
10327 case Intrinsic::arm_neon_vld3lane:
10328 case Intrinsic::arm_neon_vld4lane:
10329 case Intrinsic::arm_neon_vst1:
10330 case Intrinsic::arm_neon_vst2:
10331 case Intrinsic::arm_neon_vst3:
10332 case Intrinsic::arm_neon_vst4:
10333 case Intrinsic::arm_neon_vst2lane:
10334 case Intrinsic::arm_neon_vst3lane:
10335 case Intrinsic::arm_neon_vst4lane:
10336 return PerformVLDCombine(N, DCI);
10344 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10346 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10349 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10352 bool *Fast) const {
10353 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10354 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10356 switch (VT.getSimpleVT().SimpleTy) {
10362 // Unaligned access can use (for example) LRDB, LRDH, LDR
10363 if (AllowsUnaligned) {
10365 *Fast = Subtarget->hasV7Ops();
10372 // For any little-endian targets with neon, we can support unaligned ld/st
10373 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10374 // A big-endian target may also explicitly support unaligned accesses
10375 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10385 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10386 unsigned AlignCheck) {
10387 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10388 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10391 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10392 unsigned DstAlign, unsigned SrcAlign,
10393 bool IsMemset, bool ZeroMemset,
10395 MachineFunction &MF) const {
10396 const Function *F = MF.getFunction();
10398 // See if we can use NEON instructions for this...
10399 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10400 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10403 (memOpAlign(SrcAlign, DstAlign, 16) ||
10404 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10406 } else if (Size >= 8 &&
10407 (memOpAlign(SrcAlign, DstAlign, 8) ||
10408 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10414 // Lowering to i32/i16 if the size permits.
10417 else if (Size >= 2)
10420 // Let the target-independent logic figure it out.
10424 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10425 if (Val.getOpcode() != ISD::LOAD)
10428 EVT VT1 = Val.getValueType();
10429 if (!VT1.isSimple() || !VT1.isInteger() ||
10430 !VT2.isSimple() || !VT2.isInteger())
10433 switch (VT1.getSimpleVT().SimpleTy) {
10438 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10445 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10446 EVT VT = ExtVal.getValueType();
10448 if (!isTypeLegal(VT))
10451 // Don't create a loadext if we can fold the extension into a wide/long
10453 // If there's more than one user instruction, the loadext is desirable no
10454 // matter what. There can be two uses by the same instruction.
10455 if (ExtVal->use_empty() ||
10456 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10459 SDNode *U = *ExtVal->use_begin();
10460 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10461 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10467 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10468 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10471 if (!isTypeLegal(EVT::getEVT(Ty1)))
10474 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10476 // Assuming the caller doesn't have a zeroext or signext return parameter,
10477 // truncation all the way down to i1 is valid.
10482 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10486 unsigned Scale = 1;
10487 switch (VT.getSimpleVT().SimpleTy) {
10488 default: return false;
10503 if ((V & (Scale - 1)) != 0)
10506 return V == (V & ((1LL << 5) - 1));
10509 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10510 const ARMSubtarget *Subtarget) {
10511 bool isNeg = false;
10517 switch (VT.getSimpleVT().SimpleTy) {
10518 default: return false;
10523 // + imm12 or - imm8
10525 return V == (V & ((1LL << 8) - 1));
10526 return V == (V & ((1LL << 12) - 1));
10529 // Same as ARM mode. FIXME: NEON?
10530 if (!Subtarget->hasVFP2())
10535 return V == (V & ((1LL << 8) - 1));
10539 /// isLegalAddressImmediate - Return true if the integer value can be used
10540 /// as the offset of the target addressing mode for load / store of the
10542 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10543 const ARMSubtarget *Subtarget) {
10547 if (!VT.isSimple())
10550 if (Subtarget->isThumb1Only())
10551 return isLegalT1AddressImmediate(V, VT);
10552 else if (Subtarget->isThumb2())
10553 return isLegalT2AddressImmediate(V, VT, Subtarget);
10558 switch (VT.getSimpleVT().SimpleTy) {
10559 default: return false;
10564 return V == (V & ((1LL << 12) - 1));
10567 return V == (V & ((1LL << 8) - 1));
10570 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10575 return V == (V & ((1LL << 8) - 1));
10579 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10581 int Scale = AM.Scale;
10585 switch (VT.getSimpleVT().SimpleTy) {
10586 default: return false;
10594 Scale = Scale & ~1;
10595 return Scale == 2 || Scale == 4 || Scale == 8;
10598 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10602 // Note, we allow "void" uses (basically, uses that aren't loads or
10603 // stores), because arm allows folding a scale into many arithmetic
10604 // operations. This should be made more precise and revisited later.
10606 // Allow r << imm, but the imm has to be a multiple of two.
10607 if (Scale & 1) return false;
10608 return isPowerOf2_32(Scale);
10612 /// isLegalAddressingMode - Return true if the addressing mode represented
10613 /// by AM is legal for this target, for a load/store of the specified type.
10614 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10615 const AddrMode &AM, Type *Ty,
10616 unsigned AS) const {
10617 EVT VT = getValueType(DL, Ty, true);
10618 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10621 // Can never fold addr of global into load/store.
10625 switch (AM.Scale) {
10626 case 0: // no scale reg, must be "r+i" or "r", or "i".
10629 if (Subtarget->isThumb1Only())
10633 // ARM doesn't support any R+R*scale+imm addr modes.
10637 if (!VT.isSimple())
10640 if (Subtarget->isThumb2())
10641 return isLegalT2ScaledAddressingMode(AM, VT);
10643 int Scale = AM.Scale;
10644 switch (VT.getSimpleVT().SimpleTy) {
10645 default: return false;
10649 if (Scale < 0) Scale = -Scale;
10653 return isPowerOf2_32(Scale & ~1);
10657 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10662 // Note, we allow "void" uses (basically, uses that aren't loads or
10663 // stores), because arm allows folding a scale into many arithmetic
10664 // operations. This should be made more precise and revisited later.
10666 // Allow r << imm, but the imm has to be a multiple of two.
10667 if (Scale & 1) return false;
10668 return isPowerOf2_32(Scale);
10674 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10675 /// icmp immediate, that is the target has icmp instructions which can compare
10676 /// a register against the immediate without having to materialize the
10677 /// immediate into a register.
10678 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10679 // Thumb2 and ARM modes can use cmn for negative immediates.
10680 if (!Subtarget->isThumb())
10681 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10682 if (Subtarget->isThumb2())
10683 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10684 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10685 return Imm >= 0 && Imm <= 255;
10688 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10689 /// *or sub* immediate, that is the target has add or sub instructions which can
10690 /// add a register with the immediate without having to materialize the
10691 /// immediate into a register.
10692 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10693 // Same encoding for add/sub, just flip the sign.
10694 int64_t AbsImm = std::abs(Imm);
10695 if (!Subtarget->isThumb())
10696 return ARM_AM::getSOImmVal(AbsImm) != -1;
10697 if (Subtarget->isThumb2())
10698 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10699 // Thumb1 only has 8-bit unsigned immediate.
10700 return AbsImm >= 0 && AbsImm <= 255;
10703 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10704 bool isSEXTLoad, SDValue &Base,
10705 SDValue &Offset, bool &isInc,
10706 SelectionDAG &DAG) {
10707 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10710 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10711 // AddressingMode 3
10712 Base = Ptr->getOperand(0);
10713 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10714 int RHSC = (int)RHS->getZExtValue();
10715 if (RHSC < 0 && RHSC > -256) {
10716 assert(Ptr->getOpcode() == ISD::ADD);
10718 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10722 isInc = (Ptr->getOpcode() == ISD::ADD);
10723 Offset = Ptr->getOperand(1);
10725 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10726 // AddressingMode 2
10727 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10728 int RHSC = (int)RHS->getZExtValue();
10729 if (RHSC < 0 && RHSC > -0x1000) {
10730 assert(Ptr->getOpcode() == ISD::ADD);
10732 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10733 Base = Ptr->getOperand(0);
10738 if (Ptr->getOpcode() == ISD::ADD) {
10740 ARM_AM::ShiftOpc ShOpcVal=
10741 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10742 if (ShOpcVal != ARM_AM::no_shift) {
10743 Base = Ptr->getOperand(1);
10744 Offset = Ptr->getOperand(0);
10746 Base = Ptr->getOperand(0);
10747 Offset = Ptr->getOperand(1);
10752 isInc = (Ptr->getOpcode() == ISD::ADD);
10753 Base = Ptr->getOperand(0);
10754 Offset = Ptr->getOperand(1);
10758 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10762 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10763 bool isSEXTLoad, SDValue &Base,
10764 SDValue &Offset, bool &isInc,
10765 SelectionDAG &DAG) {
10766 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10769 Base = Ptr->getOperand(0);
10770 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10771 int RHSC = (int)RHS->getZExtValue();
10772 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10773 assert(Ptr->getOpcode() == ISD::ADD);
10775 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10777 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10778 isInc = Ptr->getOpcode() == ISD::ADD;
10779 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10787 /// getPreIndexedAddressParts - returns true by value, base pointer and
10788 /// offset pointer and addressing mode by reference if the node's address
10789 /// can be legally represented as pre-indexed load / store address.
10791 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10793 ISD::MemIndexedMode &AM,
10794 SelectionDAG &DAG) const {
10795 if (Subtarget->isThumb1Only())
10800 bool isSEXTLoad = false;
10801 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10802 Ptr = LD->getBasePtr();
10803 VT = LD->getMemoryVT();
10804 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10805 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10806 Ptr = ST->getBasePtr();
10807 VT = ST->getMemoryVT();
10812 bool isLegal = false;
10813 if (Subtarget->isThumb2())
10814 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10815 Offset, isInc, DAG);
10817 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10818 Offset, isInc, DAG);
10822 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10826 /// getPostIndexedAddressParts - returns true by value, base pointer and
10827 /// offset pointer and addressing mode by reference if this node can be
10828 /// combined with a load / store to form a post-indexed load / store.
10829 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10832 ISD::MemIndexedMode &AM,
10833 SelectionDAG &DAG) const {
10834 if (Subtarget->isThumb1Only())
10839 bool isSEXTLoad = false;
10840 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10841 VT = LD->getMemoryVT();
10842 Ptr = LD->getBasePtr();
10843 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10844 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10845 VT = ST->getMemoryVT();
10846 Ptr = ST->getBasePtr();
10851 bool isLegal = false;
10852 if (Subtarget->isThumb2())
10853 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10856 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10862 // Swap base ptr and offset to catch more post-index load / store when
10863 // it's legal. In Thumb2 mode, offset must be an immediate.
10864 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10865 !Subtarget->isThumb2())
10866 std::swap(Base, Offset);
10868 // Post-indexed load / store update the base pointer.
10873 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10877 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10880 const SelectionDAG &DAG,
10881 unsigned Depth) const {
10882 unsigned BitWidth = KnownOne.getBitWidth();
10883 KnownZero = KnownOne = APInt(BitWidth, 0);
10884 switch (Op.getOpcode()) {
10890 // These nodes' second result is a boolean
10891 if (Op.getResNo() == 0)
10893 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10895 case ARMISD::CMOV: {
10896 // Bits are known zero/one if known on the LHS and RHS.
10897 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10898 if (KnownZero == 0 && KnownOne == 0) return;
10900 APInt KnownZeroRHS, KnownOneRHS;
10901 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10902 KnownZero &= KnownZeroRHS;
10903 KnownOne &= KnownOneRHS;
10906 case ISD::INTRINSIC_W_CHAIN: {
10907 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10908 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10911 case Intrinsic::arm_ldaex:
10912 case Intrinsic::arm_ldrex: {
10913 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10914 unsigned MemBits = VT.getScalarType().getSizeInBits();
10915 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10923 //===----------------------------------------------------------------------===//
10924 // ARM Inline Assembly Support
10925 //===----------------------------------------------------------------------===//
10927 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10928 // Looking for "rev" which is V6+.
10929 if (!Subtarget->hasV6Ops())
10932 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10933 std::string AsmStr = IA->getAsmString();
10934 SmallVector<StringRef, 4> AsmPieces;
10935 SplitString(AsmStr, AsmPieces, ";\n");
10937 switch (AsmPieces.size()) {
10938 default: return false;
10940 AsmStr = AsmPieces[0];
10942 SplitString(AsmStr, AsmPieces, " \t,");
10945 if (AsmPieces.size() == 3 &&
10946 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10947 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10948 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10949 if (Ty && Ty->getBitWidth() == 32)
10950 return IntrinsicLowering::LowerToByteSwap(CI);
10958 /// getConstraintType - Given a constraint letter, return the type of
10959 /// constraint it is for this target.
10960 ARMTargetLowering::ConstraintType
10961 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10962 if (Constraint.size() == 1) {
10963 switch (Constraint[0]) {
10965 case 'l': return C_RegisterClass;
10966 case 'w': return C_RegisterClass;
10967 case 'h': return C_RegisterClass;
10968 case 'x': return C_RegisterClass;
10969 case 't': return C_RegisterClass;
10970 case 'j': return C_Other; // Constant for movw.
10971 // An address with a single base register. Due to the way we
10972 // currently handle addresses it is the same as an 'r' memory constraint.
10973 case 'Q': return C_Memory;
10975 } else if (Constraint.size() == 2) {
10976 switch (Constraint[0]) {
10978 // All 'U+' constraints are addresses.
10979 case 'U': return C_Memory;
10982 return TargetLowering::getConstraintType(Constraint);
10985 /// Examine constraint type and operand type and determine a weight value.
10986 /// This object must already have been set up with the operand type
10987 /// and the current alternative constraint selected.
10988 TargetLowering::ConstraintWeight
10989 ARMTargetLowering::getSingleConstraintMatchWeight(
10990 AsmOperandInfo &info, const char *constraint) const {
10991 ConstraintWeight weight = CW_Invalid;
10992 Value *CallOperandVal = info.CallOperandVal;
10993 // If we don't have a value, we can't do a match,
10994 // but allow it at the lowest weight.
10995 if (!CallOperandVal)
10997 Type *type = CallOperandVal->getType();
10998 // Look at the constraint type.
10999 switch (*constraint) {
11001 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11004 if (type->isIntegerTy()) {
11005 if (Subtarget->isThumb())
11006 weight = CW_SpecificReg;
11008 weight = CW_Register;
11012 if (type->isFloatingPointTy())
11013 weight = CW_Register;
11019 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11020 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11021 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11022 if (Constraint.size() == 1) {
11023 // GCC ARM Constraint Letters
11024 switch (Constraint[0]) {
11025 case 'l': // Low regs or general regs.
11026 if (Subtarget->isThumb())
11027 return RCPair(0U, &ARM::tGPRRegClass);
11028 return RCPair(0U, &ARM::GPRRegClass);
11029 case 'h': // High regs or no regs.
11030 if (Subtarget->isThumb())
11031 return RCPair(0U, &ARM::hGPRRegClass);
11034 if (Subtarget->isThumb1Only())
11035 return RCPair(0U, &ARM::tGPRRegClass);
11036 return RCPair(0U, &ARM::GPRRegClass);
11038 if (VT == MVT::Other)
11040 if (VT == MVT::f32)
11041 return RCPair(0U, &ARM::SPRRegClass);
11042 if (VT.getSizeInBits() == 64)
11043 return RCPair(0U, &ARM::DPRRegClass);
11044 if (VT.getSizeInBits() == 128)
11045 return RCPair(0U, &ARM::QPRRegClass);
11048 if (VT == MVT::Other)
11050 if (VT == MVT::f32)
11051 return RCPair(0U, &ARM::SPR_8RegClass);
11052 if (VT.getSizeInBits() == 64)
11053 return RCPair(0U, &ARM::DPR_8RegClass);
11054 if (VT.getSizeInBits() == 128)
11055 return RCPair(0U, &ARM::QPR_8RegClass);
11058 if (VT == MVT::f32)
11059 return RCPair(0U, &ARM::SPRRegClass);
11063 if (StringRef("{cc}").equals_lower(Constraint))
11064 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11066 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11069 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11070 /// vector. If it is invalid, don't add anything to Ops.
11071 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11072 std::string &Constraint,
11073 std::vector<SDValue>&Ops,
11074 SelectionDAG &DAG) const {
11077 // Currently only support length 1 constraints.
11078 if (Constraint.length() != 1) return;
11080 char ConstraintLetter = Constraint[0];
11081 switch (ConstraintLetter) {
11084 case 'I': case 'J': case 'K': case 'L':
11085 case 'M': case 'N': case 'O':
11086 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11090 int64_t CVal64 = C->getSExtValue();
11091 int CVal = (int) CVal64;
11092 // None of these constraints allow values larger than 32 bits. Check
11093 // that the value fits in an int.
11094 if (CVal != CVal64)
11097 switch (ConstraintLetter) {
11099 // Constant suitable for movw, must be between 0 and
11101 if (Subtarget->hasV6T2Ops())
11102 if (CVal >= 0 && CVal <= 65535)
11106 if (Subtarget->isThumb1Only()) {
11107 // This must be a constant between 0 and 255, for ADD
11109 if (CVal >= 0 && CVal <= 255)
11111 } else if (Subtarget->isThumb2()) {
11112 // A constant that can be used as an immediate value in a
11113 // data-processing instruction.
11114 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11117 // A constant that can be used as an immediate value in a
11118 // data-processing instruction.
11119 if (ARM_AM::getSOImmVal(CVal) != -1)
11125 if (Subtarget->isThumb()) { // FIXME thumb2
11126 // This must be a constant between -255 and -1, for negated ADD
11127 // immediates. This can be used in GCC with an "n" modifier that
11128 // prints the negated value, for use with SUB instructions. It is
11129 // not useful otherwise but is implemented for compatibility.
11130 if (CVal >= -255 && CVal <= -1)
11133 // This must be a constant between -4095 and 4095. It is not clear
11134 // what this constraint is intended for. Implemented for
11135 // compatibility with GCC.
11136 if (CVal >= -4095 && CVal <= 4095)
11142 if (Subtarget->isThumb1Only()) {
11143 // A 32-bit value where only one byte has a nonzero value. Exclude
11144 // zero to match GCC. This constraint is used by GCC internally for
11145 // constants that can be loaded with a move/shift combination.
11146 // It is not useful otherwise but is implemented for compatibility.
11147 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11149 } else if (Subtarget->isThumb2()) {
11150 // A constant whose bitwise inverse can be used as an immediate
11151 // value in a data-processing instruction. This can be used in GCC
11152 // with a "B" modifier that prints the inverted value, for use with
11153 // BIC and MVN instructions. It is not useful otherwise but is
11154 // implemented for compatibility.
11155 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11158 // A constant whose bitwise inverse can be used as an immediate
11159 // value in a data-processing instruction. This can be used in GCC
11160 // with a "B" modifier that prints the inverted value, for use with
11161 // BIC and MVN instructions. It is not useful otherwise but is
11162 // implemented for compatibility.
11163 if (ARM_AM::getSOImmVal(~CVal) != -1)
11169 if (Subtarget->isThumb1Only()) {
11170 // This must be a constant between -7 and 7,
11171 // for 3-operand ADD/SUB immediate instructions.
11172 if (CVal >= -7 && CVal < 7)
11174 } else if (Subtarget->isThumb2()) {
11175 // A constant whose negation can be used as an immediate value in a
11176 // data-processing instruction. This can be used in GCC with an "n"
11177 // modifier that prints the negated value, for use with SUB
11178 // instructions. It is not useful otherwise but is implemented for
11180 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11183 // A constant whose negation can be used as an immediate value in a
11184 // data-processing instruction. This can be used in GCC with an "n"
11185 // modifier that prints the negated value, for use with SUB
11186 // instructions. It is not useful otherwise but is implemented for
11188 if (ARM_AM::getSOImmVal(-CVal) != -1)
11194 if (Subtarget->isThumb()) { // FIXME thumb2
11195 // This must be a multiple of 4 between 0 and 1020, for
11196 // ADD sp + immediate.
11197 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11200 // A power of two or a constant between 0 and 32. This is used in
11201 // GCC for the shift amount on shifted register operands, but it is
11202 // useful in general for any shift amounts.
11203 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11209 if (Subtarget->isThumb()) { // FIXME thumb2
11210 // This must be a constant between 0 and 31, for shift amounts.
11211 if (CVal >= 0 && CVal <= 31)
11217 if (Subtarget->isThumb()) { // FIXME thumb2
11218 // This must be a multiple of 4 between -508 and 508, for
11219 // ADD/SUB sp = sp + immediate.
11220 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11225 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11229 if (Result.getNode()) {
11230 Ops.push_back(Result);
11233 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11236 static RTLIB::Libcall getDivRemLibcall(
11237 const SDNode *N, MVT::SimpleValueType SVT) {
11238 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11239 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11240 "Unhandled Opcode in getDivRemLibcall");
11241 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11242 N->getOpcode() == ISD::SREM;
11245 default: llvm_unreachable("Unexpected request for libcall!");
11246 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11247 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11248 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11249 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11254 static TargetLowering::ArgListTy getDivRemArgList(
11255 const SDNode *N, LLVMContext *Context) {
11256 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11257 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11258 "Unhandled Opcode in getDivRemArgList");
11259 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11260 N->getOpcode() == ISD::SREM;
11261 TargetLowering::ArgListTy Args;
11262 TargetLowering::ArgListEntry Entry;
11263 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11264 EVT ArgVT = N->getOperand(i).getValueType();
11265 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11266 Entry.Node = N->getOperand(i);
11268 Entry.isSExt = isSigned;
11269 Entry.isZExt = !isSigned;
11270 Args.push_back(Entry);
11275 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11276 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11277 "Register-based DivRem lowering only");
11278 unsigned Opcode = Op->getOpcode();
11279 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11280 "Invalid opcode for Div/Rem lowering");
11281 bool isSigned = (Opcode == ISD::SDIVREM);
11282 EVT VT = Op->getValueType(0);
11283 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11285 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11286 VT.getSimpleVT().SimpleTy);
11287 SDValue InChain = DAG.getEntryNode();
11289 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11292 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11293 getPointerTy(DAG.getDataLayout()));
11295 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11298 TargetLowering::CallLoweringInfo CLI(DAG);
11299 CLI.setDebugLoc(dl).setChain(InChain)
11300 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11301 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11303 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11304 return CallInfo.first;
11307 // Lowers REM using divmod helpers
11308 // see RTABI section 4.2/4.3
11309 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11310 // Build return types (div and rem)
11311 std::vector<Type*> RetTyParams;
11312 Type *RetTyElement;
11314 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11315 default: llvm_unreachable("Unexpected request for libcall!");
11316 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
11317 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11318 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11319 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11322 RetTyParams.push_back(RetTyElement);
11323 RetTyParams.push_back(RetTyElement);
11324 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11325 Type *RetTy = StructType::get(*DAG.getContext(), ret);
11327 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11329 SDValue InChain = DAG.getEntryNode();
11330 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11331 bool isSigned = N->getOpcode() == ISD::SREM;
11332 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11333 getPointerTy(DAG.getDataLayout()));
11336 CallLoweringInfo CLI(DAG);
11337 CLI.setChain(InChain)
11338 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11339 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11340 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11342 // Return second (rem) result operand (first contains div)
11343 SDNode *ResNode = CallResult.first.getNode();
11344 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11345 return ResNode->getOperand(1);
11349 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11350 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11354 SDValue Chain = Op.getOperand(0);
11355 SDValue Size = Op.getOperand(1);
11357 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11358 DAG.getConstant(2, DL, MVT::i32));
11361 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11362 Flag = Chain.getValue(1);
11364 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11365 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11367 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11368 Chain = NewSP.getValue(1);
11370 SDValue Ops[2] = { NewSP, Chain };
11371 return DAG.getMergeValues(Ops, DL);
11374 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11375 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11376 "Unexpected type for custom-lowering FP_EXTEND");
11379 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11381 SDValue SrcVal = Op.getOperand(0);
11382 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11383 /*isSigned*/ false, SDLoc(Op)).first;
11386 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11387 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11388 Subtarget->isFPOnlySP() &&
11389 "Unexpected type for custom-lowering FP_ROUND");
11392 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11394 SDValue SrcVal = Op.getOperand(0);
11395 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11396 /*isSigned*/ false, SDLoc(Op)).first;
11400 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11401 // The ARM target isn't yet aware of offsets.
11405 bool ARM::isBitFieldInvertedMask(unsigned v) {
11406 if (v == 0xffffffff)
11409 // there can be 1's on either or both "outsides", all the "inside"
11410 // bits must be 0's
11411 return isShiftedMask_32(~v);
11414 /// isFPImmLegal - Returns true if the target can instruction select the
11415 /// specified FP immediate natively. If false, the legalizer will
11416 /// materialize the FP immediate as a load from a constant pool.
11417 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11418 if (!Subtarget->hasVFP3())
11420 if (VT == MVT::f32)
11421 return ARM_AM::getFP32Imm(Imm) != -1;
11422 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11423 return ARM_AM::getFP64Imm(Imm) != -1;
11427 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11428 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11429 /// specified in the intrinsic calls.
11430 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11432 unsigned Intrinsic) const {
11433 switch (Intrinsic) {
11434 case Intrinsic::arm_neon_vld1:
11435 case Intrinsic::arm_neon_vld2:
11436 case Intrinsic::arm_neon_vld3:
11437 case Intrinsic::arm_neon_vld4:
11438 case Intrinsic::arm_neon_vld2lane:
11439 case Intrinsic::arm_neon_vld3lane:
11440 case Intrinsic::arm_neon_vld4lane: {
11441 Info.opc = ISD::INTRINSIC_W_CHAIN;
11442 // Conservatively set memVT to the entire set of vectors loaded.
11443 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11444 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11445 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11446 Info.ptrVal = I.getArgOperand(0);
11448 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11449 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11450 Info.vol = false; // volatile loads with NEON intrinsics not supported
11451 Info.readMem = true;
11452 Info.writeMem = false;
11455 case Intrinsic::arm_neon_vst1:
11456 case Intrinsic::arm_neon_vst2:
11457 case Intrinsic::arm_neon_vst3:
11458 case Intrinsic::arm_neon_vst4:
11459 case Intrinsic::arm_neon_vst2lane:
11460 case Intrinsic::arm_neon_vst3lane:
11461 case Intrinsic::arm_neon_vst4lane: {
11462 Info.opc = ISD::INTRINSIC_VOID;
11463 // Conservatively set memVT to the entire set of vectors stored.
11464 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11465 unsigned NumElts = 0;
11466 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11467 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11468 if (!ArgTy->isVectorTy())
11470 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11472 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11473 Info.ptrVal = I.getArgOperand(0);
11475 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11476 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11477 Info.vol = false; // volatile stores with NEON intrinsics not supported
11478 Info.readMem = false;
11479 Info.writeMem = true;
11482 case Intrinsic::arm_ldaex:
11483 case Intrinsic::arm_ldrex: {
11484 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11485 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11486 Info.opc = ISD::INTRINSIC_W_CHAIN;
11487 Info.memVT = MVT::getVT(PtrTy->getElementType());
11488 Info.ptrVal = I.getArgOperand(0);
11490 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11492 Info.readMem = true;
11493 Info.writeMem = false;
11496 case Intrinsic::arm_stlex:
11497 case Intrinsic::arm_strex: {
11498 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11499 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11500 Info.opc = ISD::INTRINSIC_W_CHAIN;
11501 Info.memVT = MVT::getVT(PtrTy->getElementType());
11502 Info.ptrVal = I.getArgOperand(1);
11504 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11506 Info.readMem = false;
11507 Info.writeMem = true;
11510 case Intrinsic::arm_stlexd:
11511 case Intrinsic::arm_strexd: {
11512 Info.opc = ISD::INTRINSIC_W_CHAIN;
11513 Info.memVT = MVT::i64;
11514 Info.ptrVal = I.getArgOperand(2);
11518 Info.readMem = false;
11519 Info.writeMem = true;
11522 case Intrinsic::arm_ldaexd:
11523 case Intrinsic::arm_ldrexd: {
11524 Info.opc = ISD::INTRINSIC_W_CHAIN;
11525 Info.memVT = MVT::i64;
11526 Info.ptrVal = I.getArgOperand(0);
11530 Info.readMem = true;
11531 Info.writeMem = false;
11541 /// \brief Returns true if it is beneficial to convert a load of a constant
11542 /// to just the constant itself.
11543 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11545 assert(Ty->isIntegerTy());
11547 unsigned Bits = Ty->getPrimitiveSizeInBits();
11548 if (Bits == 0 || Bits > 32)
11553 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11554 ARM_MB::MemBOpt Domain) const {
11555 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11557 // First, if the target has no DMB, see what fallback we can use.
11558 if (!Subtarget->hasDataBarrier()) {
11559 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11560 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11562 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11563 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11564 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11565 Builder.getInt32(0), Builder.getInt32(7),
11566 Builder.getInt32(10), Builder.getInt32(5)};
11567 return Builder.CreateCall(MCR, args);
11569 // Instead of using barriers, atomic accesses on these subtargets use
11571 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11574 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11575 // Only a full system barrier exists in the M-class architectures.
11576 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11577 Constant *CDomain = Builder.getInt32(Domain);
11578 return Builder.CreateCall(DMB, CDomain);
11582 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11583 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11584 AtomicOrdering Ord, bool IsStore,
11585 bool IsLoad) const {
11586 if (!getInsertFencesForAtomic())
11592 llvm_unreachable("Invalid fence: unordered/non-atomic");
11595 return nullptr; // Nothing to do
11596 case SequentiallyConsistent:
11598 return nullptr; // Nothing to do
11601 case AcquireRelease:
11602 if (Subtarget->isSwift())
11603 return makeDMB(Builder, ARM_MB::ISHST);
11604 // FIXME: add a comment with a link to documentation justifying this.
11606 return makeDMB(Builder, ARM_MB::ISH);
11608 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11611 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11612 AtomicOrdering Ord, bool IsStore,
11613 bool IsLoad) const {
11614 if (!getInsertFencesForAtomic())
11620 llvm_unreachable("Invalid fence: unordered/not-atomic");
11623 return nullptr; // Nothing to do
11625 case AcquireRelease:
11626 case SequentiallyConsistent:
11627 return makeDMB(Builder, ARM_MB::ISH);
11629 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11632 // Loads and stores less than 64-bits are already atomic; ones above that
11633 // are doomed anyway, so defer to the default libcall and blame the OS when
11634 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11635 // anything for those.
11636 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11637 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11638 return (Size == 64) && !Subtarget->isMClass();
11641 // Loads and stores less than 64-bits are already atomic; ones above that
11642 // are doomed anyway, so defer to the default libcall and blame the OS when
11643 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11644 // anything for those.
11645 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11646 // guarantee, see DDI0406C ARM architecture reference manual,
11647 // sections A8.8.72-74 LDRD)
11648 TargetLowering::AtomicExpansionKind
11649 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11650 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11651 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11652 : AtomicExpansionKind::None;
11655 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11656 // and up to 64 bits on the non-M profiles
11657 TargetLowering::AtomicExpansionKind
11658 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11659 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11660 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11661 ? AtomicExpansionKind::LLSC
11662 : AtomicExpansionKind::None;
11665 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11666 AtomicCmpXchgInst *AI) const {
11670 // This has so far only been implemented for MachO.
11671 bool ARMTargetLowering::useLoadStackGuardNode() const {
11672 return Subtarget->isTargetMachO();
11675 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11676 unsigned &Cost) const {
11677 // If we do not have NEON, vector types are not natively supported.
11678 if (!Subtarget->hasNEON())
11681 // Floating point values and vector values map to the same register file.
11682 // Therefore, although we could do a store extract of a vector type, this is
11683 // better to leave at float as we have more freedom in the addressing mode for
11685 if (VectorTy->isFPOrFPVectorTy())
11688 // If the index is unknown at compile time, this is very expensive to lower
11689 // and it is not possible to combine the store with the extract.
11690 if (!isa<ConstantInt>(Idx))
11693 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11694 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11695 // We can do a store + vector extract on any vector that fits perfectly in a D
11697 if (BitWidth == 64 || BitWidth == 128) {
11704 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11705 AtomicOrdering Ord) const {
11706 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11707 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11708 bool IsAcquire = isAtLeastAcquire(Ord);
11710 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11711 // intrinsic must return {i32, i32} and we have to recombine them into a
11712 // single i64 here.
11713 if (ValTy->getPrimitiveSizeInBits() == 64) {
11714 Intrinsic::ID Int =
11715 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11716 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11718 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11719 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11721 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11722 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11723 if (!Subtarget->isLittle())
11724 std::swap (Lo, Hi);
11725 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11726 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11727 return Builder.CreateOr(
11728 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11731 Type *Tys[] = { Addr->getType() };
11732 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11733 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11735 return Builder.CreateTruncOrBitCast(
11736 Builder.CreateCall(Ldrex, Addr),
11737 cast<PointerType>(Addr->getType())->getElementType());
11740 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11741 IRBuilder<> &Builder) const {
11742 if (!Subtarget->hasV7Ops())
11744 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11745 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
11748 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11750 AtomicOrdering Ord) const {
11751 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11752 bool IsRelease = isAtLeastRelease(Ord);
11754 // Since the intrinsics must have legal type, the i64 intrinsics take two
11755 // parameters: "i32, i32". We must marshal Val into the appropriate form
11756 // before the call.
11757 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11758 Intrinsic::ID Int =
11759 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11760 Function *Strex = Intrinsic::getDeclaration(M, Int);
11761 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11763 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11764 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11765 if (!Subtarget->isLittle())
11766 std::swap (Lo, Hi);
11767 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11768 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11771 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11772 Type *Tys[] = { Addr->getType() };
11773 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11775 return Builder.CreateCall(
11776 Strex, {Builder.CreateZExtOrBitCast(
11777 Val, Strex->getFunctionType()->getParamType(0)),
11781 /// \brief Lower an interleaved load into a vldN intrinsic.
11783 /// E.g. Lower an interleaved load (Factor = 2):
11784 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11785 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
11786 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
11789 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11790 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11791 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11792 bool ARMTargetLowering::lowerInterleavedLoad(
11793 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11794 ArrayRef<unsigned> Indices, unsigned Factor) const {
11795 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11796 "Invalid interleave factor");
11797 assert(!Shuffles.empty() && "Empty shufflevector input");
11798 assert(Shuffles.size() == Indices.size() &&
11799 "Unmatched number of shufflevectors and indices");
11801 VectorType *VecTy = Shuffles[0]->getType();
11802 Type *EltTy = VecTy->getVectorElementType();
11804 const DataLayout &DL = LI->getModule()->getDataLayout();
11805 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11806 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11808 // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11809 // support i64/f64 element).
11810 if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11813 // A pointer vector can not be the return type of the ldN intrinsics. Need to
11814 // load integer vectors first and then convert to pointer vectors.
11815 if (EltTy->isPointerTy())
11817 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11819 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11820 Intrinsic::arm_neon_vld3,
11821 Intrinsic::arm_neon_vld4};
11823 Function *VldnFunc =
11824 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11826 IRBuilder<> Builder(LI);
11827 SmallVector<Value *, 2> Ops;
11829 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11830 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11831 Ops.push_back(Builder.getInt32(LI->getAlignment()));
11833 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11835 // Replace uses of each shufflevector with the corresponding vector loaded
11837 for (unsigned i = 0; i < Shuffles.size(); i++) {
11838 ShuffleVectorInst *SV = Shuffles[i];
11839 unsigned Index = Indices[i];
11841 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11843 // Convert the integer vector to pointer vector if the element is pointer.
11844 if (EltTy->isPointerTy())
11845 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11847 SV->replaceAllUsesWith(SubVec);
11853 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11855 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11856 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11857 unsigned NumElts) {
11858 SmallVector<Constant *, 16> Mask;
11859 for (unsigned i = 0; i < NumElts; i++)
11860 Mask.push_back(Builder.getInt32(Start + i));
11862 return ConstantVector::get(Mask);
11865 /// \brief Lower an interleaved store into a vstN intrinsic.
11867 /// E.g. Lower an interleaved store (Factor = 3):
11868 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11869 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11870 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11873 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11874 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11875 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11876 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11878 /// Note that the new shufflevectors will be removed and we'll only generate one
11879 /// vst3 instruction in CodeGen.
11880 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11881 ShuffleVectorInst *SVI,
11882 unsigned Factor) const {
11883 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11884 "Invalid interleave factor");
11886 VectorType *VecTy = SVI->getType();
11887 assert(VecTy->getVectorNumElements() % Factor == 0 &&
11888 "Invalid interleaved store");
11890 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11891 Type *EltTy = VecTy->getVectorElementType();
11892 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11894 const DataLayout &DL = SI->getModule()->getDataLayout();
11895 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11896 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11898 // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11899 // doesn't support i64/f64 element).
11900 if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11903 Value *Op0 = SVI->getOperand(0);
11904 Value *Op1 = SVI->getOperand(1);
11905 IRBuilder<> Builder(SI);
11907 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11908 // vectors to integer vectors.
11909 if (EltTy->isPointerTy()) {
11910 Type *IntTy = DL.getIntPtrType(EltTy);
11912 // Convert to the corresponding integer vector.
11914 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11915 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11916 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11918 SubVecTy = VectorType::get(IntTy, NumSubElts);
11921 static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11922 Intrinsic::arm_neon_vst3,
11923 Intrinsic::arm_neon_vst4};
11924 Function *VstNFunc = Intrinsic::getDeclaration(
11925 SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11927 SmallVector<Value *, 6> Ops;
11929 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11930 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11932 // Split the shufflevector operands into sub vectors for the new vstN call.
11933 for (unsigned i = 0; i < Factor; i++)
11934 Ops.push_back(Builder.CreateShuffleVector(
11935 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11937 Ops.push_back(Builder.getInt32(SI->getAlignment()));
11938 Builder.CreateCall(VstNFunc, Ops);
11950 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11951 uint64_t &Members) {
11952 if (auto *ST = dyn_cast<StructType>(Ty)) {
11953 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11954 uint64_t SubMembers = 0;
11955 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11957 Members += SubMembers;
11959 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11960 uint64_t SubMembers = 0;
11961 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11963 Members += SubMembers * AT->getNumElements();
11964 } else if (Ty->isFloatTy()) {
11965 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11969 } else if (Ty->isDoubleTy()) {
11970 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11974 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11981 return VT->getBitWidth() == 64;
11983 return VT->getBitWidth() == 128;
11985 switch (VT->getBitWidth()) {
11998 return (Members > 0 && Members <= 4);
12001 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12002 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12003 /// passing according to AAPCS rules.
12004 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12005 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12006 if (getEffectiveCallingConv(CallConv, isVarArg) !=
12007 CallingConv::ARM_AAPCS_VFP)
12010 HABaseType Base = HA_UNKNOWN;
12011 uint64_t Members = 0;
12012 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12013 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12015 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12016 return IsHA || IsIntArray;