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);
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153 addRegisterClass(VT, &ARM::DPRRegClass);
154 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::DPairRegClass);
159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163 const ARMSubtarget &STI)
164 : TargetLowering(TM), Subtarget(&STI) {
165 RegInfo = Subtarget->getRegisterInfo();
166 Itins = Subtarget->getInstrItineraryData();
168 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
170 if (Subtarget->isTargetMachO()) {
171 // Uses VFP for Thumb libfuncs if available.
172 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174 static const struct {
175 const RTLIB::Libcall Op;
176 const char * const Name;
177 const ISD::CondCode Cond;
179 // Single-precision floating-point arithmetic.
180 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
181 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
182 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
183 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
185 // Double-precision floating-point arithmetic.
186 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
187 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
188 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
189 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
191 // Single-precision comparisons.
192 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
193 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
194 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
195 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
196 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
197 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
198 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
199 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
201 // Double-precision comparisons.
202 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
203 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
204 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
205 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
206 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
207 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
208 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
209 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
211 // Floating-point to integer conversions.
212 // i64 conversions are done via library routines even when generating VFP
213 // instructions, so use the same ones.
214 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
215 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
216 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
217 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
219 // Conversions between floating types.
220 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
221 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
223 // Integer to floating-point conversions.
224 // i64 conversions are done via library routines even when generating VFP
225 // instructions, so use the same ones.
226 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
227 // e.g., __floatunsidf vs. __floatunssidfvfp.
228 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
229 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
230 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
231 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
234 for (const auto &LC : LibraryCalls) {
235 setLibcallName(LC.Op, LC.Name);
236 if (LC.Cond != ISD::SETCC_INVALID)
237 setCmpLibcallCC(LC.Op, LC.Cond);
242 // These libcalls are not available in 32-bit.
243 setLibcallName(RTLIB::SHL_I128, nullptr);
244 setLibcallName(RTLIB::SRL_I128, nullptr);
245 setLibcallName(RTLIB::SRA_I128, nullptr);
247 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
248 !Subtarget->isTargetWindows()) {
249 static const struct {
250 const RTLIB::Libcall Op;
251 const char * const Name;
252 const CallingConv::ID CC;
253 const ISD::CondCode Cond;
255 // Double-precision floating-point arithmetic helper functions
256 // RTABI chapter 4.1.2, Table 2
257 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
258 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
259 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
260 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
262 // Double-precision floating-point comparison helper functions
263 // RTABI chapter 4.1.2, Table 3
264 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
265 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
266 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
267 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
268 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
269 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
270 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
271 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
273 // Single-precision floating-point arithmetic helper functions
274 // RTABI chapter 4.1.2, Table 4
275 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
276 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
277 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
278 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
280 // Single-precision floating-point comparison helper functions
281 // RTABI chapter 4.1.2, Table 5
282 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
283 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
284 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
285 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
286 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
287 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
288 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
289 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
291 // Floating-point to integer conversions.
292 // RTABI chapter 4.1.2, Table 6
293 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
295 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
296 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 // Conversions between floating types.
303 // RTABI chapter 4.1.2, Table 7
304 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 // Integer to floating-point conversions.
309 // RTABI chapter 4.1.2, Table 8
310 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 // Long long helper functions
320 // RTABI chapter 4.2, Table 9
321 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 // Integer division functions
327 // RTABI chapter 4.3.1
328 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 // RTABI chapter 4.3.4
339 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 for (const auto &LC : LibraryCalls) {
345 setLibcallName(LC.Op, LC.Name);
346 setLibcallCallingConv(LC.Op, LC.CC);
347 if (LC.Cond != ISD::SETCC_INVALID)
348 setCmpLibcallCC(LC.Op, LC.Cond);
352 if (Subtarget->isTargetWindows()) {
353 static const struct {
354 const RTLIB::Libcall Op;
355 const char * const Name;
356 const CallingConv::ID CC;
358 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
359 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
360 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
361 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
362 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
363 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
364 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::SDIV_I32, "__rt_sdiv", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::UDIV_I32, "__rt_udiv", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::UDIV_I64, "__rt_udiv64", 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::SELECT_CC);
587 setTargetDAGCombine(ISD::BUILD_VECTOR);
588 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
589 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
590 setTargetDAGCombine(ISD::STORE);
591 setTargetDAGCombine(ISD::FP_TO_SINT);
592 setTargetDAGCombine(ISD::FP_TO_UINT);
593 setTargetDAGCombine(ISD::FDIV);
594 setTargetDAGCombine(ISD::LOAD);
596 // It is legal to extload from v4i8 to v4i16 or v4i32.
597 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
599 for (MVT VT : MVT::integer_vector_valuetypes()) {
600 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
601 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
602 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
607 // ARM and Thumb2 support UMLAL/SMLAL.
608 if (!Subtarget->isThumb1Only())
609 setTargetDAGCombine(ISD::ADDC);
611 if (Subtarget->isFPOnlySP()) {
612 // When targeting a floating-point unit with only single-precision
613 // operations, f64 is legal for the few double-precision instructions which
614 // are present However, no double-precision operations other than moves,
615 // loads and stores are provided by the hardware.
616 setOperationAction(ISD::FADD, MVT::f64, Expand);
617 setOperationAction(ISD::FSUB, MVT::f64, Expand);
618 setOperationAction(ISD::FMUL, MVT::f64, Expand);
619 setOperationAction(ISD::FMA, MVT::f64, Expand);
620 setOperationAction(ISD::FDIV, MVT::f64, Expand);
621 setOperationAction(ISD::FREM, MVT::f64, Expand);
622 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
623 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
624 setOperationAction(ISD::FNEG, MVT::f64, Expand);
625 setOperationAction(ISD::FABS, MVT::f64, Expand);
626 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
627 setOperationAction(ISD::FSIN, MVT::f64, Expand);
628 setOperationAction(ISD::FCOS, MVT::f64, Expand);
629 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
630 setOperationAction(ISD::FPOW, MVT::f64, Expand);
631 setOperationAction(ISD::FLOG, MVT::f64, Expand);
632 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
633 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
634 setOperationAction(ISD::FEXP, MVT::f64, Expand);
635 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
636 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
637 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
638 setOperationAction(ISD::FRINT, MVT::f64, Expand);
639 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
640 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
641 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
642 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
643 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
644 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
645 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
646 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
647 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
648 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
651 computeRegisterProperties(Subtarget->getRegisterInfo());
653 // ARM does not have floating-point extending loads.
654 for (MVT VT : MVT::fp_valuetypes()) {
655 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
656 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
659 // ... or truncating stores
660 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
661 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
662 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
664 // ARM does not have i1 sign extending load.
665 for (MVT VT : MVT::integer_valuetypes())
666 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
668 // ARM supports all 4 flavors of integer indexed load / store.
669 if (!Subtarget->isThumb1Only()) {
670 for (unsigned im = (unsigned)ISD::PRE_INC;
671 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
672 setIndexedLoadAction(im, MVT::i1, Legal);
673 setIndexedLoadAction(im, MVT::i8, Legal);
674 setIndexedLoadAction(im, MVT::i16, Legal);
675 setIndexedLoadAction(im, MVT::i32, Legal);
676 setIndexedStoreAction(im, MVT::i1, Legal);
677 setIndexedStoreAction(im, MVT::i8, Legal);
678 setIndexedStoreAction(im, MVT::i16, Legal);
679 setIndexedStoreAction(im, MVT::i32, Legal);
683 setOperationAction(ISD::SADDO, MVT::i32, Custom);
684 setOperationAction(ISD::UADDO, MVT::i32, Custom);
685 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
686 setOperationAction(ISD::USUBO, MVT::i32, Custom);
688 // i64 operation support.
689 setOperationAction(ISD::MUL, MVT::i64, Expand);
690 setOperationAction(ISD::MULHU, MVT::i32, Expand);
691 if (Subtarget->isThumb1Only()) {
692 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
693 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
695 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
696 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
697 setOperationAction(ISD::MULHS, MVT::i32, Expand);
699 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
700 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
701 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
702 setOperationAction(ISD::SRL, MVT::i64, Custom);
703 setOperationAction(ISD::SRA, MVT::i64, Custom);
705 if (!Subtarget->isThumb1Only()) {
706 // FIXME: We should do this for Thumb1 as well.
707 setOperationAction(ISD::ADDC, MVT::i32, Custom);
708 setOperationAction(ISD::ADDE, MVT::i32, Custom);
709 setOperationAction(ISD::SUBC, MVT::i32, Custom);
710 setOperationAction(ISD::SUBE, MVT::i32, Custom);
713 // ARM does not have ROTL.
714 setOperationAction(ISD::ROTL, MVT::i32, Expand);
715 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
716 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
717 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
718 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
720 // These just redirect to CTTZ and CTLZ on ARM.
721 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
722 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
724 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
726 // Only ARMv6 has BSWAP.
727 if (!Subtarget->hasV6Ops())
728 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
730 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
731 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
732 // These are expanded into libcalls if the cpu doesn't have HW divider.
733 setOperationAction(ISD::SDIV, MVT::i32, Expand);
734 setOperationAction(ISD::UDIV, MVT::i32, Expand);
737 // FIXME: Also set divmod for SREM on EABI/androideabi
738 setOperationAction(ISD::SREM, MVT::i32, Expand);
739 setOperationAction(ISD::UREM, MVT::i32, Expand);
740 // Register based DivRem for AEABI (RTABI 4.2)
741 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
742 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
743 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
744 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
745 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
746 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
747 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
748 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
749 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
751 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
752 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
753 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
754 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
755 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
756 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
757 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
758 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
760 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
761 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
763 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
764 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
767 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
768 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
769 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
770 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
771 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
773 setOperationAction(ISD::TRAP, MVT::Other, Legal);
775 // Use the default implementation.
776 setOperationAction(ISD::VASTART, MVT::Other, Custom);
777 setOperationAction(ISD::VAARG, MVT::Other, Expand);
778 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
779 setOperationAction(ISD::VAEND, MVT::Other, Expand);
780 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
781 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
783 if (!Subtarget->isTargetMachO()) {
784 // Non-MachO platforms may return values in these registers via the
785 // personality function.
786 setExceptionPointerRegister(ARM::R0);
787 setExceptionSelectorRegister(ARM::R1);
790 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
791 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
793 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
795 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
796 // the default expansion. If we are targeting a single threaded system,
797 // then set them all for expand so we can lower them later into their
799 if (TM.Options.ThreadModel == ThreadModel::Single)
800 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
801 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
802 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
803 // to ldrex/strex loops already.
804 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
806 // On v8, we have particularly efficient implementations of atomic fences
807 // if they can be combined with nearby atomic loads and stores.
808 if (!Subtarget->hasV8Ops()) {
809 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
810 setInsertFencesForAtomic(true);
813 // If there's anything we can use as a barrier, go through custom lowering
815 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
816 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
818 // Set them all for expansion, which will force libcalls.
819 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
820 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
821 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
822 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
823 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
824 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
825 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
826 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
827 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
828 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
829 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
830 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
831 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
832 // Unordered/Monotonic case.
833 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
834 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
837 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
839 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
840 if (!Subtarget->hasV6Ops()) {
841 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
842 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
844 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
846 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
847 !Subtarget->isThumb1Only()) {
848 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
849 // iff target supports vfp2.
850 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
851 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
854 // We want to custom lower some of our intrinsics.
855 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
856 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
857 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
858 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
859 if (Subtarget->isTargetDarwin())
860 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
862 setOperationAction(ISD::SETCC, MVT::i32, Expand);
863 setOperationAction(ISD::SETCC, MVT::f32, Expand);
864 setOperationAction(ISD::SETCC, MVT::f64, Expand);
865 setOperationAction(ISD::SELECT, MVT::i32, Custom);
866 setOperationAction(ISD::SELECT, MVT::f32, Custom);
867 setOperationAction(ISD::SELECT, MVT::f64, Custom);
868 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
869 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
870 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
872 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
873 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
874 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
875 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
876 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
878 // We don't support sin/cos/fmod/copysign/pow
879 setOperationAction(ISD::FSIN, MVT::f64, Expand);
880 setOperationAction(ISD::FSIN, MVT::f32, Expand);
881 setOperationAction(ISD::FCOS, MVT::f32, Expand);
882 setOperationAction(ISD::FCOS, MVT::f64, Expand);
883 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
884 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
885 setOperationAction(ISD::FREM, MVT::f64, Expand);
886 setOperationAction(ISD::FREM, MVT::f32, Expand);
887 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
888 !Subtarget->isThumb1Only()) {
889 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
890 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
892 setOperationAction(ISD::FPOW, MVT::f64, Expand);
893 setOperationAction(ISD::FPOW, MVT::f32, Expand);
895 if (!Subtarget->hasVFP4()) {
896 setOperationAction(ISD::FMA, MVT::f64, Expand);
897 setOperationAction(ISD::FMA, MVT::f32, Expand);
900 // Various VFP goodness
901 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
902 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
903 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
904 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
905 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
908 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
909 if (!Subtarget->hasFP16()) {
910 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
911 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
915 // Combine sin / cos into one node or libcall if possible.
916 if (Subtarget->hasSinCos()) {
917 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
918 setLibcallName(RTLIB::SINCOS_F64, "sincos");
919 if (Subtarget->getTargetTriple().isiOS()) {
920 // For iOS, we don't want to the normal expansion of a libcall to
921 // sincos. We want to issue a libcall to __sincos_stret.
922 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
923 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
927 // FP-ARMv8 implements a lot of rounding-like FP operations.
928 if (Subtarget->hasFPARMv8()) {
929 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
930 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
931 setOperationAction(ISD::FROUND, MVT::f32, Legal);
932 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
933 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
934 setOperationAction(ISD::FRINT, MVT::f32, Legal);
935 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
936 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
937 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
938 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
939 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
940 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
942 if (!Subtarget->isFPOnlySP()) {
943 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
944 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
945 setOperationAction(ISD::FROUND, MVT::f64, Legal);
946 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
947 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
948 setOperationAction(ISD::FRINT, MVT::f64, Legal);
949 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
950 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
954 if (Subtarget->hasVFP3()) {
955 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
956 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
957 setOperationAction(ISD::FMINNAN, MVT::f64, Legal);
958 setOperationAction(ISD::FMAXNAN, MVT::f64, Legal);
961 // We have target-specific dag combine patterns for the following nodes:
962 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
963 setTargetDAGCombine(ISD::ADD);
964 setTargetDAGCombine(ISD::SUB);
965 setTargetDAGCombine(ISD::MUL);
966 setTargetDAGCombine(ISD::AND);
967 setTargetDAGCombine(ISD::OR);
968 setTargetDAGCombine(ISD::XOR);
970 if (Subtarget->hasV6Ops())
971 setTargetDAGCombine(ISD::SRL);
973 setStackPointerRegisterToSaveRestore(ARM::SP);
975 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
976 !Subtarget->hasVFP2())
977 setSchedulingPreference(Sched::RegPressure);
979 setSchedulingPreference(Sched::Hybrid);
981 //// temporary - rewrite interface to use type
982 MaxStoresPerMemset = 8;
983 MaxStoresPerMemsetOptSize = 4;
984 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
985 MaxStoresPerMemcpyOptSize = 2;
986 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
987 MaxStoresPerMemmoveOptSize = 2;
989 // On ARM arguments smaller than 4 bytes are extended, so all arguments
990 // are at least 4 bytes aligned.
991 setMinStackArgumentAlignment(4);
993 // Prefer likely predicted branches to selects on out-of-order cores.
994 PredictableSelectIsExpensive = Subtarget->isLikeA9();
996 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
999 bool ARMTargetLowering::useSoftFloat() const {
1000 return Subtarget->useSoftFloat();
1003 // FIXME: It might make sense to define the representative register class as the
1004 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1005 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1006 // SPR's representative would be DPR_VFP2. This should work well if register
1007 // pressure tracking were modified such that a register use would increment the
1008 // pressure of the register class's representative and all of it's super
1009 // classes' representatives transitively. We have not implemented this because
1010 // of the difficulty prior to coalescing of modeling operand register classes
1011 // due to the common occurrence of cross class copies and subregister insertions
1013 std::pair<const TargetRegisterClass *, uint8_t>
1014 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1016 const TargetRegisterClass *RRC = nullptr;
1018 switch (VT.SimpleTy) {
1020 return TargetLowering::findRepresentativeClass(TRI, VT);
1021 // Use DPR as representative register class for all floating point
1022 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1023 // the cost is 1 for both f32 and f64.
1024 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1025 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1026 RRC = &ARM::DPRRegClass;
1027 // When NEON is used for SP, only half of the register file is available
1028 // because operations that define both SP and DP results will be constrained
1029 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1030 // coalescing by double-counting the SP regs. See the FIXME above.
1031 if (Subtarget->useNEONForSinglePrecisionFP())
1034 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1035 case MVT::v4f32: case MVT::v2f64:
1036 RRC = &ARM::DPRRegClass;
1040 RRC = &ARM::DPRRegClass;
1044 RRC = &ARM::DPRRegClass;
1048 return std::make_pair(RRC, Cost);
1051 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1052 switch ((ARMISD::NodeType)Opcode) {
1053 case ARMISD::FIRST_NUMBER: break;
1054 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1055 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1056 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1057 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1058 case ARMISD::CALL: return "ARMISD::CALL";
1059 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1060 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1061 case ARMISD::tCALL: return "ARMISD::tCALL";
1062 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1063 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1064 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1065 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1066 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1067 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1068 case ARMISD::CMP: return "ARMISD::CMP";
1069 case ARMISD::CMN: return "ARMISD::CMN";
1070 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1071 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1072 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1073 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1074 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1076 case ARMISD::CMOV: return "ARMISD::CMOV";
1078 case ARMISD::RBIT: return "ARMISD::RBIT";
1080 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1081 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1082 case ARMISD::RRX: return "ARMISD::RRX";
1084 case ARMISD::ADDC: return "ARMISD::ADDC";
1085 case ARMISD::ADDE: return "ARMISD::ADDE";
1086 case ARMISD::SUBC: return "ARMISD::SUBC";
1087 case ARMISD::SUBE: return "ARMISD::SUBE";
1089 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1090 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1092 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1093 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1094 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1096 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1098 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1100 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1102 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1104 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1106 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1108 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1109 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1110 case ARMISD::VCGE: return "ARMISD::VCGE";
1111 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1112 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1113 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1114 case ARMISD::VCGT: return "ARMISD::VCGT";
1115 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1116 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1117 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1118 case ARMISD::VTST: return "ARMISD::VTST";
1120 case ARMISD::VSHL: return "ARMISD::VSHL";
1121 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1122 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1123 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1124 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1125 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1126 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1127 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1128 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1129 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1130 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1131 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1132 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1133 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1134 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1135 case ARMISD::VSLI: return "ARMISD::VSLI";
1136 case ARMISD::VSRI: return "ARMISD::VSRI";
1137 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1138 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1139 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1140 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1141 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1142 case ARMISD::VDUP: return "ARMISD::VDUP";
1143 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1144 case ARMISD::VEXT: return "ARMISD::VEXT";
1145 case ARMISD::VREV64: return "ARMISD::VREV64";
1146 case ARMISD::VREV32: return "ARMISD::VREV32";
1147 case ARMISD::VREV16: return "ARMISD::VREV16";
1148 case ARMISD::VZIP: return "ARMISD::VZIP";
1149 case ARMISD::VUZP: return "ARMISD::VUZP";
1150 case ARMISD::VTRN: return "ARMISD::VTRN";
1151 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1152 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1153 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1154 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1155 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1156 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1157 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1158 case ARMISD::BFI: return "ARMISD::BFI";
1159 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1160 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1161 case ARMISD::VBSL: return "ARMISD::VBSL";
1162 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1163 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1164 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1165 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1166 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1167 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1168 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1169 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1170 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1171 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1172 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1173 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1174 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1175 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1176 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1177 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1178 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1179 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1180 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1181 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1186 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1189 return getPointerTy(DL);
1190 return VT.changeVectorElementTypeToInteger();
1193 /// getRegClassFor - Return the register class that should be used for the
1194 /// specified value type.
1195 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1196 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1197 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1198 // load / store 4 to 8 consecutive D registers.
1199 if (Subtarget->hasNEON()) {
1200 if (VT == MVT::v4i64)
1201 return &ARM::QQPRRegClass;
1202 if (VT == MVT::v8i64)
1203 return &ARM::QQQQPRRegClass;
1205 return TargetLowering::getRegClassFor(VT);
1208 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1209 // source/dest is aligned and the copy size is large enough. We therefore want
1210 // to align such objects passed to memory intrinsics.
1211 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1212 unsigned &PrefAlign) const {
1213 if (!isa<MemIntrinsic>(CI))
1216 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1217 // cycle faster than 4-byte aligned LDM.
1218 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1222 // Create a fast isel object.
1224 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1225 const TargetLibraryInfo *libInfo) const {
1226 return ARM::createFastISel(funcInfo, libInfo);
1229 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1230 unsigned NumVals = N->getNumValues();
1232 return Sched::RegPressure;
1234 for (unsigned i = 0; i != NumVals; ++i) {
1235 EVT VT = N->getValueType(i);
1236 if (VT == MVT::Glue || VT == MVT::Other)
1238 if (VT.isFloatingPoint() || VT.isVector())
1242 if (!N->isMachineOpcode())
1243 return Sched::RegPressure;
1245 // Load are scheduled for latency even if there instruction itinerary
1246 // is not available.
1247 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1248 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1250 if (MCID.getNumDefs() == 0)
1251 return Sched::RegPressure;
1252 if (!Itins->isEmpty() &&
1253 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1256 return Sched::RegPressure;
1259 //===----------------------------------------------------------------------===//
1261 //===----------------------------------------------------------------------===//
1263 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1264 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1266 default: llvm_unreachable("Unknown condition code!");
1267 case ISD::SETNE: return ARMCC::NE;
1268 case ISD::SETEQ: return ARMCC::EQ;
1269 case ISD::SETGT: return ARMCC::GT;
1270 case ISD::SETGE: return ARMCC::GE;
1271 case ISD::SETLT: return ARMCC::LT;
1272 case ISD::SETLE: return ARMCC::LE;
1273 case ISD::SETUGT: return ARMCC::HI;
1274 case ISD::SETUGE: return ARMCC::HS;
1275 case ISD::SETULT: return ARMCC::LO;
1276 case ISD::SETULE: return ARMCC::LS;
1280 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1281 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1282 ARMCC::CondCodes &CondCode2) {
1283 CondCode2 = ARMCC::AL;
1285 default: llvm_unreachable("Unknown FP condition!");
1287 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1289 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1291 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1292 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1293 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1294 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1295 case ISD::SETO: CondCode = ARMCC::VC; break;
1296 case ISD::SETUO: CondCode = ARMCC::VS; break;
1297 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1298 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1299 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1301 case ISD::SETULT: CondCode = ARMCC::LT; break;
1303 case ISD::SETULE: CondCode = ARMCC::LE; break;
1305 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1309 //===----------------------------------------------------------------------===//
1310 // Calling Convention Implementation
1311 //===----------------------------------------------------------------------===//
1313 #include "ARMGenCallingConv.inc"
1315 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1316 /// account presence of floating point hardware and calling convention
1317 /// limitations, such as support for variadic functions.
1319 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1320 bool isVarArg) const {
1323 llvm_unreachable("Unsupported calling convention");
1324 case CallingConv::ARM_AAPCS:
1325 case CallingConv::ARM_APCS:
1326 case CallingConv::GHC:
1328 case CallingConv::ARM_AAPCS_VFP:
1329 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1330 case CallingConv::C:
1331 if (!Subtarget->isAAPCS_ABI())
1332 return CallingConv::ARM_APCS;
1333 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1334 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1336 return CallingConv::ARM_AAPCS_VFP;
1338 return CallingConv::ARM_AAPCS;
1339 case CallingConv::Fast:
1340 if (!Subtarget->isAAPCS_ABI()) {
1341 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1342 return CallingConv::Fast;
1343 return CallingConv::ARM_APCS;
1344 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1345 return CallingConv::ARM_AAPCS_VFP;
1347 return CallingConv::ARM_AAPCS;
1351 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1352 /// CallingConvention.
1353 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1355 bool isVarArg) const {
1356 switch (getEffectiveCallingConv(CC, isVarArg)) {
1358 llvm_unreachable("Unsupported calling convention");
1359 case CallingConv::ARM_APCS:
1360 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1361 case CallingConv::ARM_AAPCS:
1362 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1363 case CallingConv::ARM_AAPCS_VFP:
1364 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1365 case CallingConv::Fast:
1366 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1367 case CallingConv::GHC:
1368 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1372 /// LowerCallResult - Lower the result values of a call into the
1373 /// appropriate copies out of appropriate physical registers.
1375 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1376 CallingConv::ID CallConv, bool isVarArg,
1377 const SmallVectorImpl<ISD::InputArg> &Ins,
1378 SDLoc dl, SelectionDAG &DAG,
1379 SmallVectorImpl<SDValue> &InVals,
1380 bool isThisReturn, SDValue ThisVal) const {
1382 // Assign locations to each value returned by this call.
1383 SmallVector<CCValAssign, 16> RVLocs;
1384 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1385 *DAG.getContext(), Call);
1386 CCInfo.AnalyzeCallResult(Ins,
1387 CCAssignFnForNode(CallConv, /* Return*/ true,
1390 // Copy all of the result registers out of their specified physreg.
1391 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1392 CCValAssign VA = RVLocs[i];
1394 // Pass 'this' value directly from the argument to return value, to avoid
1395 // reg unit interference
1396 if (i == 0 && isThisReturn) {
1397 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1398 "unexpected return calling convention register assignment");
1399 InVals.push_back(ThisVal);
1404 if (VA.needsCustom()) {
1405 // Handle f64 or half of a v2f64.
1406 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1408 Chain = Lo.getValue(1);
1409 InFlag = Lo.getValue(2);
1410 VA = RVLocs[++i]; // skip ahead to next loc
1411 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1413 Chain = Hi.getValue(1);
1414 InFlag = Hi.getValue(2);
1415 if (!Subtarget->isLittle())
1417 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1419 if (VA.getLocVT() == MVT::v2f64) {
1420 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1421 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1422 DAG.getConstant(0, dl, MVT::i32));
1424 VA = RVLocs[++i]; // skip ahead to next loc
1425 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1426 Chain = Lo.getValue(1);
1427 InFlag = Lo.getValue(2);
1428 VA = RVLocs[++i]; // skip ahead to next loc
1429 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1430 Chain = Hi.getValue(1);
1431 InFlag = Hi.getValue(2);
1432 if (!Subtarget->isLittle())
1434 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1435 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1436 DAG.getConstant(1, dl, MVT::i32));
1439 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1441 Chain = Val.getValue(1);
1442 InFlag = Val.getValue(2);
1445 switch (VA.getLocInfo()) {
1446 default: llvm_unreachable("Unknown loc info!");
1447 case CCValAssign::Full: break;
1448 case CCValAssign::BCvt:
1449 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1453 InVals.push_back(Val);
1459 /// LowerMemOpCallTo - Store the argument to the stack.
1461 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1462 SDValue StackPtr, SDValue Arg,
1463 SDLoc dl, SelectionDAG &DAG,
1464 const CCValAssign &VA,
1465 ISD::ArgFlagsTy Flags) const {
1466 unsigned LocMemOffset = VA.getLocMemOffset();
1467 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1468 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1470 return DAG.getStore(Chain, dl, Arg, PtrOff,
1471 MachinePointerInfo::getStack(LocMemOffset),
1475 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1476 SDValue Chain, SDValue &Arg,
1477 RegsToPassVector &RegsToPass,
1478 CCValAssign &VA, CCValAssign &NextVA,
1480 SmallVectorImpl<SDValue> &MemOpChains,
1481 ISD::ArgFlagsTy Flags) const {
1483 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1484 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1485 unsigned id = Subtarget->isLittle() ? 0 : 1;
1486 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1488 if (NextVA.isRegLoc())
1489 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1491 assert(NextVA.isMemLoc());
1492 if (!StackPtr.getNode())
1493 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1494 getPointerTy(DAG.getDataLayout()));
1496 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1502 /// LowerCall - Lowering a call into a callseq_start <-
1503 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1506 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1507 SmallVectorImpl<SDValue> &InVals) const {
1508 SelectionDAG &DAG = CLI.DAG;
1510 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1511 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1512 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1513 SDValue Chain = CLI.Chain;
1514 SDValue Callee = CLI.Callee;
1515 bool &isTailCall = CLI.IsTailCall;
1516 CallingConv::ID CallConv = CLI.CallConv;
1517 bool doesNotRet = CLI.DoesNotReturn;
1518 bool isVarArg = CLI.IsVarArg;
1520 MachineFunction &MF = DAG.getMachineFunction();
1521 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1522 bool isThisReturn = false;
1523 bool isSibCall = false;
1524 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1526 // Disable tail calls if they're not supported.
1527 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1531 // Check if it's really possible to do a tail call.
1532 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1533 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1534 Outs, OutVals, Ins, DAG);
1535 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1536 report_fatal_error("failed to perform tail call elimination on a call "
1537 "site marked musttail");
1538 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1539 // detected sibcalls.
1546 // Analyze operands of the call, assigning locations to each operand.
1547 SmallVector<CCValAssign, 16> ArgLocs;
1548 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1549 *DAG.getContext(), Call);
1550 CCInfo.AnalyzeCallOperands(Outs,
1551 CCAssignFnForNode(CallConv, /* Return*/ false,
1554 // Get a count of how many bytes are to be pushed on the stack.
1555 unsigned NumBytes = CCInfo.getNextStackOffset();
1557 // For tail calls, memory operands are available in our caller's stack.
1561 // Adjust the stack pointer for the new arguments...
1562 // These operations are automatically eliminated by the prolog/epilog pass
1564 Chain = DAG.getCALLSEQ_START(Chain,
1565 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1568 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1570 RegsToPassVector RegsToPass;
1571 SmallVector<SDValue, 8> MemOpChains;
1573 // Walk the register/memloc assignments, inserting copies/loads. In the case
1574 // of tail call optimization, arguments are handled later.
1575 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1577 ++i, ++realArgIdx) {
1578 CCValAssign &VA = ArgLocs[i];
1579 SDValue Arg = OutVals[realArgIdx];
1580 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1581 bool isByVal = Flags.isByVal();
1583 // Promote the value if needed.
1584 switch (VA.getLocInfo()) {
1585 default: llvm_unreachable("Unknown loc info!");
1586 case CCValAssign::Full: break;
1587 case CCValAssign::SExt:
1588 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1590 case CCValAssign::ZExt:
1591 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1593 case CCValAssign::AExt:
1594 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1596 case CCValAssign::BCvt:
1597 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1601 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1602 if (VA.needsCustom()) {
1603 if (VA.getLocVT() == MVT::v2f64) {
1604 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1605 DAG.getConstant(0, dl, MVT::i32));
1606 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1607 DAG.getConstant(1, dl, MVT::i32));
1609 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1610 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1612 VA = ArgLocs[++i]; // skip ahead to next loc
1613 if (VA.isRegLoc()) {
1614 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1615 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1617 assert(VA.isMemLoc());
1619 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1620 dl, DAG, VA, Flags));
1623 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1624 StackPtr, MemOpChains, Flags);
1626 } else if (VA.isRegLoc()) {
1627 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1628 assert(VA.getLocVT() == MVT::i32 &&
1629 "unexpected calling convention register assignment");
1630 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1631 "unexpected use of 'returned'");
1632 isThisReturn = true;
1634 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1635 } else if (isByVal) {
1636 assert(VA.isMemLoc());
1637 unsigned offset = 0;
1639 // True if this byval aggregate will be split between registers
1641 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1642 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1644 if (CurByValIdx < ByValArgsCount) {
1646 unsigned RegBegin, RegEnd;
1647 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1650 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1652 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1653 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1654 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1655 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1656 MachinePointerInfo(),
1657 false, false, false,
1658 DAG.InferPtrAlignment(AddArg));
1659 MemOpChains.push_back(Load.getValue(1));
1660 RegsToPass.push_back(std::make_pair(j, Load));
1663 // If parameter size outsides register area, "offset" value
1664 // helps us to calculate stack slot for remained part properly.
1665 offset = RegEnd - RegBegin;
1667 CCInfo.nextInRegsParam();
1670 if (Flags.getByValSize() > 4*offset) {
1671 auto PtrVT = getPointerTy(DAG.getDataLayout());
1672 unsigned LocMemOffset = VA.getLocMemOffset();
1673 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1674 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1675 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1676 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1677 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1679 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1682 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1683 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1684 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1687 } else if (!isSibCall) {
1688 assert(VA.isMemLoc());
1690 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1691 dl, DAG, VA, Flags));
1695 if (!MemOpChains.empty())
1696 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1698 // Build a sequence of copy-to-reg nodes chained together with token chain
1699 // and flag operands which copy the outgoing args into the appropriate regs.
1701 // Tail call byval lowering might overwrite argument registers so in case of
1702 // tail call optimization the copies to registers are lowered later.
1704 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1705 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1706 RegsToPass[i].second, InFlag);
1707 InFlag = Chain.getValue(1);
1710 // For tail calls lower the arguments to the 'real' stack slot.
1712 // Force all the incoming stack arguments to be loaded from the stack
1713 // before any new outgoing arguments are stored to the stack, because the
1714 // outgoing stack slots may alias the incoming argument stack slots, and
1715 // the alias isn't otherwise explicit. This is slightly more conservative
1716 // than necessary, because it means that each store effectively depends
1717 // on every argument instead of just those arguments it would clobber.
1719 // Do not flag preceding copytoreg stuff together with the following stuff.
1721 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1722 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1723 RegsToPass[i].second, InFlag);
1724 InFlag = Chain.getValue(1);
1729 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1730 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1731 // node so that legalize doesn't hack it.
1732 bool isDirect = false;
1733 bool isARMFunc = false;
1734 bool isLocalARMFunc = false;
1735 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1736 auto PtrVt = getPointerTy(DAG.getDataLayout());
1738 if (Subtarget->genLongCalls()) {
1739 assert((Subtarget->isTargetWindows() ||
1740 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1741 "long-calls with non-static relocation model!");
1742 // Handle a global address or an external symbol. If it's not one of
1743 // those, the target's already in a register, so we don't need to do
1745 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1746 const GlobalValue *GV = G->getGlobal();
1747 // Create a constant pool entry for the callee address
1748 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1749 ARMConstantPoolValue *CPV =
1750 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1752 // Get the address of the callee into a register
1753 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1754 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1755 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1756 MachinePointerInfo::getConstantPool(), false, false,
1758 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1759 const char *Sym = S->getSymbol();
1761 // Create a constant pool entry for the callee address
1762 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1763 ARMConstantPoolValue *CPV =
1764 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1765 ARMPCLabelIndex, 0);
1766 // Get the address of the callee into a register
1767 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1768 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1769 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1770 MachinePointerInfo::getConstantPool(), false, false,
1773 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1774 const GlobalValue *GV = G->getGlobal();
1776 bool isDef = GV->isStrongDefinitionForLinker();
1777 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1778 getTargetMachine().getRelocationModel() != Reloc::Static;
1779 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1780 // ARM call to a local ARM function is predicable.
1781 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1782 // tBX takes a register source operand.
1783 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1784 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1785 Callee = DAG.getNode(
1786 ARMISD::WrapperPIC, dl, PtrVt,
1787 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1788 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1789 MachinePointerInfo::getGOT(), false, false, true, 0);
1790 } else if (Subtarget->isTargetCOFF()) {
1791 assert(Subtarget->isTargetWindows() &&
1792 "Windows is the only supported COFF target");
1793 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1794 ? ARMII::MO_DLLIMPORT
1795 : ARMII::MO_NO_FLAG;
1797 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1798 if (GV->hasDLLImportStorageClass())
1800 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1801 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1802 MachinePointerInfo::getGOT(), false, false, false, 0);
1804 // On ELF targets for PIC code, direct calls should go through the PLT
1805 unsigned OpFlags = 0;
1806 if (Subtarget->isTargetELF() &&
1807 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1808 OpFlags = ARMII::MO_PLT;
1809 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1811 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1813 bool isStub = Subtarget->isTargetMachO() &&
1814 getTargetMachine().getRelocationModel() != Reloc::Static;
1815 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1816 // tBX takes a register source operand.
1817 const char *Sym = S->getSymbol();
1818 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1819 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1820 ARMConstantPoolValue *CPV =
1821 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1822 ARMPCLabelIndex, 4);
1823 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1824 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1825 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1826 MachinePointerInfo::getConstantPool(), false, false,
1828 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1829 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1831 unsigned OpFlags = 0;
1832 // On ELF targets for PIC code, direct calls should go through the PLT
1833 if (Subtarget->isTargetELF() &&
1834 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1835 OpFlags = ARMII::MO_PLT;
1836 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1840 // FIXME: handle tail calls differently.
1842 if (Subtarget->isThumb()) {
1843 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1844 CallOpc = ARMISD::CALL_NOLINK;
1846 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1848 if (!isDirect && !Subtarget->hasV5TOps())
1849 CallOpc = ARMISD::CALL_NOLINK;
1850 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1851 // Emit regular call when code size is the priority
1852 !MF.getFunction()->optForMinSize())
1853 // "mov lr, pc; b _foo" to avoid confusing the RSP
1854 CallOpc = ARMISD::CALL_NOLINK;
1856 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1859 std::vector<SDValue> Ops;
1860 Ops.push_back(Chain);
1861 Ops.push_back(Callee);
1863 // Add argument registers to the end of the list so that they are known live
1865 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1866 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1867 RegsToPass[i].second.getValueType()));
1869 // Add a register mask operand representing the call-preserved registers.
1871 const uint32_t *Mask;
1872 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1874 // For 'this' returns, use the R0-preserving mask if applicable
1875 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1877 // Set isThisReturn to false if the calling convention is not one that
1878 // allows 'returned' to be modeled in this way, so LowerCallResult does
1879 // not try to pass 'this' straight through
1880 isThisReturn = false;
1881 Mask = ARI->getCallPreservedMask(MF, CallConv);
1884 Mask = ARI->getCallPreservedMask(MF, CallConv);
1886 assert(Mask && "Missing call preserved mask for calling convention");
1887 Ops.push_back(DAG.getRegisterMask(Mask));
1890 if (InFlag.getNode())
1891 Ops.push_back(InFlag);
1893 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1895 MF.getFrameInfo()->setHasTailCall();
1896 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1899 // Returns a chain and a flag for retval copy to use.
1900 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1901 InFlag = Chain.getValue(1);
1903 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1904 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1906 InFlag = Chain.getValue(1);
1908 // Handle result values, copying them out of physregs into vregs that we
1910 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1911 InVals, isThisReturn,
1912 isThisReturn ? OutVals[0] : SDValue());
1915 /// HandleByVal - Every parameter *after* a byval parameter is passed
1916 /// on the stack. Remember the next parameter register to allocate,
1917 /// and then confiscate the rest of the parameter registers to insure
1919 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1920 unsigned Align) const {
1921 assert((State->getCallOrPrologue() == Prologue ||
1922 State->getCallOrPrologue() == Call) &&
1923 "unhandled ParmContext");
1925 // Byval (as with any stack) slots are always at least 4 byte aligned.
1926 Align = std::max(Align, 4U);
1928 unsigned Reg = State->AllocateReg(GPRArgRegs);
1932 unsigned AlignInRegs = Align / 4;
1933 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1934 for (unsigned i = 0; i < Waste; ++i)
1935 Reg = State->AllocateReg(GPRArgRegs);
1940 unsigned Excess = 4 * (ARM::R4 - Reg);
1942 // Special case when NSAA != SP and parameter size greater than size of
1943 // all remained GPR regs. In that case we can't split parameter, we must
1944 // send it to stack. We also must set NCRN to R4, so waste all
1945 // remained registers.
1946 const unsigned NSAAOffset = State->getNextStackOffset();
1947 if (NSAAOffset != 0 && Size > Excess) {
1948 while (State->AllocateReg(GPRArgRegs))
1953 // First register for byval parameter is the first register that wasn't
1954 // allocated before this method call, so it would be "reg".
1955 // If parameter is small enough to be saved in range [reg, r4), then
1956 // the end (first after last) register would be reg + param-size-in-regs,
1957 // else parameter would be splitted between registers and stack,
1958 // end register would be r4 in this case.
1959 unsigned ByValRegBegin = Reg;
1960 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1961 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1962 // Note, first register is allocated in the beginning of function already,
1963 // allocate remained amount of registers we need.
1964 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1965 State->AllocateReg(GPRArgRegs);
1966 // A byval parameter that is split between registers and memory needs its
1967 // size truncated here.
1968 // In the case where the entire structure fits in registers, we set the
1969 // size in memory to zero.
1970 Size = std::max<int>(Size - Excess, 0);
1973 /// MatchingStackOffset - Return true if the given stack call argument is
1974 /// already available in the same position (relatively) of the caller's
1975 /// incoming argument stack.
1977 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1978 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1979 const TargetInstrInfo *TII) {
1980 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1982 if (Arg.getOpcode() == ISD::CopyFromReg) {
1983 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1984 if (!TargetRegisterInfo::isVirtualRegister(VR))
1986 MachineInstr *Def = MRI->getVRegDef(VR);
1989 if (!Flags.isByVal()) {
1990 if (!TII->isLoadFromStackSlot(Def, FI))
1995 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1996 if (Flags.isByVal())
1997 // ByVal argument is passed in as a pointer but it's now being
1998 // dereferenced. e.g.
1999 // define @foo(%struct.X* %A) {
2000 // tail call @bar(%struct.X* byval %A)
2003 SDValue Ptr = Ld->getBasePtr();
2004 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2007 FI = FINode->getIndex();
2011 assert(FI != INT_MAX);
2012 if (!MFI->isFixedObjectIndex(FI))
2014 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2017 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2018 /// for tail call optimization. Targets which want to do tail call
2019 /// optimization should implement this function.
2021 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2022 CallingConv::ID CalleeCC,
2024 bool isCalleeStructRet,
2025 bool isCallerStructRet,
2026 const SmallVectorImpl<ISD::OutputArg> &Outs,
2027 const SmallVectorImpl<SDValue> &OutVals,
2028 const SmallVectorImpl<ISD::InputArg> &Ins,
2029 SelectionDAG& DAG) const {
2030 const Function *CallerF = DAG.getMachineFunction().getFunction();
2031 CallingConv::ID CallerCC = CallerF->getCallingConv();
2032 bool CCMatch = CallerCC == CalleeCC;
2034 // Look for obvious safe cases to perform tail call optimization that do not
2035 // require ABI changes. This is what gcc calls sibcall.
2037 // Do not sibcall optimize vararg calls unless the call site is not passing
2039 if (isVarArg && !Outs.empty())
2042 // Exception-handling functions need a special set of instructions to indicate
2043 // a return to the hardware. Tail-calling another function would probably
2045 if (CallerF->hasFnAttribute("interrupt"))
2048 // Also avoid sibcall optimization if either caller or callee uses struct
2049 // return semantics.
2050 if (isCalleeStructRet || isCallerStructRet)
2053 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2054 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2055 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2056 // support in the assembler and linker to be used. This would need to be
2057 // fixed to fully support tail calls in Thumb1.
2059 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2060 // LR. This means if we need to reload LR, it takes an extra instructions,
2061 // which outweighs the value of the tail call; but here we don't know yet
2062 // whether LR is going to be used. Probably the right approach is to
2063 // generate the tail call here and turn it back into CALL/RET in
2064 // emitEpilogue if LR is used.
2066 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2067 // but we need to make sure there are enough registers; the only valid
2068 // registers are the 4 used for parameters. We don't currently do this
2070 if (Subtarget->isThumb1Only())
2073 // Externally-defined functions with weak linkage should not be
2074 // tail-called on ARM when the OS does not support dynamic
2075 // pre-emption of symbols, as the AAELF spec requires normal calls
2076 // to undefined weak functions to be replaced with a NOP or jump to the
2077 // next instruction. The behaviour of branch instructions in this
2078 // situation (as used for tail calls) is implementation-defined, so we
2079 // cannot rely on the linker replacing the tail call with a return.
2080 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2081 const GlobalValue *GV = G->getGlobal();
2082 const Triple &TT = getTargetMachine().getTargetTriple();
2083 if (GV->hasExternalWeakLinkage() &&
2084 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2088 // If the calling conventions do not match, then we'd better make sure the
2089 // results are returned in the same way as what the caller expects.
2091 SmallVector<CCValAssign, 16> RVLocs1;
2092 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2093 *DAG.getContext(), Call);
2094 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2096 SmallVector<CCValAssign, 16> RVLocs2;
2097 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2098 *DAG.getContext(), Call);
2099 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2101 if (RVLocs1.size() != RVLocs2.size())
2103 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2104 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2106 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2108 if (RVLocs1[i].isRegLoc()) {
2109 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2112 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2118 // If Caller's vararg or byval argument has been split between registers and
2119 // stack, do not perform tail call, since part of the argument is in caller's
2121 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2122 getInfo<ARMFunctionInfo>();
2123 if (AFI_Caller->getArgRegsSaveSize())
2126 // If the callee takes no arguments then go on to check the results of the
2128 if (!Outs.empty()) {
2129 // Check if stack adjustment is needed. For now, do not do this if any
2130 // argument is passed on the stack.
2131 SmallVector<CCValAssign, 16> ArgLocs;
2132 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2133 *DAG.getContext(), Call);
2134 CCInfo.AnalyzeCallOperands(Outs,
2135 CCAssignFnForNode(CalleeCC, false, isVarArg));
2136 if (CCInfo.getNextStackOffset()) {
2137 MachineFunction &MF = DAG.getMachineFunction();
2139 // Check if the arguments are already laid out in the right way as
2140 // the caller's fixed stack objects.
2141 MachineFrameInfo *MFI = MF.getFrameInfo();
2142 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2143 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2144 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2146 ++i, ++realArgIdx) {
2147 CCValAssign &VA = ArgLocs[i];
2148 EVT RegVT = VA.getLocVT();
2149 SDValue Arg = OutVals[realArgIdx];
2150 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2151 if (VA.getLocInfo() == CCValAssign::Indirect)
2153 if (VA.needsCustom()) {
2154 // f64 and vector types are split into multiple registers or
2155 // register/stack-slot combinations. The types will not match
2156 // the registers; give up on memory f64 refs until we figure
2157 // out what to do about this.
2160 if (!ArgLocs[++i].isRegLoc())
2162 if (RegVT == MVT::v2f64) {
2163 if (!ArgLocs[++i].isRegLoc())
2165 if (!ArgLocs[++i].isRegLoc())
2168 } else if (!VA.isRegLoc()) {
2169 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2181 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2182 MachineFunction &MF, bool isVarArg,
2183 const SmallVectorImpl<ISD::OutputArg> &Outs,
2184 LLVMContext &Context) const {
2185 SmallVector<CCValAssign, 16> RVLocs;
2186 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2187 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2191 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2192 SDLoc DL, SelectionDAG &DAG) {
2193 const MachineFunction &MF = DAG.getMachineFunction();
2194 const Function *F = MF.getFunction();
2196 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2198 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2199 // version of the "preferred return address". These offsets affect the return
2200 // instruction if this is a return from PL1 without hypervisor extensions.
2201 // IRQ/FIQ: +4 "subs pc, lr, #4"
2202 // SWI: 0 "subs pc, lr, #0"
2203 // ABORT: +4 "subs pc, lr, #4"
2204 // UNDEF: +4/+2 "subs pc, lr, #0"
2205 // UNDEF varies depending on where the exception came from ARM or Thumb
2206 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2209 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2212 else if (IntKind == "SWI" || IntKind == "UNDEF")
2215 report_fatal_error("Unsupported interrupt attribute. If present, value "
2216 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2218 RetOps.insert(RetOps.begin() + 1,
2219 DAG.getConstant(LROffset, DL, MVT::i32, false));
2221 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2225 ARMTargetLowering::LowerReturn(SDValue Chain,
2226 CallingConv::ID CallConv, bool isVarArg,
2227 const SmallVectorImpl<ISD::OutputArg> &Outs,
2228 const SmallVectorImpl<SDValue> &OutVals,
2229 SDLoc dl, SelectionDAG &DAG) const {
2231 // CCValAssign - represent the assignment of the return value to a location.
2232 SmallVector<CCValAssign, 16> RVLocs;
2234 // CCState - Info about the registers and stack slots.
2235 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2236 *DAG.getContext(), Call);
2238 // Analyze outgoing return values.
2239 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2243 SmallVector<SDValue, 4> RetOps;
2244 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2245 bool isLittleEndian = Subtarget->isLittle();
2247 MachineFunction &MF = DAG.getMachineFunction();
2248 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2249 AFI->setReturnRegsCount(RVLocs.size());
2251 // Copy the result values into the output registers.
2252 for (unsigned i = 0, realRVLocIdx = 0;
2254 ++i, ++realRVLocIdx) {
2255 CCValAssign &VA = RVLocs[i];
2256 assert(VA.isRegLoc() && "Can only return in registers!");
2258 SDValue Arg = OutVals[realRVLocIdx];
2260 switch (VA.getLocInfo()) {
2261 default: llvm_unreachable("Unknown loc info!");
2262 case CCValAssign::Full: break;
2263 case CCValAssign::BCvt:
2264 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2268 if (VA.needsCustom()) {
2269 if (VA.getLocVT() == MVT::v2f64) {
2270 // Extract the first half and return it in two registers.
2271 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2272 DAG.getConstant(0, dl, MVT::i32));
2273 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2274 DAG.getVTList(MVT::i32, MVT::i32), Half);
2276 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2277 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2279 Flag = Chain.getValue(1);
2280 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2281 VA = RVLocs[++i]; // skip ahead to next loc
2282 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2283 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2285 Flag = Chain.getValue(1);
2286 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2287 VA = RVLocs[++i]; // skip ahead to next loc
2289 // Extract the 2nd half and fall through to handle it as an f64 value.
2290 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2291 DAG.getConstant(1, dl, MVT::i32));
2293 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2295 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2296 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2297 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2298 fmrrd.getValue(isLittleEndian ? 0 : 1),
2300 Flag = Chain.getValue(1);
2301 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2302 VA = RVLocs[++i]; // skip ahead to next loc
2303 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2304 fmrrd.getValue(isLittleEndian ? 1 : 0),
2307 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2309 // Guarantee that all emitted copies are
2310 // stuck together, avoiding something bad.
2311 Flag = Chain.getValue(1);
2312 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2315 // Update chain and glue.
2318 RetOps.push_back(Flag);
2320 // CPUs which aren't M-class use a special sequence to return from
2321 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2322 // though we use "subs pc, lr, #N").
2324 // M-class CPUs actually use a normal return sequence with a special
2325 // (hardware-provided) value in LR, so the normal code path works.
2326 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2327 !Subtarget->isMClass()) {
2328 if (Subtarget->isThumb1Only())
2329 report_fatal_error("interrupt attribute is not supported in Thumb1");
2330 return LowerInterruptReturn(RetOps, dl, DAG);
2333 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2336 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2337 if (N->getNumValues() != 1)
2339 if (!N->hasNUsesOfValue(1, 0))
2342 SDValue TCChain = Chain;
2343 SDNode *Copy = *N->use_begin();
2344 if (Copy->getOpcode() == ISD::CopyToReg) {
2345 // If the copy has a glue operand, we conservatively assume it isn't safe to
2346 // perform a tail call.
2347 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2349 TCChain = Copy->getOperand(0);
2350 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2351 SDNode *VMov = Copy;
2352 // f64 returned in a pair of GPRs.
2353 SmallPtrSet<SDNode*, 2> Copies;
2354 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2356 if (UI->getOpcode() != ISD::CopyToReg)
2360 if (Copies.size() > 2)
2363 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2365 SDValue UseChain = UI->getOperand(0);
2366 if (Copies.count(UseChain.getNode()))
2370 // We are at the top of this chain.
2371 // If the copy has a glue operand, we conservatively assume it
2372 // isn't safe to perform a tail call.
2373 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2379 } else if (Copy->getOpcode() == ISD::BITCAST) {
2380 // f32 returned in a single GPR.
2381 if (!Copy->hasOneUse())
2383 Copy = *Copy->use_begin();
2384 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2386 // If the copy has a glue operand, we conservatively assume it isn't safe to
2387 // perform a tail call.
2388 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2390 TCChain = Copy->getOperand(0);
2395 bool HasRet = false;
2396 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2398 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2399 UI->getOpcode() != ARMISD::INTRET_FLAG)
2411 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2412 if (!Subtarget->supportsTailCall())
2416 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2417 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2420 return !Subtarget->isThumb1Only();
2423 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2424 // and pass the lower and high parts through.
2425 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2427 SDValue WriteValue = Op->getOperand(2);
2429 // This function is only supposed to be called for i64 type argument.
2430 assert(WriteValue.getValueType() == MVT::i64
2431 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2433 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2434 DAG.getConstant(0, DL, MVT::i32));
2435 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2436 DAG.getConstant(1, DL, MVT::i32));
2437 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2438 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2441 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2442 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2443 // one of the above mentioned nodes. It has to be wrapped because otherwise
2444 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2445 // be used to form addressing mode. These wrapped nodes will be selected
2447 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2448 EVT PtrVT = Op.getValueType();
2449 // FIXME there is no actual debug info here
2451 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2453 if (CP->isMachineConstantPoolEntry())
2454 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2455 CP->getAlignment());
2457 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2458 CP->getAlignment());
2459 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2462 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2463 return MachineJumpTableInfo::EK_Inline;
2466 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2467 SelectionDAG &DAG) const {
2468 MachineFunction &MF = DAG.getMachineFunction();
2469 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2470 unsigned ARMPCLabelIndex = 0;
2472 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2473 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2474 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2476 if (RelocM == Reloc::Static) {
2477 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2479 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2480 ARMPCLabelIndex = AFI->createPICLabelUId();
2481 ARMConstantPoolValue *CPV =
2482 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2483 ARMCP::CPBlockAddress, PCAdj);
2484 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2486 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2487 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2488 MachinePointerInfo::getConstantPool(),
2489 false, false, false, 0);
2490 if (RelocM == Reloc::Static)
2492 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2493 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2496 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2498 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2499 SelectionDAG &DAG) const {
2501 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2502 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2503 MachineFunction &MF = DAG.getMachineFunction();
2504 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2505 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2506 ARMConstantPoolValue *CPV =
2507 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2508 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2509 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2510 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2511 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2512 MachinePointerInfo::getConstantPool(),
2513 false, false, false, 0);
2514 SDValue Chain = Argument.getValue(1);
2516 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2517 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2519 // call __tls_get_addr.
2522 Entry.Node = Argument;
2523 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2524 Args.push_back(Entry);
2526 // FIXME: is there useful debug info available here?
2527 TargetLowering::CallLoweringInfo CLI(DAG);
2528 CLI.setDebugLoc(dl).setChain(Chain)
2529 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2530 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2533 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2534 return CallResult.first;
2537 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2538 // "local exec" model.
2540 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2542 TLSModel::Model model) const {
2543 const GlobalValue *GV = GA->getGlobal();
2546 SDValue Chain = DAG.getEntryNode();
2547 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2548 // Get the Thread Pointer
2549 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2551 if (model == TLSModel::InitialExec) {
2552 MachineFunction &MF = DAG.getMachineFunction();
2553 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2554 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2555 // Initial exec model.
2556 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2557 ARMConstantPoolValue *CPV =
2558 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2559 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2561 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2562 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2563 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2564 MachinePointerInfo::getConstantPool(),
2565 false, false, false, 0);
2566 Chain = Offset.getValue(1);
2568 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2569 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2571 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2572 MachinePointerInfo::getConstantPool(),
2573 false, false, false, 0);
2576 assert(model == TLSModel::LocalExec);
2577 ARMConstantPoolValue *CPV =
2578 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2579 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2580 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2581 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2582 MachinePointerInfo::getConstantPool(),
2583 false, false, false, 0);
2586 // The address of the thread local variable is the add of the thread
2587 // pointer with the offset of the variable.
2588 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2592 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2593 // TODO: implement the "local dynamic" model
2594 assert(Subtarget->isTargetELF() &&
2595 "TLS not implemented for non-ELF targets");
2596 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2597 if (DAG.getTarget().Options.EmulatedTLS)
2598 return LowerToTLSEmulatedModel(GA, DAG);
2600 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2603 case TLSModel::GeneralDynamic:
2604 case TLSModel::LocalDynamic:
2605 return LowerToTLSGeneralDynamicModel(GA, DAG);
2606 case TLSModel::InitialExec:
2607 case TLSModel::LocalExec:
2608 return LowerToTLSExecModels(GA, DAG, model);
2610 llvm_unreachable("bogus TLS model");
2613 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2614 SelectionDAG &DAG) const {
2615 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2617 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2618 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2619 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2620 ARMConstantPoolValue *CPV =
2621 ARMConstantPoolConstant::Create(GV,
2622 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2623 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2624 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2625 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2627 MachinePointerInfo::getConstantPool(),
2628 false, false, false, 0);
2629 SDValue Chain = Result.getValue(1);
2630 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2631 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2633 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2634 MachinePointerInfo::getGOT(),
2635 false, false, false, 0);
2639 // If we have T2 ops, we can materialize the address directly via movt/movw
2640 // pair. This is always cheaper.
2641 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2643 // FIXME: Once remat is capable of dealing with instructions with register
2644 // operands, expand this into two nodes.
2645 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2646 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2648 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2649 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2650 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2651 MachinePointerInfo::getConstantPool(),
2652 false, false, false, 0);
2656 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2657 SelectionDAG &DAG) const {
2658 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2660 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2661 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2663 if (Subtarget->useMovt(DAG.getMachineFunction()))
2666 // FIXME: Once remat is capable of dealing with instructions with register
2667 // operands, expand this into multiple nodes
2669 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2671 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2672 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2674 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2675 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2676 MachinePointerInfo::getGOT(), false, false, false, 0);
2680 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2681 SelectionDAG &DAG) const {
2682 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2683 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2684 "Windows on ARM expects to use movw/movt");
2686 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2687 const ARMII::TOF TargetFlags =
2688 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2689 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2695 // FIXME: Once remat is capable of dealing with instructions with register
2696 // operands, expand this into two nodes.
2697 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2698 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2700 if (GV->hasDLLImportStorageClass())
2701 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2702 MachinePointerInfo::getGOT(), false, false, false, 0);
2706 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2707 SelectionDAG &DAG) const {
2708 assert(Subtarget->isTargetELF() &&
2709 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2710 MachineFunction &MF = DAG.getMachineFunction();
2711 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2712 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2713 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2715 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2716 ARMConstantPoolValue *CPV =
2717 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2718 ARMPCLabelIndex, PCAdj);
2719 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2720 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2721 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2722 MachinePointerInfo::getConstantPool(),
2723 false, false, false, 0);
2724 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2725 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2729 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2731 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2732 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2733 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2734 Op.getOperand(1), Val);
2738 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2740 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2741 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2744 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2745 SelectionDAG &DAG) const {
2747 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2752 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2753 const ARMSubtarget *Subtarget) const {
2754 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2757 default: return SDValue(); // Don't custom lower most intrinsics.
2758 case Intrinsic::arm_rbit: {
2759 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2760 "RBIT intrinsic must have i32 type!");
2761 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2763 case Intrinsic::arm_thread_pointer: {
2764 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2765 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2767 case Intrinsic::eh_sjlj_lsda: {
2768 MachineFunction &MF = DAG.getMachineFunction();
2769 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2770 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2771 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2772 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2774 unsigned PCAdj = (RelocM != Reloc::PIC_)
2775 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2776 ARMConstantPoolValue *CPV =
2777 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2778 ARMCP::CPLSDA, PCAdj);
2779 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2780 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2782 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2783 MachinePointerInfo::getConstantPool(),
2784 false, false, false, 0);
2786 if (RelocM == Reloc::PIC_) {
2787 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2788 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2792 case Intrinsic::arm_neon_vmulls:
2793 case Intrinsic::arm_neon_vmullu: {
2794 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2795 ? ARMISD::VMULLs : ARMISD::VMULLu;
2796 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2797 Op.getOperand(1), Op.getOperand(2));
2799 case Intrinsic::arm_neon_vminnm:
2800 case Intrinsic::arm_neon_vmaxnm: {
2801 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2802 ? ISD::FMINNUM : ISD::FMAXNUM;
2803 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2804 Op.getOperand(1), Op.getOperand(2));
2809 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2810 const ARMSubtarget *Subtarget) {
2811 // FIXME: handle "fence singlethread" more efficiently.
2813 if (!Subtarget->hasDataBarrier()) {
2814 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2815 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2817 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2818 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2819 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2820 DAG.getConstant(0, dl, MVT::i32));
2823 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2824 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2825 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2826 if (Subtarget->isMClass()) {
2827 // Only a full system barrier exists in the M-class architectures.
2828 Domain = ARM_MB::SY;
2829 } else if (Subtarget->isSwift() && Ord == Release) {
2830 // Swift happens to implement ISHST barriers in a way that's compatible with
2831 // Release semantics but weaker than ISH so we'd be fools not to use
2832 // it. Beware: other processors probably don't!
2833 Domain = ARM_MB::ISHST;
2836 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2837 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2838 DAG.getConstant(Domain, dl, MVT::i32));
2841 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2842 const ARMSubtarget *Subtarget) {
2843 // ARM pre v5TE and Thumb1 does not have preload instructions.
2844 if (!(Subtarget->isThumb2() ||
2845 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2846 // Just preserve the chain.
2847 return Op.getOperand(0);
2850 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2852 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2853 // ARMv7 with MP extension has PLDW.
2854 return Op.getOperand(0);
2856 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2857 if (Subtarget->isThumb()) {
2859 isRead = ~isRead & 1;
2860 isData = ~isData & 1;
2863 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2864 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2865 DAG.getConstant(isData, dl, MVT::i32));
2868 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2869 MachineFunction &MF = DAG.getMachineFunction();
2870 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2872 // vastart just stores the address of the VarArgsFrameIndex slot into the
2873 // memory location argument.
2875 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2876 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2877 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2878 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2879 MachinePointerInfo(SV), false, false, 0);
2883 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2884 SDValue &Root, SelectionDAG &DAG,
2886 MachineFunction &MF = DAG.getMachineFunction();
2887 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2889 const TargetRegisterClass *RC;
2890 if (AFI->isThumb1OnlyFunction())
2891 RC = &ARM::tGPRRegClass;
2893 RC = &ARM::GPRRegClass;
2895 // Transform the arguments stored in physical registers into virtual ones.
2896 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2897 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2900 if (NextVA.isMemLoc()) {
2901 MachineFrameInfo *MFI = MF.getFrameInfo();
2902 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2904 // Create load node to retrieve arguments from the stack.
2905 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2906 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2907 MachinePointerInfo::getFixedStack(FI),
2908 false, false, false, 0);
2910 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2911 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2913 if (!Subtarget->isLittle())
2914 std::swap (ArgValue, ArgValue2);
2915 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2918 // The remaining GPRs hold either the beginning of variable-argument
2919 // data, or the beginning of an aggregate passed by value (usually
2920 // byval). Either way, we allocate stack slots adjacent to the data
2921 // provided by our caller, and store the unallocated registers there.
2922 // If this is a variadic function, the va_list pointer will begin with
2923 // these values; otherwise, this reassembles a (byval) structure that
2924 // was split between registers and memory.
2925 // Return: The frame index registers were stored into.
2927 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2928 SDLoc dl, SDValue &Chain,
2929 const Value *OrigArg,
2930 unsigned InRegsParamRecordIdx,
2932 unsigned ArgSize) const {
2933 // Currently, two use-cases possible:
2934 // Case #1. Non-var-args function, and we meet first byval parameter.
2935 // Setup first unallocated register as first byval register;
2936 // eat all remained registers
2937 // (these two actions are performed by HandleByVal method).
2938 // Then, here, we initialize stack frame with
2939 // "store-reg" instructions.
2940 // Case #2. Var-args function, that doesn't contain byval parameters.
2941 // The same: eat all remained unallocated registers,
2942 // initialize stack frame.
2944 MachineFunction &MF = DAG.getMachineFunction();
2945 MachineFrameInfo *MFI = MF.getFrameInfo();
2946 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2947 unsigned RBegin, REnd;
2948 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2949 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2951 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2952 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2957 ArgOffset = -4 * (ARM::R4 - RBegin);
2959 auto PtrVT = getPointerTy(DAG.getDataLayout());
2960 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2961 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2963 SmallVector<SDValue, 4> MemOps;
2964 const TargetRegisterClass *RC =
2965 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2967 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2968 unsigned VReg = MF.addLiveIn(Reg, RC);
2969 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2971 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2972 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2973 MemOps.push_back(Store);
2974 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2977 if (!MemOps.empty())
2978 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2982 // Setup stack frame, the va_list pointer will start from.
2984 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2985 SDLoc dl, SDValue &Chain,
2987 unsigned TotalArgRegsSaveSize,
2988 bool ForceMutable) const {
2989 MachineFunction &MF = DAG.getMachineFunction();
2990 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2992 // Try to store any remaining integer argument regs
2993 // to their spots on the stack so that they may be loaded by deferencing
2994 // the result of va_next.
2995 // If there is no regs to be stored, just point address after last
2996 // argument passed via stack.
2997 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2998 CCInfo.getInRegsParamsCount(),
2999 CCInfo.getNextStackOffset(), 4);
3000 AFI->setVarArgsFrameIndex(FrameIndex);
3004 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3005 CallingConv::ID CallConv, bool isVarArg,
3006 const SmallVectorImpl<ISD::InputArg>
3008 SDLoc dl, SelectionDAG &DAG,
3009 SmallVectorImpl<SDValue> &InVals)
3011 MachineFunction &MF = DAG.getMachineFunction();
3012 MachineFrameInfo *MFI = MF.getFrameInfo();
3014 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3016 // Assign locations to all of the incoming arguments.
3017 SmallVector<CCValAssign, 16> ArgLocs;
3018 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3019 *DAG.getContext(), Prologue);
3020 CCInfo.AnalyzeFormalArguments(Ins,
3021 CCAssignFnForNode(CallConv, /* Return*/ false,
3024 SmallVector<SDValue, 16> ArgValues;
3026 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3027 unsigned CurArgIdx = 0;
3029 // Initially ArgRegsSaveSize is zero.
3030 // Then we increase this value each time we meet byval parameter.
3031 // We also increase this value in case of varargs function.
3032 AFI->setArgRegsSaveSize(0);
3034 // Calculate the amount of stack space that we need to allocate to store
3035 // byval and variadic arguments that are passed in registers.
3036 // We need to know this before we allocate the first byval or variadic
3037 // argument, as they will be allocated a stack slot below the CFA (Canonical
3038 // Frame Address, the stack pointer at entry to the function).
3039 unsigned ArgRegBegin = ARM::R4;
3040 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3041 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3044 CCValAssign &VA = ArgLocs[i];
3045 unsigned Index = VA.getValNo();
3046 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3047 if (!Flags.isByVal())
3050 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3051 unsigned RBegin, REnd;
3052 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3053 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3055 CCInfo.nextInRegsParam();
3057 CCInfo.rewindByValRegsInfo();
3059 int lastInsIndex = -1;
3060 if (isVarArg && MFI->hasVAStart()) {
3061 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3062 if (RegIdx != array_lengthof(GPRArgRegs))
3063 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3066 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3067 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3068 auto PtrVT = getPointerTy(DAG.getDataLayout());
3070 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3071 CCValAssign &VA = ArgLocs[i];
3072 if (Ins[VA.getValNo()].isOrigArg()) {
3073 std::advance(CurOrigArg,
3074 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3075 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3077 // Arguments stored in registers.
3078 if (VA.isRegLoc()) {
3079 EVT RegVT = VA.getLocVT();
3081 if (VA.needsCustom()) {
3082 // f64 and vector types are split up into multiple registers or
3083 // combinations of registers and stack slots.
3084 if (VA.getLocVT() == MVT::v2f64) {
3085 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3087 VA = ArgLocs[++i]; // skip ahead to next loc
3089 if (VA.isMemLoc()) {
3090 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3091 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3092 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3093 MachinePointerInfo::getFixedStack(FI),
3094 false, false, false, 0);
3096 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3099 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3100 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3101 ArgValue, ArgValue1,
3102 DAG.getIntPtrConstant(0, dl));
3103 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3104 ArgValue, ArgValue2,
3105 DAG.getIntPtrConstant(1, dl));
3107 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3110 const TargetRegisterClass *RC;
3112 if (RegVT == MVT::f32)
3113 RC = &ARM::SPRRegClass;
3114 else if (RegVT == MVT::f64)
3115 RC = &ARM::DPRRegClass;
3116 else if (RegVT == MVT::v2f64)
3117 RC = &ARM::QPRRegClass;
3118 else if (RegVT == MVT::i32)
3119 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3120 : &ARM::GPRRegClass;
3122 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3124 // Transform the arguments in physical registers into virtual ones.
3125 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3126 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3129 // If this is an 8 or 16-bit value, it is really passed promoted
3130 // to 32 bits. Insert an assert[sz]ext to capture this, then
3131 // truncate to the right size.
3132 switch (VA.getLocInfo()) {
3133 default: llvm_unreachable("Unknown loc info!");
3134 case CCValAssign::Full: break;
3135 case CCValAssign::BCvt:
3136 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3138 case CCValAssign::SExt:
3139 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3140 DAG.getValueType(VA.getValVT()));
3141 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3143 case CCValAssign::ZExt:
3144 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3145 DAG.getValueType(VA.getValVT()));
3146 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3150 InVals.push_back(ArgValue);
3152 } else { // VA.isRegLoc()
3155 assert(VA.isMemLoc());
3156 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3158 int index = VA.getValNo();
3160 // Some Ins[] entries become multiple ArgLoc[] entries.
3161 // Process them only once.
3162 if (index != lastInsIndex)
3164 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3165 // FIXME: For now, all byval parameter objects are marked mutable.
3166 // This can be changed with more analysis.
3167 // In case of tail call optimization mark all arguments mutable.
3168 // Since they could be overwritten by lowering of arguments in case of
3170 if (Flags.isByVal()) {
3171 assert(Ins[index].isOrigArg() &&
3172 "Byval arguments cannot be implicit");
3173 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3175 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3176 CurByValIndex, VA.getLocMemOffset(),
3177 Flags.getByValSize());
3178 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3179 CCInfo.nextInRegsParam();
3181 unsigned FIOffset = VA.getLocMemOffset();
3182 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3185 // Create load nodes to retrieve arguments from the stack.
3186 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3187 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3188 MachinePointerInfo::getFixedStack(FI),
3189 false, false, false, 0));
3191 lastInsIndex = index;
3197 if (isVarArg && MFI->hasVAStart())
3198 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3199 CCInfo.getNextStackOffset(),
3200 TotalArgRegsSaveSize);
3202 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3207 /// isFloatingPointZero - Return true if this is +0.0.
3208 static bool isFloatingPointZero(SDValue Op) {
3209 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3210 return CFP->getValueAPF().isPosZero();
3211 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3212 // Maybe this has already been legalized into the constant pool?
3213 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3214 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3215 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3216 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3217 return CFP->getValueAPF().isPosZero();
3219 } else if (Op->getOpcode() == ISD::BITCAST &&
3220 Op->getValueType(0) == MVT::f64) {
3221 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3222 // created by LowerConstantFP().
3223 SDValue BitcastOp = Op->getOperand(0);
3224 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3225 SDValue MoveOp = BitcastOp->getOperand(0);
3226 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3227 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3235 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3236 /// the given operands.
3238 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3239 SDValue &ARMcc, SelectionDAG &DAG,
3241 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3242 unsigned C = RHSC->getZExtValue();
3243 if (!isLegalICmpImmediate(C)) {
3244 // Constant does not fit, try adjusting it by one?
3249 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3250 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3251 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3256 if (C != 0 && isLegalICmpImmediate(C-1)) {
3257 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3258 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3263 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3264 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3265 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3270 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3271 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3272 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3279 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3280 ARMISD::NodeType CompareType;
3283 CompareType = ARMISD::CMP;
3288 CompareType = ARMISD::CMPZ;
3291 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3292 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3295 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3297 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3299 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3301 if (!isFloatingPointZero(RHS))
3302 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3304 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3305 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3308 /// duplicateCmp - Glue values can have only one use, so this function
3309 /// duplicates a comparison node.
3311 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3312 unsigned Opc = Cmp.getOpcode();
3314 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3315 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3317 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3318 Cmp = Cmp.getOperand(0);
3319 Opc = Cmp.getOpcode();
3320 if (Opc == ARMISD::CMPFP)
3321 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3323 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3324 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3326 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3329 std::pair<SDValue, SDValue>
3330 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3331 SDValue &ARMcc) const {
3332 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3334 SDValue Value, OverflowCmp;
3335 SDValue LHS = Op.getOperand(0);
3336 SDValue RHS = Op.getOperand(1);
3339 // FIXME: We are currently always generating CMPs because we don't support
3340 // generating CMN through the backend. This is not as good as the natural
3341 // CMP case because it causes a register dependency and cannot be folded
3344 switch (Op.getOpcode()) {
3346 llvm_unreachable("Unknown overflow instruction!");
3348 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3349 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3350 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3353 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3354 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3355 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3358 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3359 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3360 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3363 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3364 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3365 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3369 return std::make_pair(Value, OverflowCmp);
3374 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3375 // Let legalize expand this if it isn't a legal type yet.
3376 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3379 SDValue Value, OverflowCmp;
3381 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3382 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3384 // We use 0 and 1 as false and true values.
3385 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3386 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3387 EVT VT = Op.getValueType();
3389 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3390 ARMcc, CCR, OverflowCmp);
3392 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3393 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3397 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3398 SDValue Cond = Op.getOperand(0);
3399 SDValue SelectTrue = Op.getOperand(1);
3400 SDValue SelectFalse = Op.getOperand(2);
3402 unsigned Opc = Cond.getOpcode();
3404 if (Cond.getResNo() == 1 &&
3405 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3406 Opc == ISD::USUBO)) {
3407 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3410 SDValue Value, OverflowCmp;
3412 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3413 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3414 EVT VT = Op.getValueType();
3416 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3422 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3423 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3425 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3426 const ConstantSDNode *CMOVTrue =
3427 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3428 const ConstantSDNode *CMOVFalse =
3429 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3431 if (CMOVTrue && CMOVFalse) {
3432 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3433 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3437 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3439 False = SelectFalse;
3440 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3445 if (True.getNode() && False.getNode()) {
3446 EVT VT = Op.getValueType();
3447 SDValue ARMcc = Cond.getOperand(2);
3448 SDValue CCR = Cond.getOperand(3);
3449 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3450 assert(True.getValueType() == VT);
3451 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3456 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3457 // undefined bits before doing a full-word comparison with zero.
3458 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3459 DAG.getConstant(1, dl, Cond.getValueType()));
3461 return DAG.getSelectCC(dl, Cond,
3462 DAG.getConstant(0, dl, Cond.getValueType()),
3463 SelectTrue, SelectFalse, ISD::SETNE);
3466 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3467 bool &swpCmpOps, bool &swpVselOps) {
3468 // Start by selecting the GE condition code for opcodes that return true for
3470 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3472 CondCode = ARMCC::GE;
3474 // and GT for opcodes that return false for 'equality'.
3475 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3477 CondCode = ARMCC::GT;
3479 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3480 // to swap the compare operands.
3481 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3485 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3486 // If we have an unordered opcode, we need to swap the operands to the VSEL
3487 // instruction (effectively negating the condition).
3489 // This also has the effect of swapping which one of 'less' or 'greater'
3490 // returns true, so we also swap the compare operands. It also switches
3491 // whether we return true for 'equality', so we compensate by picking the
3492 // opposite condition code to our original choice.
3493 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3494 CC == ISD::SETUGT) {
3495 swpCmpOps = !swpCmpOps;
3496 swpVselOps = !swpVselOps;
3497 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3500 // 'ordered' is 'anything but unordered', so use the VS condition code and
3501 // swap the VSEL operands.
3502 if (CC == ISD::SETO) {
3503 CondCode = ARMCC::VS;
3507 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3508 // code and swap the VSEL operands.
3509 if (CC == ISD::SETUNE) {
3510 CondCode = ARMCC::EQ;
3515 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3516 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3517 SDValue Cmp, SelectionDAG &DAG) const {
3518 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3519 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3520 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3521 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3522 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3524 SDValue TrueLow = TrueVal.getValue(0);
3525 SDValue TrueHigh = TrueVal.getValue(1);
3526 SDValue FalseLow = FalseVal.getValue(0);
3527 SDValue FalseHigh = FalseVal.getValue(1);
3529 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3531 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3532 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3534 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3536 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3541 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3542 EVT VT = Op.getValueType();
3543 SDValue LHS = Op.getOperand(0);
3544 SDValue RHS = Op.getOperand(1);
3545 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3546 SDValue TrueVal = Op.getOperand(2);
3547 SDValue FalseVal = Op.getOperand(3);
3550 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3551 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3554 // If softenSetCCOperands only returned one value, we should compare it to
3556 if (!RHS.getNode()) {
3557 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3562 if (LHS.getValueType() == MVT::i32) {
3563 // Try to generate VSEL on ARMv8.
3564 // The VSEL instruction can't use all the usual ARM condition
3565 // codes: it only has two bits to select the condition code, so it's
3566 // constrained to use only GE, GT, VS and EQ.
3568 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3569 // swap the operands of the previous compare instruction (effectively
3570 // inverting the compare condition, swapping 'less' and 'greater') and
3571 // sometimes need to swap the operands to the VSEL (which inverts the
3572 // condition in the sense of firing whenever the previous condition didn't)
3573 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3574 TrueVal.getValueType() == MVT::f64)) {
3575 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3576 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3577 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3578 CC = ISD::getSetCCInverse(CC, true);
3579 std::swap(TrueVal, FalseVal);
3584 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3585 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3586 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3589 ARMCC::CondCodes CondCode, CondCode2;
3590 FPCCToARMCC(CC, CondCode, CondCode2);
3592 // Try to generate VMAXNM/VMINNM on ARMv8.
3593 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3594 TrueVal.getValueType() == MVT::f64)) {
3595 // We can use VMAXNM/VMINNM for a compare followed by a select with the
3596 // same operands, as follows:
3597 // c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3599 // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3600 bool swapSides = false;
3601 if (!getTargetMachine().Options.NoNaNsFPMath) {
3602 // transformability may depend on which way around we compare
3610 // the non-NaN should be RHS
3611 swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3617 // the non-NaN should be LHS
3618 swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3622 swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3624 CC = ISD::getSetCCSwappedOperands(CC);
3625 std::swap(LHS, RHS);
3627 if (LHS == TrueVal && RHS == FalseVal) {
3628 bool canTransform = true;
3629 // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3630 if (!getTargetMachine().Options.UnsafeFPMath &&
3631 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3632 const ConstantFPSDNode *Zero;
3639 // RHS must not be -0
3640 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3641 !Zero->isNegative();
3646 // LHS must not be -0
3647 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3648 !Zero->isNegative();
3653 // RHS must not be +0
3654 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3660 // LHS must not be +0
3661 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3667 // Note: If one of the elements in a pair is a number and the other
3668 // element is NaN, the corresponding result element is the number.
3669 // This is consistent with the IEEE 754-2008 standard.
3670 // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3676 if (!DAG.isKnownNeverNaN(RHS))
3678 return DAG.getNode(ISD::FMAXNUM, dl, VT, LHS, RHS);
3681 if (!DAG.isKnownNeverNaN(LHS))
3685 return DAG.getNode(ISD::FMAXNUM, dl, VT, LHS, RHS);
3688 if (!DAG.isKnownNeverNaN(RHS))
3690 return DAG.getNode(ISD::FMINNUM, dl, VT, LHS, RHS);
3693 if (!DAG.isKnownNeverNaN(LHS))
3697 return DAG.getNode(ISD::FMINNUM, dl, VT, LHS, RHS);
3702 bool swpCmpOps = false;
3703 bool swpVselOps = false;
3704 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3706 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3707 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3709 std::swap(LHS, RHS);
3711 std::swap(TrueVal, FalseVal);
3715 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3716 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3717 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3718 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3719 if (CondCode2 != ARMCC::AL) {
3720 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3721 // FIXME: Needs another CMP because flag can have but one use.
3722 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3723 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3728 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3729 /// to morph to an integer compare sequence.
3730 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3731 const ARMSubtarget *Subtarget) {
3732 SDNode *N = Op.getNode();
3733 if (!N->hasOneUse())
3734 // Otherwise it requires moving the value from fp to integer registers.
3736 if (!N->getNumValues())
3738 EVT VT = Op.getValueType();
3739 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3740 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3741 // vmrs are very slow, e.g. cortex-a8.
3744 if (isFloatingPointZero(Op)) {
3748 return ISD::isNormalLoad(N);
3751 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3752 if (isFloatingPointZero(Op))
3753 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3755 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3756 return DAG.getLoad(MVT::i32, SDLoc(Op),
3757 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3758 Ld->isVolatile(), Ld->isNonTemporal(),
3759 Ld->isInvariant(), Ld->getAlignment());
3761 llvm_unreachable("Unknown VFP cmp argument!");
3764 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3765 SDValue &RetVal1, SDValue &RetVal2) {
3768 if (isFloatingPointZero(Op)) {
3769 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3770 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3774 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3775 SDValue Ptr = Ld->getBasePtr();
3776 RetVal1 = DAG.getLoad(MVT::i32, dl,
3777 Ld->getChain(), Ptr,
3778 Ld->getPointerInfo(),
3779 Ld->isVolatile(), Ld->isNonTemporal(),
3780 Ld->isInvariant(), Ld->getAlignment());
3782 EVT PtrType = Ptr.getValueType();
3783 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3784 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3785 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3786 RetVal2 = DAG.getLoad(MVT::i32, dl,
3787 Ld->getChain(), NewPtr,
3788 Ld->getPointerInfo().getWithOffset(4),
3789 Ld->isVolatile(), Ld->isNonTemporal(),
3790 Ld->isInvariant(), NewAlign);
3794 llvm_unreachable("Unknown VFP cmp argument!");
3797 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3798 /// f32 and even f64 comparisons to integer ones.
3800 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3801 SDValue Chain = Op.getOperand(0);
3802 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3803 SDValue LHS = Op.getOperand(2);
3804 SDValue RHS = Op.getOperand(3);
3805 SDValue Dest = Op.getOperand(4);
3808 bool LHSSeenZero = false;
3809 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3810 bool RHSSeenZero = false;
3811 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3812 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3813 // If unsafe fp math optimization is enabled and there are no other uses of
3814 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3815 // to an integer comparison.
3816 if (CC == ISD::SETOEQ)
3818 else if (CC == ISD::SETUNE)
3821 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3823 if (LHS.getValueType() == MVT::f32) {
3824 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3825 bitcastf32Toi32(LHS, DAG), Mask);
3826 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3827 bitcastf32Toi32(RHS, DAG), Mask);
3828 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3829 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3830 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3831 Chain, Dest, ARMcc, CCR, Cmp);
3836 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3837 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3838 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3839 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3840 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3841 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3842 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3843 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3844 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3850 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3851 SDValue Chain = Op.getOperand(0);
3852 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3853 SDValue LHS = Op.getOperand(2);
3854 SDValue RHS = Op.getOperand(3);
3855 SDValue Dest = Op.getOperand(4);
3858 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3859 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3862 // If softenSetCCOperands only returned one value, we should compare it to
3864 if (!RHS.getNode()) {
3865 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3870 if (LHS.getValueType() == MVT::i32) {
3872 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3873 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3874 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3875 Chain, Dest, ARMcc, CCR, Cmp);
3878 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3880 if (getTargetMachine().Options.UnsafeFPMath &&
3881 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3882 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3883 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3884 if (Result.getNode())
3888 ARMCC::CondCodes CondCode, CondCode2;
3889 FPCCToARMCC(CC, CondCode, CondCode2);
3891 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3892 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3893 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3894 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3895 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3896 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3897 if (CondCode2 != ARMCC::AL) {
3898 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3899 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3900 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3905 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3906 SDValue Chain = Op.getOperand(0);
3907 SDValue Table = Op.getOperand(1);
3908 SDValue Index = Op.getOperand(2);
3911 EVT PTy = getPointerTy(DAG.getDataLayout());
3912 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3913 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3914 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3915 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3916 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3917 if (Subtarget->isThumb2()) {
3918 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3919 // which does another jump to the destination. This also makes it easier
3920 // to translate it to TBB / TBH later.
3921 // FIXME: This might not work if the function is extremely large.
3922 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3923 Addr, Op.getOperand(2), JTI);
3925 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3926 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3927 MachinePointerInfo::getJumpTable(),
3928 false, false, false, 0);
3929 Chain = Addr.getValue(1);
3930 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3931 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3933 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3934 MachinePointerInfo::getJumpTable(),
3935 false, false, false, 0);
3936 Chain = Addr.getValue(1);
3937 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3941 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3942 EVT VT = Op.getValueType();
3945 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3946 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3948 return DAG.UnrollVectorOp(Op.getNode());
3951 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3952 "Invalid type for custom lowering!");
3953 if (VT != MVT::v4i16)
3954 return DAG.UnrollVectorOp(Op.getNode());
3956 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3957 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3960 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3961 EVT VT = Op.getValueType();
3963 return LowerVectorFP_TO_INT(Op, DAG);
3964 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3966 if (Op.getOpcode() == ISD::FP_TO_SINT)
3967 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3970 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3972 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3973 /*isSigned*/ false, SDLoc(Op)).first;
3979 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3980 EVT VT = Op.getValueType();
3983 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3984 if (VT.getVectorElementType() == MVT::f32)
3986 return DAG.UnrollVectorOp(Op.getNode());
3989 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3990 "Invalid type for custom lowering!");
3991 if (VT != MVT::v4f32)
3992 return DAG.UnrollVectorOp(Op.getNode());
3996 switch (Op.getOpcode()) {
3997 default: llvm_unreachable("Invalid opcode!");
3998 case ISD::SINT_TO_FP:
3999 CastOpc = ISD::SIGN_EXTEND;
4000 Opc = ISD::SINT_TO_FP;
4002 case ISD::UINT_TO_FP:
4003 CastOpc = ISD::ZERO_EXTEND;
4004 Opc = ISD::UINT_TO_FP;
4008 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4009 return DAG.getNode(Opc, dl, VT, Op);
4012 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4013 EVT VT = Op.getValueType();
4015 return LowerVectorINT_TO_FP(Op, DAG);
4016 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4018 if (Op.getOpcode() == ISD::SINT_TO_FP)
4019 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4022 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4024 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4025 /*isSigned*/ false, SDLoc(Op)).first;
4031 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4032 // Implement fcopysign with a fabs and a conditional fneg.
4033 SDValue Tmp0 = Op.getOperand(0);
4034 SDValue Tmp1 = Op.getOperand(1);
4036 EVT VT = Op.getValueType();
4037 EVT SrcVT = Tmp1.getValueType();
4038 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4039 Tmp0.getOpcode() == ARMISD::VMOVDRR;
4040 bool UseNEON = !InGPR && Subtarget->hasNEON();
4043 // Use VBSL to copy the sign bit.
4044 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4045 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4046 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4047 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4049 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4050 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4051 DAG.getConstant(32, dl, MVT::i32));
4052 else /*if (VT == MVT::f32)*/
4053 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4054 if (SrcVT == MVT::f32) {
4055 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4057 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4058 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4059 DAG.getConstant(32, dl, MVT::i32));
4060 } else if (VT == MVT::f32)
4061 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4062 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4063 DAG.getConstant(32, dl, MVT::i32));
4064 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4065 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4067 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4069 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4070 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4071 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4073 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4074 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4075 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4076 if (VT == MVT::f32) {
4077 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4078 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4079 DAG.getConstant(0, dl, MVT::i32));
4081 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4087 // Bitcast operand 1 to i32.
4088 if (SrcVT == MVT::f64)
4089 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4091 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4093 // Or in the signbit with integer operations.
4094 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4095 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4096 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4097 if (VT == MVT::f32) {
4098 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4099 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4100 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4101 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4104 // f64: Or the high part with signbit and then combine two parts.
4105 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4107 SDValue Lo = Tmp0.getValue(0);
4108 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4109 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4110 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4113 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4114 MachineFunction &MF = DAG.getMachineFunction();
4115 MachineFrameInfo *MFI = MF.getFrameInfo();
4116 MFI->setReturnAddressIsTaken(true);
4118 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4121 EVT VT = Op.getValueType();
4123 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4125 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4126 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4127 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4128 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4129 MachinePointerInfo(), false, false, false, 0);
4132 // Return LR, which contains the return address. Mark it an implicit live-in.
4133 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4134 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4137 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4138 const ARMBaseRegisterInfo &ARI =
4139 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4140 MachineFunction &MF = DAG.getMachineFunction();
4141 MachineFrameInfo *MFI = MF.getFrameInfo();
4142 MFI->setFrameAddressIsTaken(true);
4144 EVT VT = Op.getValueType();
4145 SDLoc dl(Op); // FIXME probably not meaningful
4146 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4147 unsigned FrameReg = ARI.getFrameRegister(MF);
4148 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4150 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4151 MachinePointerInfo(),
4152 false, false, false, 0);
4156 // FIXME? Maybe this could be a TableGen attribute on some registers and
4157 // this table could be generated automatically from RegInfo.
4158 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4159 SelectionDAG &DAG) const {
4160 unsigned Reg = StringSwitch<unsigned>(RegName)
4161 .Case("sp", ARM::SP)
4165 report_fatal_error(Twine("Invalid register name \""
4166 + StringRef(RegName) + "\"."));
4169 // Result is 64 bit value so split into two 32 bit values and return as a
4171 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4172 SelectionDAG &DAG) {
4175 // This function is only supposed to be called for i64 type destination.
4176 assert(N->getValueType(0) == MVT::i64
4177 && "ExpandREAD_REGISTER called for non-i64 type result.");
4179 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4180 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4184 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4186 Results.push_back(Read.getOperand(0));
4189 /// ExpandBITCAST - If the target supports VFP, this function is called to
4190 /// expand a bit convert where either the source or destination type is i64 to
4191 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4192 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4193 /// vectors), since the legalizer won't know what to do with that.
4194 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4195 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4197 SDValue Op = N->getOperand(0);
4199 // This function is only supposed to be called for i64 types, either as the
4200 // source or destination of the bit convert.
4201 EVT SrcVT = Op.getValueType();
4202 EVT DstVT = N->getValueType(0);
4203 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4204 "ExpandBITCAST called for non-i64 type");
4206 // Turn i64->f64 into VMOVDRR.
4207 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4208 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4209 DAG.getConstant(0, dl, MVT::i32));
4210 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4211 DAG.getConstant(1, dl, MVT::i32));
4212 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4213 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4216 // Turn f64->i64 into VMOVRRD.
4217 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4219 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4220 SrcVT.getVectorNumElements() > 1)
4221 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4222 DAG.getVTList(MVT::i32, MVT::i32),
4223 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4225 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4226 DAG.getVTList(MVT::i32, MVT::i32), Op);
4227 // Merge the pieces into a single i64 value.
4228 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4234 /// getZeroVector - Returns a vector of specified type with all zero elements.
4235 /// Zero vectors are used to represent vector negation and in those cases
4236 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4237 /// not support i64 elements, so sometimes the zero vectors will need to be
4238 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4240 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4241 assert(VT.isVector() && "Expected a vector type");
4242 // The canonical modified immediate encoding of a zero vector is....0!
4243 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4244 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4245 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4246 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4249 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4250 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4251 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4252 SelectionDAG &DAG) const {
4253 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4254 EVT VT = Op.getValueType();
4255 unsigned VTBits = VT.getSizeInBits();
4257 SDValue ShOpLo = Op.getOperand(0);
4258 SDValue ShOpHi = Op.getOperand(1);
4259 SDValue ShAmt = Op.getOperand(2);
4261 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4263 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4265 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4266 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4267 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4268 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4269 DAG.getConstant(VTBits, dl, MVT::i32));
4270 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4271 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4272 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4274 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4275 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4276 ISD::SETGE, ARMcc, DAG, dl);
4277 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4278 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4281 SDValue Ops[2] = { Lo, Hi };
4282 return DAG.getMergeValues(Ops, dl);
4285 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4286 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4287 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4288 SelectionDAG &DAG) const {
4289 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4290 EVT VT = Op.getValueType();
4291 unsigned VTBits = VT.getSizeInBits();
4293 SDValue ShOpLo = Op.getOperand(0);
4294 SDValue ShOpHi = Op.getOperand(1);
4295 SDValue ShAmt = Op.getOperand(2);
4298 assert(Op.getOpcode() == ISD::SHL_PARTS);
4299 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4300 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4301 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4302 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4303 DAG.getConstant(VTBits, dl, MVT::i32));
4304 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4305 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4307 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4308 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4309 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4310 ISD::SETGE, ARMcc, DAG, dl);
4311 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4312 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4315 SDValue Ops[2] = { Lo, Hi };
4316 return DAG.getMergeValues(Ops, dl);
4319 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4320 SelectionDAG &DAG) const {
4321 // The rounding mode is in bits 23:22 of the FPSCR.
4322 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4323 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4324 // so that the shift + and get folded into a bitfield extract.
4326 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4327 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4329 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4330 DAG.getConstant(1U << 22, dl, MVT::i32));
4331 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4332 DAG.getConstant(22, dl, MVT::i32));
4333 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4334 DAG.getConstant(3, dl, MVT::i32));
4337 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4338 const ARMSubtarget *ST) {
4340 EVT VT = N->getValueType(0);
4341 if (VT.isVector()) {
4342 assert(ST->hasNEON());
4344 // Compute the least significant set bit: LSB = X & -X
4345 SDValue X = N->getOperand(0);
4346 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4347 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4349 EVT ElemTy = VT.getVectorElementType();
4351 if (ElemTy == MVT::i8) {
4352 // Compute with: cttz(x) = ctpop(lsb - 1)
4353 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4354 DAG.getTargetConstant(1, dl, ElemTy));
4355 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4356 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4359 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4360 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4361 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4362 unsigned NumBits = ElemTy.getSizeInBits();
4363 SDValue WidthMinus1 =
4364 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4365 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4366 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4367 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4370 // Compute with: cttz(x) = ctpop(lsb - 1)
4372 // Since we can only compute the number of bits in a byte with vcnt.8, we
4373 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4378 if (ElemTy == MVT::i64) {
4379 // Load constant 0xffff'ffff'ffff'ffff to register.
4380 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4381 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4382 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4384 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4385 DAG.getTargetConstant(1, dl, ElemTy));
4386 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4389 // Count #bits with vcnt.8.
4390 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4391 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4392 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4394 // Gather the #bits with vpaddl (pairwise add.)
4395 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4396 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4397 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4399 if (ElemTy == MVT::i16)
4402 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4403 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4404 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4406 if (ElemTy == MVT::i32)
4409 assert(ElemTy == MVT::i64);
4410 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4411 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4416 if (!ST->hasV6T2Ops())
4419 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4420 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4423 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4424 /// for each 16-bit element from operand, repeated. The basic idea is to
4425 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4427 /// Trace for v4i16:
4428 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4429 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4430 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4431 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4432 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4433 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4434 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4435 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4436 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4437 EVT VT = N->getValueType(0);
4440 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4441 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4442 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4443 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4444 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4445 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4448 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4449 /// bit-count for each 16-bit element from the operand. We need slightly
4450 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4451 /// 64/128-bit registers.
4453 /// Trace for v4i16:
4454 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4455 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4456 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4457 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4458 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4459 EVT VT = N->getValueType(0);
4462 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4463 if (VT.is64BitVector()) {
4464 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4465 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4466 DAG.getIntPtrConstant(0, DL));
4468 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4469 BitCounts, DAG.getIntPtrConstant(0, DL));
4470 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4474 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4475 /// bit-count for each 32-bit element from the operand. The idea here is
4476 /// to split the vector into 16-bit elements, leverage the 16-bit count
4477 /// routine, and then combine the results.
4479 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4480 /// input = [v0 v1 ] (vi: 32-bit elements)
4481 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4482 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4483 /// vrev: N0 = [k1 k0 k3 k2 ]
4485 /// N1 =+[k1 k0 k3 k2 ]
4487 /// N2 =+[k1 k3 k0 k2 ]
4489 /// Extended =+[k1 k3 k0 k2 ]
4491 /// Extracted=+[k1 k3 ]
4493 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4494 EVT VT = N->getValueType(0);
4497 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4499 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4500 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4501 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4502 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4503 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4505 if (VT.is64BitVector()) {
4506 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4507 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4508 DAG.getIntPtrConstant(0, DL));
4510 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4511 DAG.getIntPtrConstant(0, DL));
4512 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4516 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4517 const ARMSubtarget *ST) {
4518 EVT VT = N->getValueType(0);
4520 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4521 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4522 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4523 "Unexpected type for custom ctpop lowering");
4525 if (VT.getVectorElementType() == MVT::i32)
4526 return lowerCTPOP32BitElements(N, DAG);
4528 return lowerCTPOP16BitElements(N, DAG);
4531 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4532 const ARMSubtarget *ST) {
4533 EVT VT = N->getValueType(0);
4539 // Lower vector shifts on NEON to use VSHL.
4540 assert(ST->hasNEON() && "unexpected vector shift");
4542 // Left shifts translate directly to the vshiftu intrinsic.
4543 if (N->getOpcode() == ISD::SHL)
4544 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4545 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4547 N->getOperand(0), N->getOperand(1));
4549 assert((N->getOpcode() == ISD::SRA ||
4550 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4552 // NEON uses the same intrinsics for both left and right shifts. For
4553 // right shifts, the shift amounts are negative, so negate the vector of
4555 EVT ShiftVT = N->getOperand(1).getValueType();
4556 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4557 getZeroVector(ShiftVT, DAG, dl),
4559 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4560 Intrinsic::arm_neon_vshifts :
4561 Intrinsic::arm_neon_vshiftu);
4562 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4563 DAG.getConstant(vshiftInt, dl, MVT::i32),
4564 N->getOperand(0), NegatedCount);
4567 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4568 const ARMSubtarget *ST) {
4569 EVT VT = N->getValueType(0);
4572 // We can get here for a node like i32 = ISD::SHL i32, i64
4576 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4577 "Unknown shift to lower!");
4579 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4580 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4581 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4584 // If we are in thumb mode, we don't have RRX.
4585 if (ST->isThumb1Only()) return SDValue();
4587 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4588 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4589 DAG.getConstant(0, dl, MVT::i32));
4590 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4591 DAG.getConstant(1, dl, MVT::i32));
4593 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4594 // captures the result into a carry flag.
4595 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4596 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4598 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4599 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4601 // Merge the pieces into a single i64 value.
4602 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4605 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4606 SDValue TmpOp0, TmpOp1;
4607 bool Invert = false;
4611 SDValue Op0 = Op.getOperand(0);
4612 SDValue Op1 = Op.getOperand(1);
4613 SDValue CC = Op.getOperand(2);
4614 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4615 EVT VT = Op.getValueType();
4616 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4619 if (Op1.getValueType().isFloatingPoint()) {
4620 switch (SetCCOpcode) {
4621 default: llvm_unreachable("Illegal FP comparison");
4623 case ISD::SETNE: Invert = true; // Fallthrough
4625 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4627 case ISD::SETLT: Swap = true; // Fallthrough
4629 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4631 case ISD::SETLE: Swap = true; // Fallthrough
4633 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4634 case ISD::SETUGE: Swap = true; // Fallthrough
4635 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4636 case ISD::SETUGT: Swap = true; // Fallthrough
4637 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4638 case ISD::SETUEQ: Invert = true; // Fallthrough
4640 // Expand this to (OLT | OGT).
4644 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4645 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4647 case ISD::SETUO: Invert = true; // Fallthrough
4649 // Expand this to (OLT | OGE).
4653 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4654 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4658 // Integer comparisons.
4659 switch (SetCCOpcode) {
4660 default: llvm_unreachable("Illegal integer comparison");
4661 case ISD::SETNE: Invert = true;
4662 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4663 case ISD::SETLT: Swap = true;
4664 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4665 case ISD::SETLE: Swap = true;
4666 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4667 case ISD::SETULT: Swap = true;
4668 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4669 case ISD::SETULE: Swap = true;
4670 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4673 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4674 if (Opc == ARMISD::VCEQ) {
4677 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4679 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4682 // Ignore bitconvert.
4683 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4684 AndOp = AndOp.getOperand(0);
4686 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4688 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4689 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4696 std::swap(Op0, Op1);
4698 // If one of the operands is a constant vector zero, attempt to fold the
4699 // comparison to a specialized compare-against-zero form.
4701 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4703 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4704 if (Opc == ARMISD::VCGE)
4705 Opc = ARMISD::VCLEZ;
4706 else if (Opc == ARMISD::VCGT)
4707 Opc = ARMISD::VCLTZ;
4712 if (SingleOp.getNode()) {
4715 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4717 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4719 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4721 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4723 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4725 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4728 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4731 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4734 Result = DAG.getNOT(dl, Result, VT);
4739 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4740 /// valid vector constant for a NEON instruction with a "modified immediate"
4741 /// operand (e.g., VMOV). If so, return the encoded value.
4742 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4743 unsigned SplatBitSize, SelectionDAG &DAG,
4744 SDLoc dl, EVT &VT, bool is128Bits,
4745 NEONModImmType type) {
4746 unsigned OpCmode, Imm;
4748 // SplatBitSize is set to the smallest size that splats the vector, so a
4749 // zero vector will always have SplatBitSize == 8. However, NEON modified
4750 // immediate instructions others than VMOV do not support the 8-bit encoding
4751 // of a zero vector, and the default encoding of zero is supposed to be the
4756 switch (SplatBitSize) {
4758 if (type != VMOVModImm)
4760 // Any 1-byte value is OK. Op=0, Cmode=1110.
4761 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4764 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4768 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4769 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4770 if ((SplatBits & ~0xff) == 0) {
4771 // Value = 0x00nn: Op=x, Cmode=100x.
4776 if ((SplatBits & ~0xff00) == 0) {
4777 // Value = 0xnn00: Op=x, Cmode=101x.
4779 Imm = SplatBits >> 8;
4785 // NEON's 32-bit VMOV supports splat values where:
4786 // * only one byte is nonzero, or
4787 // * the least significant byte is 0xff and the second byte is nonzero, or
4788 // * the least significant 2 bytes are 0xff and the third is nonzero.
4789 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4790 if ((SplatBits & ~0xff) == 0) {
4791 // Value = 0x000000nn: Op=x, Cmode=000x.
4796 if ((SplatBits & ~0xff00) == 0) {
4797 // Value = 0x0000nn00: Op=x, Cmode=001x.
4799 Imm = SplatBits >> 8;
4802 if ((SplatBits & ~0xff0000) == 0) {
4803 // Value = 0x00nn0000: Op=x, Cmode=010x.
4805 Imm = SplatBits >> 16;
4808 if ((SplatBits & ~0xff000000) == 0) {
4809 // Value = 0xnn000000: Op=x, Cmode=011x.
4811 Imm = SplatBits >> 24;
4815 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4816 if (type == OtherModImm) return SDValue();
4818 if ((SplatBits & ~0xffff) == 0 &&
4819 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4820 // Value = 0x0000nnff: Op=x, Cmode=1100.
4822 Imm = SplatBits >> 8;
4826 if ((SplatBits & ~0xffffff) == 0 &&
4827 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4828 // Value = 0x00nnffff: Op=x, Cmode=1101.
4830 Imm = SplatBits >> 16;
4834 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4835 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4836 // VMOV.I32. A (very) minor optimization would be to replicate the value
4837 // and fall through here to test for a valid 64-bit splat. But, then the
4838 // caller would also need to check and handle the change in size.
4842 if (type != VMOVModImm)
4844 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4845 uint64_t BitMask = 0xff;
4847 unsigned ImmMask = 1;
4849 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4850 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4853 } else if ((SplatBits & BitMask) != 0) {
4860 if (DAG.getDataLayout().isBigEndian())
4861 // swap higher and lower 32 bit word
4862 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4864 // Op=1, Cmode=1110.
4866 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4871 llvm_unreachable("unexpected size for isNEONModifiedImm");
4874 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4875 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4878 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4879 const ARMSubtarget *ST) const {
4883 bool IsDouble = Op.getValueType() == MVT::f64;
4884 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4886 // Use the default (constant pool) lowering for double constants when we have
4888 if (IsDouble && Subtarget->isFPOnlySP())
4891 // Try splatting with a VMOV.f32...
4892 APFloat FPVal = CFP->getValueAPF();
4893 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4896 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4897 // We have code in place to select a valid ConstantFP already, no need to
4902 // It's a float and we are trying to use NEON operations where
4903 // possible. Lower it to a splat followed by an extract.
4905 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4906 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4908 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4909 DAG.getConstant(0, DL, MVT::i32));
4912 // The rest of our options are NEON only, make sure that's allowed before
4914 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4918 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4920 // It wouldn't really be worth bothering for doubles except for one very
4921 // important value, which does happen to match: 0.0. So make sure we don't do
4923 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4926 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4927 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4928 VMovVT, false, VMOVModImm);
4929 if (NewVal != SDValue()) {
4931 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4934 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4936 // It's a float: cast and extract a vector element.
4937 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4939 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4940 DAG.getConstant(0, DL, MVT::i32));
4943 // Finally, try a VMVN.i32
4944 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4946 if (NewVal != SDValue()) {
4948 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4951 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4953 // It's a float: cast and extract a vector element.
4954 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4956 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4957 DAG.getConstant(0, DL, MVT::i32));
4963 // check if an VEXT instruction can handle the shuffle mask when the
4964 // vector sources of the shuffle are the same.
4965 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4966 unsigned NumElts = VT.getVectorNumElements();
4968 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4974 // If this is a VEXT shuffle, the immediate value is the index of the first
4975 // element. The other shuffle indices must be the successive elements after
4977 unsigned ExpectedElt = Imm;
4978 for (unsigned i = 1; i < NumElts; ++i) {
4979 // Increment the expected index. If it wraps around, just follow it
4980 // back to index zero and keep going.
4982 if (ExpectedElt == NumElts)
4985 if (M[i] < 0) continue; // ignore UNDEF indices
4986 if (ExpectedElt != static_cast<unsigned>(M[i]))
4994 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4995 bool &ReverseVEXT, unsigned &Imm) {
4996 unsigned NumElts = VT.getVectorNumElements();
4997 ReverseVEXT = false;
4999 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5005 // If this is a VEXT shuffle, the immediate value is the index of the first
5006 // element. The other shuffle indices must be the successive elements after
5008 unsigned ExpectedElt = Imm;
5009 for (unsigned i = 1; i < NumElts; ++i) {
5010 // Increment the expected index. If it wraps around, it may still be
5011 // a VEXT but the source vectors must be swapped.
5013 if (ExpectedElt == NumElts * 2) {
5018 if (M[i] < 0) continue; // ignore UNDEF indices
5019 if (ExpectedElt != static_cast<unsigned>(M[i]))
5023 // Adjust the index value if the source operands will be swapped.
5030 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5031 /// instruction with the specified blocksize. (The order of the elements
5032 /// within each block of the vector is reversed.)
5033 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5034 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5035 "Only possible block sizes for VREV are: 16, 32, 64");
5037 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5041 unsigned NumElts = VT.getVectorNumElements();
5042 unsigned BlockElts = M[0] + 1;
5043 // If the first shuffle index is UNDEF, be optimistic.
5045 BlockElts = BlockSize / EltSz;
5047 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5050 for (unsigned i = 0; i < NumElts; ++i) {
5051 if (M[i] < 0) continue; // ignore UNDEF indices
5052 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5059 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5060 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5061 // range, then 0 is placed into the resulting vector. So pretty much any mask
5062 // of 8 elements can work here.
5063 return VT == MVT::v8i8 && M.size() == 8;
5066 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5067 // checking that pairs of elements in the shuffle mask represent the same index
5068 // in each vector, incrementing the expected index by 2 at each step.
5069 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5070 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5072 // WhichResult gives the offset for each element in the mask based on which
5073 // of the two results it belongs to.
5075 // The transpose can be represented either as:
5076 // result1 = shufflevector v1, v2, result1_shuffle_mask
5077 // result2 = shufflevector v1, v2, result2_shuffle_mask
5078 // where v1/v2 and the shuffle masks have the same number of elements
5079 // (here WhichResult (see below) indicates which result is being checked)
5082 // results = shufflevector v1, v2, shuffle_mask
5083 // where both results are returned in one vector and the shuffle mask has twice
5084 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5085 // want to check the low half and high half of the shuffle mask as if it were
5087 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5088 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5092 unsigned NumElts = VT.getVectorNumElements();
5093 if (M.size() != NumElts && M.size() != NumElts*2)
5096 // If the mask is twice as long as the result then we need to check the upper
5097 // and lower parts of the mask
5098 for (unsigned i = 0; i < M.size(); i += NumElts) {
5099 WhichResult = M[i] == 0 ? 0 : 1;
5100 for (unsigned j = 0; j < NumElts; j += 2) {
5101 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5102 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5107 if (M.size() == NumElts*2)
5113 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5114 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5115 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5116 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5117 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5121 unsigned NumElts = VT.getVectorNumElements();
5122 if (M.size() != NumElts && M.size() != NumElts*2)
5125 for (unsigned i = 0; i < M.size(); i += NumElts) {
5126 WhichResult = M[i] == 0 ? 0 : 1;
5127 for (unsigned j = 0; j < NumElts; j += 2) {
5128 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5129 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5134 if (M.size() == NumElts*2)
5140 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5141 // that the mask elements are either all even and in steps of size 2 or all odd
5142 // and in steps of size 2.
5143 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5144 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5146 // Requires similar checks to that of isVTRNMask with
5147 // respect the how results are returned.
5148 static bool isVUZPMask(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 for (unsigned i = 0; i < M.size(); i += NumElts) {
5158 WhichResult = M[i] == 0 ? 0 : 1;
5159 for (unsigned j = 0; j < NumElts; ++j) {
5160 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5165 if (M.size() == NumElts*2)
5168 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5169 if (VT.is64BitVector() && EltSz == 32)
5175 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5176 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5177 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5178 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5179 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5183 unsigned NumElts = VT.getVectorNumElements();
5184 if (M.size() != NumElts && M.size() != NumElts*2)
5187 unsigned Half = NumElts / 2;
5188 for (unsigned i = 0; i < M.size(); i += NumElts) {
5189 WhichResult = M[i] == 0 ? 0 : 1;
5190 for (unsigned j = 0; j < NumElts; j += Half) {
5191 unsigned Idx = WhichResult;
5192 for (unsigned k = 0; k < Half; ++k) {
5193 int MIdx = M[i + j + k];
5194 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5201 if (M.size() == NumElts*2)
5204 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5205 if (VT.is64BitVector() && EltSz == 32)
5211 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5212 // that pairs of elements of the shufflemask represent the same index in each
5213 // vector incrementing sequentially through the vectors.
5214 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5215 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5217 // Requires similar checks to that of isVTRNMask with respect the how results
5219 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5220 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5224 unsigned NumElts = VT.getVectorNumElements();
5225 if (M.size() != NumElts && M.size() != NumElts*2)
5228 for (unsigned i = 0; i < M.size(); i += NumElts) {
5229 WhichResult = M[i] == 0 ? 0 : 1;
5230 unsigned Idx = WhichResult * NumElts / 2;
5231 for (unsigned j = 0; j < NumElts; j += 2) {
5232 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5233 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5239 if (M.size() == NumElts*2)
5242 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5243 if (VT.is64BitVector() && EltSz == 32)
5249 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5250 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5251 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5252 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5253 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5257 unsigned NumElts = VT.getVectorNumElements();
5258 if (M.size() != NumElts && M.size() != NumElts*2)
5261 for (unsigned i = 0; i < M.size(); i += NumElts) {
5262 WhichResult = M[i] == 0 ? 0 : 1;
5263 unsigned Idx = WhichResult * NumElts / 2;
5264 for (unsigned j = 0; j < NumElts; j += 2) {
5265 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5266 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5272 if (M.size() == NumElts*2)
5275 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5276 if (VT.is64BitVector() && EltSz == 32)
5282 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5283 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5284 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5285 unsigned &WhichResult,
5288 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5289 return ARMISD::VTRN;
5290 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5291 return ARMISD::VUZP;
5292 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5293 return ARMISD::VZIP;
5296 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5297 return ARMISD::VTRN;
5298 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5299 return ARMISD::VUZP;
5300 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5301 return ARMISD::VZIP;
5306 /// \return true if this is a reverse operation on an vector.
5307 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5308 unsigned NumElts = VT.getVectorNumElements();
5309 // Make sure the mask has the right size.
5310 if (NumElts != M.size())
5313 // Look for <15, ..., 3, -1, 1, 0>.
5314 for (unsigned i = 0; i != NumElts; ++i)
5315 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5321 // If N is an integer constant that can be moved into a register in one
5322 // instruction, return an SDValue of such a constant (will become a MOV
5323 // instruction). Otherwise return null.
5324 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5325 const ARMSubtarget *ST, SDLoc dl) {
5327 if (!isa<ConstantSDNode>(N))
5329 Val = cast<ConstantSDNode>(N)->getZExtValue();
5331 if (ST->isThumb1Only()) {
5332 if (Val <= 255 || ~Val <= 255)
5333 return DAG.getConstant(Val, dl, MVT::i32);
5335 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5336 return DAG.getConstant(Val, dl, MVT::i32);
5341 // If this is a case we can't handle, return null and let the default
5342 // expansion code take care of it.
5343 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5344 const ARMSubtarget *ST) const {
5345 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5347 EVT VT = Op.getValueType();
5349 APInt SplatBits, SplatUndef;
5350 unsigned SplatBitSize;
5352 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5353 if (SplatBitSize <= 64) {
5354 // Check if an immediate VMOV works.
5356 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5357 SplatUndef.getZExtValue(), SplatBitSize,
5358 DAG, dl, VmovVT, VT.is128BitVector(),
5360 if (Val.getNode()) {
5361 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5362 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5365 // Try an immediate VMVN.
5366 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5367 Val = isNEONModifiedImm(NegatedImm,
5368 SplatUndef.getZExtValue(), SplatBitSize,
5369 DAG, dl, VmovVT, VT.is128BitVector(),
5371 if (Val.getNode()) {
5372 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5373 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5376 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5377 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5378 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5380 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5381 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5387 // Scan through the operands to see if only one value is used.
5389 // As an optimisation, even if more than one value is used it may be more
5390 // profitable to splat with one value then change some lanes.
5392 // Heuristically we decide to do this if the vector has a "dominant" value,
5393 // defined as splatted to more than half of the lanes.
5394 unsigned NumElts = VT.getVectorNumElements();
5395 bool isOnlyLowElement = true;
5396 bool usesOnlyOneValue = true;
5397 bool hasDominantValue = false;
5398 bool isConstant = true;
5400 // Map of the number of times a particular SDValue appears in the
5402 DenseMap<SDValue, unsigned> ValueCounts;
5404 for (unsigned i = 0; i < NumElts; ++i) {
5405 SDValue V = Op.getOperand(i);
5406 if (V.getOpcode() == ISD::UNDEF)
5409 isOnlyLowElement = false;
5410 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5413 ValueCounts.insert(std::make_pair(V, 0));
5414 unsigned &Count = ValueCounts[V];
5416 // Is this value dominant? (takes up more than half of the lanes)
5417 if (++Count > (NumElts / 2)) {
5418 hasDominantValue = true;
5422 if (ValueCounts.size() != 1)
5423 usesOnlyOneValue = false;
5424 if (!Value.getNode() && ValueCounts.size() > 0)
5425 Value = ValueCounts.begin()->first;
5427 if (ValueCounts.size() == 0)
5428 return DAG.getUNDEF(VT);
5430 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5431 // Keep going if we are hitting this case.
5432 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5433 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5435 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5437 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5438 // i32 and try again.
5439 if (hasDominantValue && EltSize <= 32) {
5443 // If we are VDUPing a value that comes directly from a vector, that will
5444 // cause an unnecessary move to and from a GPR, where instead we could
5445 // just use VDUPLANE. We can only do this if the lane being extracted
5446 // is at a constant index, as the VDUP from lane instructions only have
5447 // constant-index forms.
5448 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5449 isa<ConstantSDNode>(Value->getOperand(1))) {
5450 // We need to create a new undef vector to use for the VDUPLANE if the
5451 // size of the vector from which we get the value is different than the
5452 // size of the vector that we need to create. We will insert the element
5453 // such that the register coalescer will remove unnecessary copies.
5454 if (VT != Value->getOperand(0).getValueType()) {
5455 ConstantSDNode *constIndex;
5456 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5457 assert(constIndex && "The index is not a constant!");
5458 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5459 VT.getVectorNumElements();
5460 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5461 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5462 Value, DAG.getConstant(index, dl, MVT::i32)),
5463 DAG.getConstant(index, dl, MVT::i32));
5465 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5466 Value->getOperand(0), Value->getOperand(1));
5468 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5470 if (!usesOnlyOneValue) {
5471 // The dominant value was splatted as 'N', but we now have to insert
5472 // all differing elements.
5473 for (unsigned I = 0; I < NumElts; ++I) {
5474 if (Op.getOperand(I) == Value)
5476 SmallVector<SDValue, 3> Ops;
5478 Ops.push_back(Op.getOperand(I));
5479 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5480 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5485 if (VT.getVectorElementType().isFloatingPoint()) {
5486 SmallVector<SDValue, 8> Ops;
5487 for (unsigned i = 0; i < NumElts; ++i)
5488 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5490 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5491 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5492 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5494 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5496 if (usesOnlyOneValue) {
5497 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5498 if (isConstant && Val.getNode())
5499 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5503 // If all elements are constants and the case above didn't get hit, fall back
5504 // to the default expansion, which will generate a load from the constant
5509 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5511 SDValue shuffle = ReconstructShuffle(Op, DAG);
5512 if (shuffle != SDValue())
5516 // Vectors with 32- or 64-bit elements can be built by directly assigning
5517 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5518 // will be legalized.
5519 if (EltSize >= 32) {
5520 // Do the expansion with floating-point types, since that is what the VFP
5521 // registers are defined to use, and since i64 is not legal.
5522 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5523 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5524 SmallVector<SDValue, 8> Ops;
5525 for (unsigned i = 0; i < NumElts; ++i)
5526 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5527 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5528 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5531 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5532 // know the default expansion would otherwise fall back on something even
5533 // worse. For a vector with one or two non-undef values, that's
5534 // scalar_to_vector for the elements followed by a shuffle (provided the
5535 // shuffle is valid for the target) and materialization element by element
5536 // on the stack followed by a load for everything else.
5537 if (!isConstant && !usesOnlyOneValue) {
5538 SDValue Vec = DAG.getUNDEF(VT);
5539 for (unsigned i = 0 ; i < NumElts; ++i) {
5540 SDValue V = Op.getOperand(i);
5541 if (V.getOpcode() == ISD::UNDEF)
5543 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5544 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5552 /// getExtFactor - Determine the adjustment factor for the position when
5553 /// generating an "extract from vector registers" instruction.
5554 static unsigned getExtFactor(SDValue &V) {
5555 EVT EltType = V.getValueType().getVectorElementType();
5556 return EltType.getSizeInBits() / 8;
5559 // Gather data to see if the operation can be modelled as a
5560 // shuffle in combination with VEXTs.
5561 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5562 SelectionDAG &DAG) const {
5563 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5565 EVT VT = Op.getValueType();
5566 unsigned NumElts = VT.getVectorNumElements();
5568 struct ShuffleSourceInfo {
5573 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5574 // be compatible with the shuffle we intend to construct. As a result
5575 // ShuffleVec will be some sliding window into the original Vec.
5578 // Code should guarantee that element i in Vec starts at element "WindowBase
5579 // + i * WindowScale in ShuffleVec".
5583 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5584 ShuffleSourceInfo(SDValue Vec)
5585 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5589 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5591 SmallVector<ShuffleSourceInfo, 2> Sources;
5592 for (unsigned i = 0; i < NumElts; ++i) {
5593 SDValue V = Op.getOperand(i);
5594 if (V.getOpcode() == ISD::UNDEF)
5596 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5597 // A shuffle can only come from building a vector from various
5598 // elements of other vectors.
5602 // Add this element source to the list if it's not already there.
5603 SDValue SourceVec = V.getOperand(0);
5604 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5605 if (Source == Sources.end())
5606 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5608 // Update the minimum and maximum lane number seen.
5609 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5610 Source->MinElt = std::min(Source->MinElt, EltNo);
5611 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5614 // Currently only do something sane when at most two source vectors
5616 if (Sources.size() > 2)
5619 // Find out the smallest element size among result and two sources, and use
5620 // it as element size to build the shuffle_vector.
5621 EVT SmallestEltTy = VT.getVectorElementType();
5622 for (auto &Source : Sources) {
5623 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5624 if (SrcEltTy.bitsLT(SmallestEltTy))
5625 SmallestEltTy = SrcEltTy;
5627 unsigned ResMultiplier =
5628 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5629 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5630 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5632 // If the source vector is too wide or too narrow, we may nevertheless be able
5633 // to construct a compatible shuffle either by concatenating it with UNDEF or
5634 // extracting a suitable range of elements.
5635 for (auto &Src : Sources) {
5636 EVT SrcVT = Src.ShuffleVec.getValueType();
5638 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5641 // This stage of the search produces a source with the same element type as
5642 // the original, but with a total width matching the BUILD_VECTOR output.
5643 EVT EltVT = SrcVT.getVectorElementType();
5644 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5645 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5647 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5648 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5650 // We can pad out the smaller vector for free, so if it's part of a
5653 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5654 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5658 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5661 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5662 // Span too large for a VEXT to cope
5666 if (Src.MinElt >= NumSrcElts) {
5667 // The extraction can just take the second half
5669 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5670 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5671 Src.WindowBase = -NumSrcElts;
5672 } else if (Src.MaxElt < NumSrcElts) {
5673 // The extraction can just take the first half
5675 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5676 DAG.getConstant(0, dl, MVT::i32));
5678 // An actual VEXT is needed
5680 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5681 DAG.getConstant(0, dl, MVT::i32));
5683 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5684 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5685 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5687 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5689 DAG.getConstant(Imm, dl, MVT::i32));
5690 Src.WindowBase = -Src.MinElt;
5694 // Another possible incompatibility occurs from the vector element types. We
5695 // can fix this by bitcasting the source vectors to the same type we intend
5697 for (auto &Src : Sources) {
5698 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5699 if (SrcEltTy == SmallestEltTy)
5701 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5702 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5703 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5704 Src.WindowBase *= Src.WindowScale;
5707 // Final sanity check before we try to actually produce a shuffle.
5709 for (auto Src : Sources)
5710 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5713 // The stars all align, our next step is to produce the mask for the shuffle.
5714 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5715 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5716 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5717 SDValue Entry = Op.getOperand(i);
5718 if (Entry.getOpcode() == ISD::UNDEF)
5721 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5722 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5724 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5725 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5727 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5728 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5729 VT.getVectorElementType().getSizeInBits());
5730 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5732 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5733 // starting at the appropriate offset.
5734 int *LaneMask = &Mask[i * ResMultiplier];
5736 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5737 ExtractBase += NumElts * (Src - Sources.begin());
5738 for (int j = 0; j < LanesDefined; ++j)
5739 LaneMask[j] = ExtractBase + j;
5742 // Final check before we try to produce nonsense...
5743 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5746 // We can't handle more than two sources. This should have already
5747 // been checked before this point.
5748 assert(Sources.size() <= 2 && "Too many sources!");
5750 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5751 for (unsigned i = 0; i < Sources.size(); ++i)
5752 ShuffleOps[i] = Sources[i].ShuffleVec;
5754 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5755 ShuffleOps[1], &Mask[0]);
5756 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5759 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5760 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5761 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5762 /// are assumed to be legal.
5764 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5766 if (VT.getVectorNumElements() == 4 &&
5767 (VT.is128BitVector() || VT.is64BitVector())) {
5768 unsigned PFIndexes[4];
5769 for (unsigned i = 0; i != 4; ++i) {
5773 PFIndexes[i] = M[i];
5776 // Compute the index in the perfect shuffle table.
5777 unsigned PFTableIndex =
5778 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5779 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5780 unsigned Cost = (PFEntry >> 30);
5786 bool ReverseVEXT, isV_UNDEF;
5787 unsigned Imm, WhichResult;
5789 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5790 return (EltSize >= 32 ||
5791 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5792 isVREVMask(M, VT, 64) ||
5793 isVREVMask(M, VT, 32) ||
5794 isVREVMask(M, VT, 16) ||
5795 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5796 isVTBLMask(M, VT) ||
5797 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5798 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5801 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5802 /// the specified operations to build the shuffle.
5803 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5804 SDValue RHS, SelectionDAG &DAG,
5806 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5807 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5808 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5811 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5820 OP_VUZPL, // VUZP, left result
5821 OP_VUZPR, // VUZP, right result
5822 OP_VZIPL, // VZIP, left result
5823 OP_VZIPR, // VZIP, right result
5824 OP_VTRNL, // VTRN, left result
5825 OP_VTRNR // VTRN, right result
5828 if (OpNum == OP_COPY) {
5829 if (LHSID == (1*9+2)*9+3) return LHS;
5830 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5834 SDValue OpLHS, OpRHS;
5835 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5836 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5837 EVT VT = OpLHS.getValueType();
5840 default: llvm_unreachable("Unknown shuffle opcode!");
5842 // VREV divides the vector in half and swaps within the half.
5843 if (VT.getVectorElementType() == MVT::i32 ||
5844 VT.getVectorElementType() == MVT::f32)
5845 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5846 // vrev <4 x i16> -> VREV32
5847 if (VT.getVectorElementType() == MVT::i16)
5848 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5849 // vrev <4 x i8> -> VREV16
5850 assert(VT.getVectorElementType() == MVT::i8);
5851 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5856 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5857 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5861 return DAG.getNode(ARMISD::VEXT, dl, VT,
5863 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5866 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5867 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5870 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5871 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5874 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5875 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5879 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5880 ArrayRef<int> ShuffleMask,
5881 SelectionDAG &DAG) {
5882 // Check to see if we can use the VTBL instruction.
5883 SDValue V1 = Op.getOperand(0);
5884 SDValue V2 = Op.getOperand(1);
5887 SmallVector<SDValue, 8> VTBLMask;
5888 for (ArrayRef<int>::iterator
5889 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5890 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5892 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5893 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5894 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5896 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5897 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5900 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5901 SelectionDAG &DAG) {
5903 SDValue OpLHS = Op.getOperand(0);
5904 EVT VT = OpLHS.getValueType();
5906 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5907 "Expect an v8i16/v16i8 type");
5908 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5909 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5910 // extract the first 8 bytes into the top double word and the last 8 bytes
5911 // into the bottom double word. The v8i16 case is similar.
5912 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5913 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5914 DAG.getConstant(ExtractNum, DL, MVT::i32));
5917 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5918 SDValue V1 = Op.getOperand(0);
5919 SDValue V2 = Op.getOperand(1);
5921 EVT VT = Op.getValueType();
5922 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5924 // Convert shuffles that are directly supported on NEON to target-specific
5925 // DAG nodes, instead of keeping them as shuffles and matching them again
5926 // during code selection. This is more efficient and avoids the possibility
5927 // of inconsistencies between legalization and selection.
5928 // FIXME: floating-point vectors should be canonicalized to integer vectors
5929 // of the same time so that they get CSEd properly.
5930 ArrayRef<int> ShuffleMask = SVN->getMask();
5932 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5933 if (EltSize <= 32) {
5934 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5935 int Lane = SVN->getSplatIndex();
5936 // If this is undef splat, generate it via "just" vdup, if possible.
5937 if (Lane == -1) Lane = 0;
5939 // Test if V1 is a SCALAR_TO_VECTOR.
5940 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5941 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5943 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5944 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5946 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5947 !isa<ConstantSDNode>(V1.getOperand(0))) {
5948 bool IsScalarToVector = true;
5949 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5950 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5951 IsScalarToVector = false;
5954 if (IsScalarToVector)
5955 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5957 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5958 DAG.getConstant(Lane, dl, MVT::i32));
5963 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5966 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5967 DAG.getConstant(Imm, dl, MVT::i32));
5970 if (isVREVMask(ShuffleMask, VT, 64))
5971 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5972 if (isVREVMask(ShuffleMask, VT, 32))
5973 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5974 if (isVREVMask(ShuffleMask, VT, 16))
5975 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5977 if (V2->getOpcode() == ISD::UNDEF &&
5978 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5979 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5980 DAG.getConstant(Imm, dl, MVT::i32));
5983 // Check for Neon shuffles that modify both input vectors in place.
5984 // If both results are used, i.e., if there are two shuffles with the same
5985 // source operands and with masks corresponding to both results of one of
5986 // these operations, DAG memoization will ensure that a single node is
5987 // used for both shuffles.
5988 unsigned WhichResult;
5990 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5991 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5994 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5995 .getValue(WhichResult);
5998 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5999 // shuffles that produce a result larger than their operands with:
6000 // shuffle(concat(v1, undef), concat(v2, undef))
6002 // shuffle(concat(v1, v2), undef)
6003 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6005 // This is useful in the general case, but there are special cases where
6006 // native shuffles produce larger results: the two-result ops.
6008 // Look through the concat when lowering them:
6009 // shuffle(concat(v1, v2), undef)
6011 // concat(VZIP(v1, v2):0, :1)
6013 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
6014 V2->getOpcode() == ISD::UNDEF) {
6015 SDValue SubV1 = V1->getOperand(0);
6016 SDValue SubV2 = V1->getOperand(1);
6017 EVT SubVT = SubV1.getValueType();
6019 // We expect these to have been canonicalized to -1.
6020 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6021 return i < (int)VT.getVectorNumElements();
6022 }) && "Unexpected shuffle index into UNDEF operand!");
6024 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6025 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6028 assert((WhichResult == 0) &&
6029 "In-place shuffle of concat can only have one result!");
6030 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6032 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6038 // If the shuffle is not directly supported and it has 4 elements, use
6039 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6040 unsigned NumElts = VT.getVectorNumElements();
6042 unsigned PFIndexes[4];
6043 for (unsigned i = 0; i != 4; ++i) {
6044 if (ShuffleMask[i] < 0)
6047 PFIndexes[i] = ShuffleMask[i];
6050 // Compute the index in the perfect shuffle table.
6051 unsigned PFTableIndex =
6052 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6053 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6054 unsigned Cost = (PFEntry >> 30);
6057 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6060 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6061 if (EltSize >= 32) {
6062 // Do the expansion with floating-point types, since that is what the VFP
6063 // registers are defined to use, and since i64 is not legal.
6064 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6065 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6066 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6067 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6068 SmallVector<SDValue, 8> Ops;
6069 for (unsigned i = 0; i < NumElts; ++i) {
6070 if (ShuffleMask[i] < 0)
6071 Ops.push_back(DAG.getUNDEF(EltVT));
6073 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6074 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6075 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6078 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6079 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6082 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6083 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6085 if (VT == MVT::v8i8) {
6086 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6087 if (NewOp.getNode())
6094 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6095 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6096 SDValue Lane = Op.getOperand(2);
6097 if (!isa<ConstantSDNode>(Lane))
6103 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6104 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6105 SDValue Lane = Op.getOperand(1);
6106 if (!isa<ConstantSDNode>(Lane))
6109 SDValue Vec = Op.getOperand(0);
6110 if (Op.getValueType() == MVT::i32 &&
6111 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6113 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6119 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6120 // The only time a CONCAT_VECTORS operation can have legal types is when
6121 // two 64-bit vectors are concatenated to a 128-bit vector.
6122 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6123 "unexpected CONCAT_VECTORS");
6125 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6126 SDValue Op0 = Op.getOperand(0);
6127 SDValue Op1 = Op.getOperand(1);
6128 if (Op0.getOpcode() != ISD::UNDEF)
6129 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6130 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6131 DAG.getIntPtrConstant(0, dl));
6132 if (Op1.getOpcode() != ISD::UNDEF)
6133 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6134 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6135 DAG.getIntPtrConstant(1, dl));
6136 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6139 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6140 /// element has been zero/sign-extended, depending on the isSigned parameter,
6141 /// from an integer type half its size.
6142 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6144 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6145 EVT VT = N->getValueType(0);
6146 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6147 SDNode *BVN = N->getOperand(0).getNode();
6148 if (BVN->getValueType(0) != MVT::v4i32 ||
6149 BVN->getOpcode() != ISD::BUILD_VECTOR)
6151 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6152 unsigned HiElt = 1 - LoElt;
6153 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6154 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6155 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6156 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6157 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6160 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6161 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6164 if (Hi0->isNullValue() && Hi1->isNullValue())
6170 if (N->getOpcode() != ISD::BUILD_VECTOR)
6173 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6174 SDNode *Elt = N->getOperand(i).getNode();
6175 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6176 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6177 unsigned HalfSize = EltSize / 2;
6179 if (!isIntN(HalfSize, C->getSExtValue()))
6182 if (!isUIntN(HalfSize, C->getZExtValue()))
6193 /// isSignExtended - Check if a node is a vector value that is sign-extended
6194 /// or a constant BUILD_VECTOR with sign-extended elements.
6195 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6196 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6198 if (isExtendedBUILD_VECTOR(N, DAG, true))
6203 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6204 /// or a constant BUILD_VECTOR with zero-extended elements.
6205 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6206 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6208 if (isExtendedBUILD_VECTOR(N, DAG, false))
6213 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6214 if (OrigVT.getSizeInBits() >= 64)
6217 assert(OrigVT.isSimple() && "Expecting a simple value type");
6219 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6220 switch (OrigSimpleTy) {
6221 default: llvm_unreachable("Unexpected Vector Type");
6230 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6231 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6232 /// We insert the required extension here to get the vector to fill a D register.
6233 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6236 unsigned ExtOpcode) {
6237 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6238 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6239 // 64-bits we need to insert a new extension so that it will be 64-bits.
6240 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6241 if (OrigTy.getSizeInBits() >= 64)
6244 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6245 EVT NewVT = getExtensionTo64Bits(OrigTy);
6247 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6250 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6251 /// does not do any sign/zero extension. If the original vector is less
6252 /// than 64 bits, an appropriate extension will be added after the load to
6253 /// reach a total size of 64 bits. We have to add the extension separately
6254 /// because ARM does not have a sign/zero extending load for vectors.
6255 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6256 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6258 // The load already has the right type.
6259 if (ExtendedTy == LD->getMemoryVT())
6260 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6261 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6262 LD->isNonTemporal(), LD->isInvariant(),
6263 LD->getAlignment());
6265 // We need to create a zextload/sextload. We cannot just create a load
6266 // followed by a zext/zext node because LowerMUL is also run during normal
6267 // operation legalization where we can't create illegal types.
6268 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6269 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6270 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6271 LD->isNonTemporal(), LD->getAlignment());
6274 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6275 /// extending load, or BUILD_VECTOR with extended elements, return the
6276 /// unextended value. The unextended vector should be 64 bits so that it can
6277 /// be used as an operand to a VMULL instruction. If the original vector size
6278 /// before extension is less than 64 bits we add a an extension to resize
6279 /// the vector to 64 bits.
6280 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6281 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6282 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6283 N->getOperand(0)->getValueType(0),
6287 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6288 return SkipLoadExtensionForVMULL(LD, DAG);
6290 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6291 // have been legalized as a BITCAST from v4i32.
6292 if (N->getOpcode() == ISD::BITCAST) {
6293 SDNode *BVN = N->getOperand(0).getNode();
6294 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6295 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6296 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6297 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6298 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6300 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6301 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6302 EVT VT = N->getValueType(0);
6303 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6304 unsigned NumElts = VT.getVectorNumElements();
6305 MVT TruncVT = MVT::getIntegerVT(EltSize);
6306 SmallVector<SDValue, 8> Ops;
6308 for (unsigned i = 0; i != NumElts; ++i) {
6309 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6310 const APInt &CInt = C->getAPIntValue();
6311 // Element types smaller than 32 bits are not legal, so use i32 elements.
6312 // The values are implicitly truncated so sext vs. zext doesn't matter.
6313 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6315 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6316 MVT::getVectorVT(TruncVT, NumElts), Ops);
6319 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6320 unsigned Opcode = N->getOpcode();
6321 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6322 SDNode *N0 = N->getOperand(0).getNode();
6323 SDNode *N1 = N->getOperand(1).getNode();
6324 return N0->hasOneUse() && N1->hasOneUse() &&
6325 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6330 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6331 unsigned Opcode = N->getOpcode();
6332 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6333 SDNode *N0 = N->getOperand(0).getNode();
6334 SDNode *N1 = N->getOperand(1).getNode();
6335 return N0->hasOneUse() && N1->hasOneUse() &&
6336 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6341 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6342 // Multiplications are only custom-lowered for 128-bit vectors so that
6343 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6344 EVT VT = Op.getValueType();
6345 assert(VT.is128BitVector() && VT.isInteger() &&
6346 "unexpected type for custom-lowering ISD::MUL");
6347 SDNode *N0 = Op.getOperand(0).getNode();
6348 SDNode *N1 = Op.getOperand(1).getNode();
6349 unsigned NewOpc = 0;
6351 bool isN0SExt = isSignExtended(N0, DAG);
6352 bool isN1SExt = isSignExtended(N1, DAG);
6353 if (isN0SExt && isN1SExt)
6354 NewOpc = ARMISD::VMULLs;
6356 bool isN0ZExt = isZeroExtended(N0, DAG);
6357 bool isN1ZExt = isZeroExtended(N1, DAG);
6358 if (isN0ZExt && isN1ZExt)
6359 NewOpc = ARMISD::VMULLu;
6360 else if (isN1SExt || isN1ZExt) {
6361 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6362 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6363 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6364 NewOpc = ARMISD::VMULLs;
6366 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6367 NewOpc = ARMISD::VMULLu;
6369 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6371 NewOpc = ARMISD::VMULLu;
6377 if (VT == MVT::v2i64)
6378 // Fall through to expand this. It is not legal.
6381 // Other vector multiplications are legal.
6386 // Legalize to a VMULL instruction.
6389 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6391 Op0 = SkipExtensionForVMULL(N0, DAG);
6392 assert(Op0.getValueType().is64BitVector() &&
6393 Op1.getValueType().is64BitVector() &&
6394 "unexpected types for extended operands to VMULL");
6395 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6398 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6399 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6406 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6407 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6408 EVT Op1VT = Op1.getValueType();
6409 return DAG.getNode(N0->getOpcode(), DL, VT,
6410 DAG.getNode(NewOpc, DL, VT,
6411 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6412 DAG.getNode(NewOpc, DL, VT,
6413 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6417 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6419 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6420 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6421 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6422 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6423 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6424 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6425 // Get reciprocal estimate.
6426 // float4 recip = vrecpeq_f32(yf);
6427 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6428 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6430 // Because char has a smaller range than uchar, we can actually get away
6431 // without any newton steps. This requires that we use a weird bias
6432 // of 0xb000, however (again, this has been exhaustively tested).
6433 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6434 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6435 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6436 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6437 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6438 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6439 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6440 // Convert back to short.
6441 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6442 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6447 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6449 // Convert to float.
6450 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6451 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6452 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6453 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6454 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6455 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6457 // Use reciprocal estimate and one refinement step.
6458 // float4 recip = vrecpeq_f32(yf);
6459 // recip *= vrecpsq_f32(yf, recip);
6460 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6461 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6463 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6464 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6466 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6467 // Because short has a smaller range than ushort, we can actually get away
6468 // with only a single newton step. This requires that we use a weird bias
6469 // of 89, however (again, this has been exhaustively tested).
6470 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6471 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6472 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6473 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6474 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6475 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6476 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6477 // Convert back to integer and return.
6478 // return vmovn_s32(vcvt_s32_f32(result));
6479 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6480 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6484 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6485 EVT VT = Op.getValueType();
6486 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6487 "unexpected type for custom-lowering ISD::SDIV");
6490 SDValue N0 = Op.getOperand(0);
6491 SDValue N1 = Op.getOperand(1);
6494 if (VT == MVT::v8i8) {
6495 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6496 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6498 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6499 DAG.getIntPtrConstant(4, dl));
6500 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6501 DAG.getIntPtrConstant(4, dl));
6502 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6503 DAG.getIntPtrConstant(0, dl));
6504 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6505 DAG.getIntPtrConstant(0, dl));
6507 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6508 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6510 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6511 N0 = LowerCONCAT_VECTORS(N0, DAG);
6513 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6516 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6519 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6520 EVT VT = Op.getValueType();
6521 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6522 "unexpected type for custom-lowering ISD::UDIV");
6525 SDValue N0 = Op.getOperand(0);
6526 SDValue N1 = Op.getOperand(1);
6529 if (VT == MVT::v8i8) {
6530 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6531 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6533 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6534 DAG.getIntPtrConstant(4, dl));
6535 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6536 DAG.getIntPtrConstant(4, dl));
6537 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6538 DAG.getIntPtrConstant(0, dl));
6539 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6540 DAG.getIntPtrConstant(0, dl));
6542 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6543 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6545 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6546 N0 = LowerCONCAT_VECTORS(N0, DAG);
6548 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6549 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6555 // v4i16 sdiv ... Convert to float.
6556 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6557 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6558 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6559 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6560 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6561 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6563 // Use reciprocal estimate and two refinement steps.
6564 // float4 recip = vrecpeq_f32(yf);
6565 // recip *= vrecpsq_f32(yf, recip);
6566 // recip *= vrecpsq_f32(yf, recip);
6567 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6568 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6570 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6571 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6573 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6574 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6575 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6577 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6578 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6579 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6580 // and that it will never cause us to return an answer too large).
6581 // float4 result = as_float4(as_int4(xf*recip) + 2);
6582 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6583 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6584 N1 = DAG.getConstant(2, dl, MVT::i32);
6585 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6586 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6587 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6588 // Convert back to integer and return.
6589 // return vmovn_u32(vcvt_s32_f32(result));
6590 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6591 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6595 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6596 EVT VT = Op.getNode()->getValueType(0);
6597 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6600 bool ExtraOp = false;
6601 switch (Op.getOpcode()) {
6602 default: llvm_unreachable("Invalid code");
6603 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6604 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6605 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6606 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6610 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6612 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6613 Op.getOperand(1), Op.getOperand(2));
6616 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6617 assert(Subtarget->isTargetDarwin());
6619 // For iOS, we want to call an alternative entry point: __sincos_stret,
6620 // return values are passed via sret.
6622 SDValue Arg = Op.getOperand(0);
6623 EVT ArgVT = Arg.getValueType();
6624 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6625 auto PtrVT = getPointerTy(DAG.getDataLayout());
6627 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6629 // Pair of floats / doubles used to pass the result.
6630 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6632 // Create stack object for sret.
6633 auto &DL = DAG.getDataLayout();
6634 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6635 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6636 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6637 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6643 Entry.Ty = RetTy->getPointerTo();
6644 Entry.isSExt = false;
6645 Entry.isZExt = false;
6646 Entry.isSRet = true;
6647 Args.push_back(Entry);
6651 Entry.isSExt = false;
6652 Entry.isZExt = false;
6653 Args.push_back(Entry);
6655 const char *LibcallName = (ArgVT == MVT::f64)
6656 ? "__sincos_stret" : "__sincosf_stret";
6657 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6659 TargetLowering::CallLoweringInfo CLI(DAG);
6660 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6661 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6663 .setDiscardResult();
6665 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6667 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6668 MachinePointerInfo(), false, false, false, 0);
6670 // Address of cos field.
6671 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6672 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6673 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6674 MachinePointerInfo(), false, false, false, 0);
6676 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6677 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6678 LoadSin.getValue(0), LoadCos.getValue(0));
6681 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6682 // Monotonic load/store is legal for all targets
6683 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6686 // Acquire/Release load/store is not legal for targets without a
6687 // dmb or equivalent available.
6691 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6692 SmallVectorImpl<SDValue> &Results,
6694 const ARMSubtarget *Subtarget) {
6696 SDValue Cycles32, OutChain;
6698 if (Subtarget->hasPerfMon()) {
6699 // Under Power Management extensions, the cycle-count is:
6700 // mrc p15, #0, <Rt>, c9, c13, #0
6701 SDValue Ops[] = { N->getOperand(0), // Chain
6702 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6703 DAG.getConstant(15, DL, MVT::i32),
6704 DAG.getConstant(0, DL, MVT::i32),
6705 DAG.getConstant(9, DL, MVT::i32),
6706 DAG.getConstant(13, DL, MVT::i32),
6707 DAG.getConstant(0, DL, MVT::i32)
6710 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6711 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6712 OutChain = Cycles32.getValue(1);
6714 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6715 // there are older ARM CPUs that have implementation-specific ways of
6716 // obtaining this information (FIXME!).
6717 Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6718 OutChain = DAG.getEntryNode();
6722 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6723 Cycles32, DAG.getConstant(0, DL, MVT::i32));
6724 Results.push_back(Cycles64);
6725 Results.push_back(OutChain);
6728 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6729 switch (Op.getOpcode()) {
6730 default: llvm_unreachable("Don't know how to custom lower this!");
6731 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6732 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6733 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6734 case ISD::GlobalAddress:
6735 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6736 default: llvm_unreachable("unknown object format");
6738 return LowerGlobalAddressWindows(Op, DAG);
6740 return LowerGlobalAddressELF(Op, DAG);
6742 return LowerGlobalAddressDarwin(Op, DAG);
6744 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6745 case ISD::SELECT: return LowerSELECT(Op, DAG);
6746 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6747 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6748 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6749 case ISD::VASTART: return LowerVASTART(Op, DAG);
6750 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6751 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6752 case ISD::SINT_TO_FP:
6753 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6754 case ISD::FP_TO_SINT:
6755 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6756 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6757 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6758 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6759 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6760 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6761 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6762 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6763 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6765 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6768 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6769 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6770 case ISD::SRL_PARTS:
6771 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6773 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6774 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6775 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6776 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6777 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6778 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6779 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6780 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6781 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6782 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6783 case ISD::MUL: return LowerMUL(Op, DAG);
6784 case ISD::SDIV: return LowerSDIV(Op, DAG);
6785 case ISD::UDIV: return LowerUDIV(Op, DAG);
6789 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6794 return LowerXALUO(Op, DAG);
6795 case ISD::ATOMIC_LOAD:
6796 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6797 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6799 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6800 case ISD::DYNAMIC_STACKALLOC:
6801 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6802 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6803 llvm_unreachable("Don't know how to custom lower this!");
6804 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6805 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6809 /// ReplaceNodeResults - Replace the results of node with an illegal result
6810 /// type with new values built out of custom code.
6811 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6812 SmallVectorImpl<SDValue>&Results,
6813 SelectionDAG &DAG) const {
6815 switch (N->getOpcode()) {
6817 llvm_unreachable("Don't know how to custom expand this!");
6818 case ISD::READ_REGISTER:
6819 ExpandREAD_REGISTER(N, Results, DAG);
6822 Res = ExpandBITCAST(N, DAG);
6826 Res = Expand64BitShift(N, DAG, Subtarget);
6828 case ISD::READCYCLECOUNTER:
6829 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6833 Results.push_back(Res);
6836 //===----------------------------------------------------------------------===//
6837 // ARM Scheduler Hooks
6838 //===----------------------------------------------------------------------===//
6840 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6841 /// registers the function context.
6842 void ARMTargetLowering::
6843 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6844 MachineBasicBlock *DispatchBB, int FI) const {
6845 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6846 DebugLoc dl = MI->getDebugLoc();
6847 MachineFunction *MF = MBB->getParent();
6848 MachineRegisterInfo *MRI = &MF->getRegInfo();
6849 MachineConstantPool *MCP = MF->getConstantPool();
6850 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6851 const Function *F = MF->getFunction();
6853 bool isThumb = Subtarget->isThumb();
6854 bool isThumb2 = Subtarget->isThumb2();
6856 unsigned PCLabelId = AFI->createPICLabelUId();
6857 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6858 ARMConstantPoolValue *CPV =
6859 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6860 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6862 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6863 : &ARM::GPRRegClass;
6865 // Grab constant pool and fixed stack memory operands.
6866 MachineMemOperand *CPMMO =
6867 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6868 MachineMemOperand::MOLoad, 4, 4);
6870 MachineMemOperand *FIMMOSt =
6871 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6872 MachineMemOperand::MOStore, 4, 4);
6874 // Load the address of the dispatch MBB into the jump buffer.
6876 // Incoming value: jbuf
6877 // ldr.n r5, LCPI1_1
6880 // str r5, [$jbuf, #+4] ; &jbuf[1]
6881 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6882 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6883 .addConstantPoolIndex(CPI)
6884 .addMemOperand(CPMMO));
6885 // Set the low bit because of thumb mode.
6886 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6888 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6889 .addReg(NewVReg1, RegState::Kill)
6891 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6892 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6893 .addReg(NewVReg2, RegState::Kill)
6895 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6896 .addReg(NewVReg3, RegState::Kill)
6898 .addImm(36) // &jbuf[1] :: pc
6899 .addMemOperand(FIMMOSt));
6900 } else if (isThumb) {
6901 // Incoming value: jbuf
6902 // ldr.n r1, LCPI1_4
6906 // add r2, $jbuf, #+4 ; &jbuf[1]
6908 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6909 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6910 .addConstantPoolIndex(CPI)
6911 .addMemOperand(CPMMO));
6912 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6913 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6914 .addReg(NewVReg1, RegState::Kill)
6916 // Set the low bit because of thumb mode.
6917 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6918 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6919 .addReg(ARM::CPSR, RegState::Define)
6921 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6922 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6923 .addReg(ARM::CPSR, RegState::Define)
6924 .addReg(NewVReg2, RegState::Kill)
6925 .addReg(NewVReg3, RegState::Kill));
6926 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6927 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6929 .addImm(36); // &jbuf[1] :: pc
6930 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6931 .addReg(NewVReg4, RegState::Kill)
6932 .addReg(NewVReg5, RegState::Kill)
6934 .addMemOperand(FIMMOSt));
6936 // Incoming value: jbuf
6939 // str r1, [$jbuf, #+4] ; &jbuf[1]
6940 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6941 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6942 .addConstantPoolIndex(CPI)
6944 .addMemOperand(CPMMO));
6945 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6946 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6947 .addReg(NewVReg1, RegState::Kill)
6948 .addImm(PCLabelId));
6949 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6950 .addReg(NewVReg2, RegState::Kill)
6952 .addImm(36) // &jbuf[1] :: pc
6953 .addMemOperand(FIMMOSt));
6957 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6958 MachineBasicBlock *MBB) const {
6959 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6960 DebugLoc dl = MI->getDebugLoc();
6961 MachineFunction *MF = MBB->getParent();
6962 MachineRegisterInfo *MRI = &MF->getRegInfo();
6963 MachineFrameInfo *MFI = MF->getFrameInfo();
6964 int FI = MFI->getFunctionContextIndex();
6966 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6967 : &ARM::GPRnopcRegClass;
6969 // Get a mapping of the call site numbers to all of the landing pads they're
6971 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6972 unsigned MaxCSNum = 0;
6973 MachineModuleInfo &MMI = MF->getMMI();
6974 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6976 if (!BB->isLandingPad()) continue;
6978 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6980 for (MachineBasicBlock::iterator
6981 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6982 if (!II->isEHLabel()) continue;
6984 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6985 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6987 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6988 for (SmallVectorImpl<unsigned>::iterator
6989 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6990 CSI != CSE; ++CSI) {
6991 CallSiteNumToLPad[*CSI].push_back(BB);
6992 MaxCSNum = std::max(MaxCSNum, *CSI);
6998 // Get an ordered list of the machine basic blocks for the jump table.
6999 std::vector<MachineBasicBlock*> LPadList;
7000 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7001 LPadList.reserve(CallSiteNumToLPad.size());
7002 for (unsigned I = 1; I <= MaxCSNum; ++I) {
7003 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7004 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7005 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7006 LPadList.push_back(*II);
7007 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7011 assert(!LPadList.empty() &&
7012 "No landing pad destinations for the dispatch jump table!");
7014 // Create the jump table and associated information.
7015 MachineJumpTableInfo *JTI =
7016 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7017 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7018 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7020 // Create the MBBs for the dispatch code.
7022 // Shove the dispatch's address into the return slot in the function context.
7023 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7024 DispatchBB->setIsLandingPad();
7026 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7027 unsigned trap_opcode;
7028 if (Subtarget->isThumb())
7029 trap_opcode = ARM::tTRAP;
7031 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7033 BuildMI(TrapBB, dl, TII->get(trap_opcode));
7034 DispatchBB->addSuccessor(TrapBB);
7036 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7037 DispatchBB->addSuccessor(DispContBB);
7040 MF->insert(MF->end(), DispatchBB);
7041 MF->insert(MF->end(), DispContBB);
7042 MF->insert(MF->end(), TrapBB);
7044 // Insert code into the entry block that creates and registers the function
7046 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7048 MachineMemOperand *FIMMOLd =
7049 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
7050 MachineMemOperand::MOLoad |
7051 MachineMemOperand::MOVolatile, 4, 4);
7053 MachineInstrBuilder MIB;
7054 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7056 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7057 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7059 // Add a register mask with no preserved registers. This results in all
7060 // registers being marked as clobbered.
7061 MIB.addRegMask(RI.getNoPreservedMask());
7063 unsigned NumLPads = LPadList.size();
7064 if (Subtarget->isThumb2()) {
7065 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7066 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7069 .addMemOperand(FIMMOLd));
7071 if (NumLPads < 256) {
7072 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7074 .addImm(LPadList.size()));
7076 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7077 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7078 .addImm(NumLPads & 0xFFFF));
7080 unsigned VReg2 = VReg1;
7081 if ((NumLPads & 0xFFFF0000) != 0) {
7082 VReg2 = MRI->createVirtualRegister(TRC);
7083 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7085 .addImm(NumLPads >> 16));
7088 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7093 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7098 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7099 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7100 .addJumpTableIndex(MJTI));
7102 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7105 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7106 .addReg(NewVReg3, RegState::Kill)
7108 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7110 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7111 .addReg(NewVReg4, RegState::Kill)
7113 .addJumpTableIndex(MJTI);
7114 } else if (Subtarget->isThumb()) {
7115 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7116 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7119 .addMemOperand(FIMMOLd));
7121 if (NumLPads < 256) {
7122 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7126 MachineConstantPool *ConstantPool = MF->getConstantPool();
7127 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7128 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7130 // MachineConstantPool wants an explicit alignment.
7131 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7133 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7134 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7136 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7137 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7138 .addReg(VReg1, RegState::Define)
7139 .addConstantPoolIndex(Idx));
7140 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7145 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7150 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7151 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7152 .addReg(ARM::CPSR, RegState::Define)
7156 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7157 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7158 .addJumpTableIndex(MJTI));
7160 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7161 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7162 .addReg(ARM::CPSR, RegState::Define)
7163 .addReg(NewVReg2, RegState::Kill)
7166 MachineMemOperand *JTMMOLd =
7167 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7168 MachineMemOperand::MOLoad, 4, 4);
7170 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7171 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7172 .addReg(NewVReg4, RegState::Kill)
7174 .addMemOperand(JTMMOLd));
7176 unsigned NewVReg6 = NewVReg5;
7177 if (RelocM == Reloc::PIC_) {
7178 NewVReg6 = MRI->createVirtualRegister(TRC);
7179 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7180 .addReg(ARM::CPSR, RegState::Define)
7181 .addReg(NewVReg5, RegState::Kill)
7185 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7186 .addReg(NewVReg6, RegState::Kill)
7187 .addJumpTableIndex(MJTI);
7189 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7190 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7193 .addMemOperand(FIMMOLd));
7195 if (NumLPads < 256) {
7196 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7199 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7200 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7201 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7202 .addImm(NumLPads & 0xFFFF));
7204 unsigned VReg2 = VReg1;
7205 if ((NumLPads & 0xFFFF0000) != 0) {
7206 VReg2 = MRI->createVirtualRegister(TRC);
7207 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7209 .addImm(NumLPads >> 16));
7212 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7216 MachineConstantPool *ConstantPool = MF->getConstantPool();
7217 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7218 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7220 // MachineConstantPool wants an explicit alignment.
7221 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7223 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7224 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7226 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7227 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7228 .addReg(VReg1, RegState::Define)
7229 .addConstantPoolIndex(Idx)
7231 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7233 .addReg(VReg1, RegState::Kill));
7236 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7241 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7243 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7245 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7246 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7247 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7248 .addJumpTableIndex(MJTI));
7250 MachineMemOperand *JTMMOLd =
7251 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7252 MachineMemOperand::MOLoad, 4, 4);
7253 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7255 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7256 .addReg(NewVReg3, RegState::Kill)
7259 .addMemOperand(JTMMOLd));
7261 if (RelocM == Reloc::PIC_) {
7262 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7263 .addReg(NewVReg5, RegState::Kill)
7265 .addJumpTableIndex(MJTI);
7267 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7268 .addReg(NewVReg5, RegState::Kill)
7269 .addJumpTableIndex(MJTI);
7273 // Add the jump table entries as successors to the MBB.
7274 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7275 for (std::vector<MachineBasicBlock*>::iterator
7276 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7277 MachineBasicBlock *CurMBB = *I;
7278 if (SeenMBBs.insert(CurMBB).second)
7279 DispContBB->addSuccessor(CurMBB);
7282 // N.B. the order the invoke BBs are processed in doesn't matter here.
7283 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7284 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7285 for (MachineBasicBlock *BB : InvokeBBs) {
7287 // Remove the landing pad successor from the invoke block and replace it
7288 // with the new dispatch block.
7289 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7291 while (!Successors.empty()) {
7292 MachineBasicBlock *SMBB = Successors.pop_back_val();
7293 if (SMBB->isLandingPad()) {
7294 BB->removeSuccessor(SMBB);
7295 MBBLPads.push_back(SMBB);
7299 BB->addSuccessor(DispatchBB);
7301 // Find the invoke call and mark all of the callee-saved registers as
7302 // 'implicit defined' so that they're spilled. This prevents code from
7303 // moving instructions to before the EH block, where they will never be
7305 for (MachineBasicBlock::reverse_iterator
7306 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7307 if (!II->isCall()) continue;
7309 DenseMap<unsigned, bool> DefRegs;
7310 for (MachineInstr::mop_iterator
7311 OI = II->operands_begin(), OE = II->operands_end();
7313 if (!OI->isReg()) continue;
7314 DefRegs[OI->getReg()] = true;
7317 MachineInstrBuilder MIB(*MF, &*II);
7319 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7320 unsigned Reg = SavedRegs[i];
7321 if (Subtarget->isThumb2() &&
7322 !ARM::tGPRRegClass.contains(Reg) &&
7323 !ARM::hGPRRegClass.contains(Reg))
7325 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7327 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7330 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7337 // Mark all former landing pads as non-landing pads. The dispatch is the only
7339 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7340 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7341 (*I)->setIsLandingPad(false);
7343 // The instruction is gone now.
7344 MI->eraseFromParent();
7348 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7349 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7350 E = MBB->succ_end(); I != E; ++I)
7353 llvm_unreachable("Expecting a BB with two successors!");
7356 /// Return the load opcode for a given load size. If load size >= 8,
7357 /// neon opcode will be returned.
7358 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7360 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7361 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7363 return LdSize == 4 ? ARM::tLDRi
7364 : LdSize == 2 ? ARM::tLDRHi
7365 : LdSize == 1 ? ARM::tLDRBi : 0;
7367 return LdSize == 4 ? ARM::t2LDR_POST
7368 : LdSize == 2 ? ARM::t2LDRH_POST
7369 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7370 return LdSize == 4 ? ARM::LDR_POST_IMM
7371 : LdSize == 2 ? ARM::LDRH_POST
7372 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7375 /// Return the store opcode for a given store size. If store size >= 8,
7376 /// neon opcode will be returned.
7377 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7379 return StSize == 16 ? ARM::VST1q32wb_fixed
7380 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7382 return StSize == 4 ? ARM::tSTRi
7383 : StSize == 2 ? ARM::tSTRHi
7384 : StSize == 1 ? ARM::tSTRBi : 0;
7386 return StSize == 4 ? ARM::t2STR_POST
7387 : StSize == 2 ? ARM::t2STRH_POST
7388 : StSize == 1 ? ARM::t2STRB_POST : 0;
7389 return StSize == 4 ? ARM::STR_POST_IMM
7390 : StSize == 2 ? ARM::STRH_POST
7391 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7394 /// Emit a post-increment load operation with given size. The instructions
7395 /// will be added to BB at Pos.
7396 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7397 const TargetInstrInfo *TII, DebugLoc dl,
7398 unsigned LdSize, unsigned Data, unsigned AddrIn,
7399 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7400 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7401 assert(LdOpc != 0 && "Should have a load opcode");
7403 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7404 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7406 } else if (IsThumb1) {
7407 // load + update AddrIn
7408 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7409 .addReg(AddrIn).addImm(0));
7410 MachineInstrBuilder MIB =
7411 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7412 MIB = AddDefaultT1CC(MIB);
7413 MIB.addReg(AddrIn).addImm(LdSize);
7414 AddDefaultPred(MIB);
7415 } else if (IsThumb2) {
7416 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7417 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7420 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7421 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7422 .addReg(0).addImm(LdSize));
7426 /// Emit a post-increment store operation with given size. The instructions
7427 /// will be added to BB at Pos.
7428 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7429 const TargetInstrInfo *TII, DebugLoc dl,
7430 unsigned StSize, unsigned Data, unsigned AddrIn,
7431 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7432 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7433 assert(StOpc != 0 && "Should have a store opcode");
7435 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7436 .addReg(AddrIn).addImm(0).addReg(Data));
7437 } else if (IsThumb1) {
7438 // store + update AddrIn
7439 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7440 .addReg(AddrIn).addImm(0));
7441 MachineInstrBuilder MIB =
7442 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7443 MIB = AddDefaultT1CC(MIB);
7444 MIB.addReg(AddrIn).addImm(StSize);
7445 AddDefaultPred(MIB);
7446 } else if (IsThumb2) {
7447 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7448 .addReg(Data).addReg(AddrIn).addImm(StSize));
7450 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7451 .addReg(Data).addReg(AddrIn).addReg(0)
7457 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7458 MachineBasicBlock *BB) const {
7459 // This pseudo instruction has 3 operands: dst, src, size
7460 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7461 // Otherwise, we will generate unrolled scalar copies.
7462 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7463 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7464 MachineFunction::iterator It = BB;
7467 unsigned dest = MI->getOperand(0).getReg();
7468 unsigned src = MI->getOperand(1).getReg();
7469 unsigned SizeVal = MI->getOperand(2).getImm();
7470 unsigned Align = MI->getOperand(3).getImm();
7471 DebugLoc dl = MI->getDebugLoc();
7473 MachineFunction *MF = BB->getParent();
7474 MachineRegisterInfo &MRI = MF->getRegInfo();
7475 unsigned UnitSize = 0;
7476 const TargetRegisterClass *TRC = nullptr;
7477 const TargetRegisterClass *VecTRC = nullptr;
7479 bool IsThumb1 = Subtarget->isThumb1Only();
7480 bool IsThumb2 = Subtarget->isThumb2();
7484 } else if (Align & 2) {
7487 // Check whether we can use NEON instructions.
7488 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7489 Subtarget->hasNEON()) {
7490 if ((Align % 16 == 0) && SizeVal >= 16)
7492 else if ((Align % 8 == 0) && SizeVal >= 8)
7495 // Can't use NEON instructions.
7500 // Select the correct opcode and register class for unit size load/store
7501 bool IsNeon = UnitSize >= 8;
7502 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7504 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7505 : UnitSize == 8 ? &ARM::DPRRegClass
7508 unsigned BytesLeft = SizeVal % UnitSize;
7509 unsigned LoopSize = SizeVal - BytesLeft;
7511 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7512 // Use LDR and STR to copy.
7513 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7514 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7515 unsigned srcIn = src;
7516 unsigned destIn = dest;
7517 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7518 unsigned srcOut = MRI.createVirtualRegister(TRC);
7519 unsigned destOut = MRI.createVirtualRegister(TRC);
7520 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7521 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7522 IsThumb1, IsThumb2);
7523 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7524 IsThumb1, IsThumb2);
7529 // Handle the leftover bytes with LDRB and STRB.
7530 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7531 // [destOut] = STRB_POST(scratch, destIn, 1)
7532 for (unsigned i = 0; i < BytesLeft; i++) {
7533 unsigned srcOut = MRI.createVirtualRegister(TRC);
7534 unsigned destOut = MRI.createVirtualRegister(TRC);
7535 unsigned scratch = MRI.createVirtualRegister(TRC);
7536 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7537 IsThumb1, IsThumb2);
7538 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7539 IsThumb1, IsThumb2);
7543 MI->eraseFromParent(); // The instruction is gone now.
7547 // Expand the pseudo op to a loop.
7550 // movw varEnd, # --> with thumb2
7552 // ldrcp varEnd, idx --> without thumb2
7553 // fallthrough --> loopMBB
7555 // PHI varPhi, varEnd, varLoop
7556 // PHI srcPhi, src, srcLoop
7557 // PHI destPhi, dst, destLoop
7558 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7559 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7560 // subs varLoop, varPhi, #UnitSize
7562 // fallthrough --> exitMBB
7564 // epilogue to handle left-over bytes
7565 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7566 // [destOut] = STRB_POST(scratch, destLoop, 1)
7567 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7568 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7569 MF->insert(It, loopMBB);
7570 MF->insert(It, exitMBB);
7572 // Transfer the remainder of BB and its successor edges to exitMBB.
7573 exitMBB->splice(exitMBB->begin(), BB,
7574 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7575 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7577 // Load an immediate to varEnd.
7578 unsigned varEnd = MRI.createVirtualRegister(TRC);
7579 if (Subtarget->useMovt(*MF)) {
7580 unsigned Vtmp = varEnd;
7581 if ((LoopSize & 0xFFFF0000) != 0)
7582 Vtmp = MRI.createVirtualRegister(TRC);
7583 AddDefaultPred(BuildMI(BB, dl,
7584 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7585 Vtmp).addImm(LoopSize & 0xFFFF));
7587 if ((LoopSize & 0xFFFF0000) != 0)
7588 AddDefaultPred(BuildMI(BB, dl,
7589 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7592 .addImm(LoopSize >> 16));
7594 MachineConstantPool *ConstantPool = MF->getConstantPool();
7595 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7596 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7598 // MachineConstantPool wants an explicit alignment.
7599 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7601 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7602 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7605 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7606 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7608 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7609 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7611 BB->addSuccessor(loopMBB);
7613 // Generate the loop body:
7614 // varPhi = PHI(varLoop, varEnd)
7615 // srcPhi = PHI(srcLoop, src)
7616 // destPhi = PHI(destLoop, dst)
7617 MachineBasicBlock *entryBB = BB;
7619 unsigned varLoop = MRI.createVirtualRegister(TRC);
7620 unsigned varPhi = MRI.createVirtualRegister(TRC);
7621 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7622 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7623 unsigned destLoop = MRI.createVirtualRegister(TRC);
7624 unsigned destPhi = MRI.createVirtualRegister(TRC);
7626 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7627 .addReg(varLoop).addMBB(loopMBB)
7628 .addReg(varEnd).addMBB(entryBB);
7629 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7630 .addReg(srcLoop).addMBB(loopMBB)
7631 .addReg(src).addMBB(entryBB);
7632 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7633 .addReg(destLoop).addMBB(loopMBB)
7634 .addReg(dest).addMBB(entryBB);
7636 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7637 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7638 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7639 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7640 IsThumb1, IsThumb2);
7641 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7642 IsThumb1, IsThumb2);
7644 // Decrement loop variable by UnitSize.
7646 MachineInstrBuilder MIB =
7647 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7648 MIB = AddDefaultT1CC(MIB);
7649 MIB.addReg(varPhi).addImm(UnitSize);
7650 AddDefaultPred(MIB);
7652 MachineInstrBuilder MIB =
7653 BuildMI(*BB, BB->end(), dl,
7654 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7655 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7656 MIB->getOperand(5).setReg(ARM::CPSR);
7657 MIB->getOperand(5).setIsDef(true);
7659 BuildMI(*BB, BB->end(), dl,
7660 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7661 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7663 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7664 BB->addSuccessor(loopMBB);
7665 BB->addSuccessor(exitMBB);
7667 // Add epilogue to handle BytesLeft.
7669 MachineInstr *StartOfExit = exitMBB->begin();
7671 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7672 // [destOut] = STRB_POST(scratch, destLoop, 1)
7673 unsigned srcIn = srcLoop;
7674 unsigned destIn = destLoop;
7675 for (unsigned i = 0; i < BytesLeft; i++) {
7676 unsigned srcOut = MRI.createVirtualRegister(TRC);
7677 unsigned destOut = MRI.createVirtualRegister(TRC);
7678 unsigned scratch = MRI.createVirtualRegister(TRC);
7679 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7680 IsThumb1, IsThumb2);
7681 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7682 IsThumb1, IsThumb2);
7687 MI->eraseFromParent(); // The instruction is gone now.
7692 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7693 MachineBasicBlock *MBB) const {
7694 const TargetMachine &TM = getTargetMachine();
7695 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7696 DebugLoc DL = MI->getDebugLoc();
7698 assert(Subtarget->isTargetWindows() &&
7699 "__chkstk is only supported on Windows");
7700 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7702 // __chkstk takes the number of words to allocate on the stack in R4, and
7703 // returns the stack adjustment in number of bytes in R4. This will not
7704 // clober any other registers (other than the obvious lr).
7706 // Although, technically, IP should be considered a register which may be
7707 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7708 // thumb-2 environment, so there is no interworking required. As a result, we
7709 // do not expect a veneer to be emitted by the linker, clobbering IP.
7711 // Each module receives its own copy of __chkstk, so no import thunk is
7712 // required, again, ensuring that IP is not clobbered.
7714 // Finally, although some linkers may theoretically provide a trampoline for
7715 // out of range calls (which is quite common due to a 32M range limitation of
7716 // branches for Thumb), we can generate the long-call version via
7717 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7720 switch (TM.getCodeModel()) {
7721 case CodeModel::Small:
7722 case CodeModel::Medium:
7723 case CodeModel::Default:
7724 case CodeModel::Kernel:
7725 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7726 .addImm((unsigned)ARMCC::AL).addReg(0)
7727 .addExternalSymbol("__chkstk")
7728 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7729 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7730 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7732 case CodeModel::Large:
7733 case CodeModel::JITDefault: {
7734 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7735 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7737 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7738 .addExternalSymbol("__chkstk");
7739 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7740 .addImm((unsigned)ARMCC::AL).addReg(0)
7741 .addReg(Reg, RegState::Kill)
7742 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7743 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7744 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7749 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7751 .addReg(ARM::SP).addReg(ARM::R4)));
7753 MI->eraseFromParent();
7758 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7759 MachineBasicBlock *BB) const {
7760 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7761 DebugLoc dl = MI->getDebugLoc();
7762 bool isThumb2 = Subtarget->isThumb2();
7763 switch (MI->getOpcode()) {
7766 llvm_unreachable("Unexpected instr type to insert");
7768 // The Thumb2 pre-indexed stores have the same MI operands, they just
7769 // define them differently in the .td files from the isel patterns, so
7770 // they need pseudos.
7771 case ARM::t2STR_preidx:
7772 MI->setDesc(TII->get(ARM::t2STR_PRE));
7774 case ARM::t2STRB_preidx:
7775 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7777 case ARM::t2STRH_preidx:
7778 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7781 case ARM::STRi_preidx:
7782 case ARM::STRBi_preidx: {
7783 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7784 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7785 // Decode the offset.
7786 unsigned Offset = MI->getOperand(4).getImm();
7787 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7788 Offset = ARM_AM::getAM2Offset(Offset);
7792 MachineMemOperand *MMO = *MI->memoperands_begin();
7793 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7794 .addOperand(MI->getOperand(0)) // Rn_wb
7795 .addOperand(MI->getOperand(1)) // Rt
7796 .addOperand(MI->getOperand(2)) // Rn
7797 .addImm(Offset) // offset (skip GPR==zero_reg)
7798 .addOperand(MI->getOperand(5)) // pred
7799 .addOperand(MI->getOperand(6))
7800 .addMemOperand(MMO);
7801 MI->eraseFromParent();
7804 case ARM::STRr_preidx:
7805 case ARM::STRBr_preidx:
7806 case ARM::STRH_preidx: {
7808 switch (MI->getOpcode()) {
7809 default: llvm_unreachable("unexpected opcode!");
7810 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7811 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7812 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7814 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7815 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7816 MIB.addOperand(MI->getOperand(i));
7817 MI->eraseFromParent();
7821 case ARM::tMOVCCr_pseudo: {
7822 // To "insert" a SELECT_CC instruction, we actually have to insert the
7823 // diamond control-flow pattern. The incoming instruction knows the
7824 // destination vreg to set, the condition code register to branch on, the
7825 // true/false values to select between, and a branch opcode to use.
7826 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7827 MachineFunction::iterator It = BB;
7833 // cmpTY ccX, r1, r2
7835 // fallthrough --> copy0MBB
7836 MachineBasicBlock *thisMBB = BB;
7837 MachineFunction *F = BB->getParent();
7838 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7839 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7840 F->insert(It, copy0MBB);
7841 F->insert(It, sinkMBB);
7843 // Transfer the remainder of BB and its successor edges to sinkMBB.
7844 sinkMBB->splice(sinkMBB->begin(), BB,
7845 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7846 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7848 BB->addSuccessor(copy0MBB);
7849 BB->addSuccessor(sinkMBB);
7851 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7852 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7855 // %FalseValue = ...
7856 // # fallthrough to sinkMBB
7859 // Update machine-CFG edges
7860 BB->addSuccessor(sinkMBB);
7863 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7866 BuildMI(*BB, BB->begin(), dl,
7867 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7868 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7869 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7871 MI->eraseFromParent(); // The pseudo instruction is gone now.
7876 case ARM::BCCZi64: {
7877 // If there is an unconditional branch to the other successor, remove it.
7878 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7880 // Compare both parts that make up the double comparison separately for
7882 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7884 unsigned LHS1 = MI->getOperand(1).getReg();
7885 unsigned LHS2 = MI->getOperand(2).getReg();
7887 AddDefaultPred(BuildMI(BB, dl,
7888 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7889 .addReg(LHS1).addImm(0));
7890 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7891 .addReg(LHS2).addImm(0)
7892 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7894 unsigned RHS1 = MI->getOperand(3).getReg();
7895 unsigned RHS2 = MI->getOperand(4).getReg();
7896 AddDefaultPred(BuildMI(BB, dl,
7897 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7898 .addReg(LHS1).addReg(RHS1));
7899 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7900 .addReg(LHS2).addReg(RHS2)
7901 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7904 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7905 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7906 if (MI->getOperand(0).getImm() == ARMCC::NE)
7907 std::swap(destMBB, exitMBB);
7909 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7910 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7912 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7914 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7916 MI->eraseFromParent(); // The pseudo instruction is gone now.
7920 case ARM::Int_eh_sjlj_setjmp:
7921 case ARM::Int_eh_sjlj_setjmp_nofp:
7922 case ARM::tInt_eh_sjlj_setjmp:
7923 case ARM::t2Int_eh_sjlj_setjmp:
7924 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7927 case ARM::Int_eh_sjlj_setup_dispatch:
7928 EmitSjLjDispatchBlock(MI, BB);
7933 // To insert an ABS instruction, we have to insert the
7934 // diamond control-flow pattern. The incoming instruction knows the
7935 // source vreg to test against 0, the destination vreg to set,
7936 // the condition code register to branch on, the
7937 // true/false values to select between, and a branch opcode to use.
7942 // BCC (branch to SinkBB if V0 >= 0)
7943 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7944 // SinkBB: V1 = PHI(V2, V3)
7945 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7946 MachineFunction::iterator BBI = BB;
7948 MachineFunction *Fn = BB->getParent();
7949 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7950 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7951 Fn->insert(BBI, RSBBB);
7952 Fn->insert(BBI, SinkBB);
7954 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7955 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7956 bool ABSSrcKIll = MI->getOperand(1).isKill();
7957 bool isThumb2 = Subtarget->isThumb2();
7958 MachineRegisterInfo &MRI = Fn->getRegInfo();
7959 // In Thumb mode S must not be specified if source register is the SP or
7960 // PC and if destination register is the SP, so restrict register class
7961 unsigned NewRsbDstReg =
7962 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7964 // Transfer the remainder of BB and its successor edges to sinkMBB.
7965 SinkBB->splice(SinkBB->begin(), BB,
7966 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7967 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7969 BB->addSuccessor(RSBBB);
7970 BB->addSuccessor(SinkBB);
7972 // fall through to SinkMBB
7973 RSBBB->addSuccessor(SinkBB);
7975 // insert a cmp at the end of BB
7976 AddDefaultPred(BuildMI(BB, dl,
7977 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7978 .addReg(ABSSrcReg).addImm(0));
7980 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7982 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7983 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7985 // insert rsbri in RSBBB
7986 // Note: BCC and rsbri will be converted into predicated rsbmi
7987 // by if-conversion pass
7988 BuildMI(*RSBBB, RSBBB->begin(), dl,
7989 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7990 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7991 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7993 // insert PHI in SinkBB,
7994 // reuse ABSDstReg to not change uses of ABS instruction
7995 BuildMI(*SinkBB, SinkBB->begin(), dl,
7996 TII->get(ARM::PHI), ABSDstReg)
7997 .addReg(NewRsbDstReg).addMBB(RSBBB)
7998 .addReg(ABSSrcReg).addMBB(BB);
8000 // remove ABS instruction
8001 MI->eraseFromParent();
8003 // return last added BB
8006 case ARM::COPY_STRUCT_BYVAL_I32:
8008 return EmitStructByval(MI, BB);
8009 case ARM::WIN__CHKSTK:
8010 return EmitLowered__chkstk(MI, BB);
8014 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8015 SDNode *Node) const {
8016 const MCInstrDesc *MCID = &MI->getDesc();
8017 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8018 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8019 // operand is still set to noreg. If needed, set the optional operand's
8020 // register to CPSR, and remove the redundant implicit def.
8022 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8024 // Rename pseudo opcodes.
8025 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8027 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8028 MCID = &TII->get(NewOpc);
8030 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8031 "converted opcode should be the same except for cc_out");
8035 // Add the optional cc_out operand
8036 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8038 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8040 // Any ARM instruction that sets the 's' bit should specify an optional
8041 // "cc_out" operand in the last operand position.
8042 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8043 assert(!NewOpc && "Optional cc_out operand required");
8046 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8047 // since we already have an optional CPSR def.
8048 bool definesCPSR = false;
8049 bool deadCPSR = false;
8050 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8052 const MachineOperand &MO = MI->getOperand(i);
8053 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8057 MI->RemoveOperand(i);
8062 assert(!NewOpc && "Optional cc_out operand required");
8065 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8067 assert(!MI->getOperand(ccOutIdx).getReg() &&
8068 "expect uninitialized optional cc_out operand");
8072 // If this instruction was defined with an optional CPSR def and its dag node
8073 // had a live implicit CPSR def, then activate the optional CPSR def.
8074 MachineOperand &MO = MI->getOperand(ccOutIdx);
8075 MO.setReg(ARM::CPSR);
8079 //===----------------------------------------------------------------------===//
8080 // ARM Optimization Hooks
8081 //===----------------------------------------------------------------------===//
8083 // Helper function that checks if N is a null or all ones constant.
8084 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8085 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8088 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8091 // Return true if N is conditionally 0 or all ones.
8092 // Detects these expressions where cc is an i1 value:
8094 // (select cc 0, y) [AllOnes=0]
8095 // (select cc y, 0) [AllOnes=0]
8096 // (zext cc) [AllOnes=0]
8097 // (sext cc) [AllOnes=0/1]
8098 // (select cc -1, y) [AllOnes=1]
8099 // (select cc y, -1) [AllOnes=1]
8101 // Invert is set when N is the null/all ones constant when CC is false.
8102 // OtherOp is set to the alternative value of N.
8103 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8104 SDValue &CC, bool &Invert,
8106 SelectionDAG &DAG) {
8107 switch (N->getOpcode()) {
8108 default: return false;
8110 CC = N->getOperand(0);
8111 SDValue N1 = N->getOperand(1);
8112 SDValue N2 = N->getOperand(2);
8113 if (isZeroOrAllOnes(N1, AllOnes)) {
8118 if (isZeroOrAllOnes(N2, AllOnes)) {
8125 case ISD::ZERO_EXTEND:
8126 // (zext cc) can never be the all ones value.
8130 case ISD::SIGN_EXTEND: {
8132 EVT VT = N->getValueType(0);
8133 CC = N->getOperand(0);
8134 if (CC.getValueType() != MVT::i1)
8138 // When looking for an AllOnes constant, N is an sext, and the 'other'
8140 OtherOp = DAG.getConstant(0, dl, VT);
8141 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8142 // When looking for a 0 constant, N can be zext or sext.
8143 OtherOp = DAG.getConstant(1, dl, VT);
8145 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8152 // Combine a constant select operand into its use:
8154 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8155 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8156 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8157 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8158 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8160 // The transform is rejected if the select doesn't have a constant operand that
8161 // is null, or all ones when AllOnes is set.
8163 // Also recognize sext/zext from i1:
8165 // (add (zext cc), x) -> (select cc (add x, 1), x)
8166 // (add (sext cc), x) -> (select cc (add x, -1), x)
8168 // These transformations eventually create predicated instructions.
8170 // @param N The node to transform.
8171 // @param Slct The N operand that is a select.
8172 // @param OtherOp The other N operand (x above).
8173 // @param DCI Context.
8174 // @param AllOnes Require the select constant to be all ones instead of null.
8175 // @returns The new node, or SDValue() on failure.
8177 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8178 TargetLowering::DAGCombinerInfo &DCI,
8179 bool AllOnes = false) {
8180 SelectionDAG &DAG = DCI.DAG;
8181 EVT VT = N->getValueType(0);
8182 SDValue NonConstantVal;
8185 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8186 NonConstantVal, DAG))
8189 // Slct is now know to be the desired identity constant when CC is true.
8190 SDValue TrueVal = OtherOp;
8191 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8192 OtherOp, NonConstantVal);
8193 // Unless SwapSelectOps says CC should be false.
8195 std::swap(TrueVal, FalseVal);
8197 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8198 CCOp, TrueVal, FalseVal);
8201 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8203 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8204 TargetLowering::DAGCombinerInfo &DCI) {
8205 SDValue N0 = N->getOperand(0);
8206 SDValue N1 = N->getOperand(1);
8207 if (N0.getNode()->hasOneUse()) {
8208 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8209 if (Result.getNode())
8212 if (N1.getNode()->hasOneUse()) {
8213 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8214 if (Result.getNode())
8220 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8221 // (only after legalization).
8222 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8223 TargetLowering::DAGCombinerInfo &DCI,
8224 const ARMSubtarget *Subtarget) {
8226 // Only perform optimization if after legalize, and if NEON is available. We
8227 // also expected both operands to be BUILD_VECTORs.
8228 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8229 || N0.getOpcode() != ISD::BUILD_VECTOR
8230 || N1.getOpcode() != ISD::BUILD_VECTOR)
8233 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8234 EVT VT = N->getValueType(0);
8235 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8238 // Check that the vector operands are of the right form.
8239 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8240 // operands, where N is the size of the formed vector.
8241 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8242 // index such that we have a pair wise add pattern.
8244 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8245 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8247 SDValue Vec = N0->getOperand(0)->getOperand(0);
8248 SDNode *V = Vec.getNode();
8249 unsigned nextIndex = 0;
8251 // For each operands to the ADD which are BUILD_VECTORs,
8252 // check to see if each of their operands are an EXTRACT_VECTOR with
8253 // the same vector and appropriate index.
8254 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8255 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8256 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8258 SDValue ExtVec0 = N0->getOperand(i);
8259 SDValue ExtVec1 = N1->getOperand(i);
8261 // First operand is the vector, verify its the same.
8262 if (V != ExtVec0->getOperand(0).getNode() ||
8263 V != ExtVec1->getOperand(0).getNode())
8266 // Second is the constant, verify its correct.
8267 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8268 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8270 // For the constant, we want to see all the even or all the odd.
8271 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8272 || C1->getZExtValue() != nextIndex+1)
8281 // Create VPADDL node.
8282 SelectionDAG &DAG = DCI.DAG;
8283 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8287 // Build operand list.
8288 SmallVector<SDValue, 8> Ops;
8289 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8290 TLI.getPointerTy(DAG.getDataLayout())));
8292 // Input is the vector.
8295 // Get widened type and narrowed type.
8297 unsigned numElem = VT.getVectorNumElements();
8299 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8300 switch (inputLaneType.getSimpleVT().SimpleTy) {
8301 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8302 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8303 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8305 llvm_unreachable("Invalid vector element type for padd optimization.");
8308 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8309 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8310 return DAG.getNode(ExtOp, dl, VT, tmp);
8313 static SDValue findMUL_LOHI(SDValue V) {
8314 if (V->getOpcode() == ISD::UMUL_LOHI ||
8315 V->getOpcode() == ISD::SMUL_LOHI)
8320 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8321 TargetLowering::DAGCombinerInfo &DCI,
8322 const ARMSubtarget *Subtarget) {
8324 if (Subtarget->isThumb1Only()) return SDValue();
8326 // Only perform the checks after legalize when the pattern is available.
8327 if (DCI.isBeforeLegalize()) return SDValue();
8329 // Look for multiply add opportunities.
8330 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8331 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8332 // a glue link from the first add to the second add.
8333 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8334 // a S/UMLAL instruction.
8337 // / \ [no multiline comment]
8343 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8344 SDValue AddcOp0 = AddcNode->getOperand(0);
8345 SDValue AddcOp1 = AddcNode->getOperand(1);
8347 // Check if the two operands are from the same mul_lohi node.
8348 if (AddcOp0.getNode() == AddcOp1.getNode())
8351 assert(AddcNode->getNumValues() == 2 &&
8352 AddcNode->getValueType(0) == MVT::i32 &&
8353 "Expect ADDC with two result values. First: i32");
8355 // Check that we have a glued ADDC node.
8356 if (AddcNode->getValueType(1) != MVT::Glue)
8359 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8360 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8361 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8362 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8363 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8366 // Look for the glued ADDE.
8367 SDNode* AddeNode = AddcNode->getGluedUser();
8371 // Make sure it is really an ADDE.
8372 if (AddeNode->getOpcode() != ISD::ADDE)
8375 assert(AddeNode->getNumOperands() == 3 &&
8376 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8377 "ADDE node has the wrong inputs");
8379 // Check for the triangle shape.
8380 SDValue AddeOp0 = AddeNode->getOperand(0);
8381 SDValue AddeOp1 = AddeNode->getOperand(1);
8383 // Make sure that the ADDE operands are not coming from the same node.
8384 if (AddeOp0.getNode() == AddeOp1.getNode())
8387 // Find the MUL_LOHI node walking up ADDE's operands.
8388 bool IsLeftOperandMUL = false;
8389 SDValue MULOp = findMUL_LOHI(AddeOp0);
8390 if (MULOp == SDValue())
8391 MULOp = findMUL_LOHI(AddeOp1);
8393 IsLeftOperandMUL = true;
8394 if (MULOp == SDValue())
8397 // Figure out the right opcode.
8398 unsigned Opc = MULOp->getOpcode();
8399 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8401 // Figure out the high and low input values to the MLAL node.
8402 SDValue* HiAdd = nullptr;
8403 SDValue* LoMul = nullptr;
8404 SDValue* LowAdd = nullptr;
8406 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8407 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8410 if (IsLeftOperandMUL)
8416 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8417 // whose low result is fed to the ADDC we are checking.
8419 if (AddcOp0 == MULOp.getValue(0)) {
8423 if (AddcOp1 == MULOp.getValue(0)) {
8431 // Create the merged node.
8432 SelectionDAG &DAG = DCI.DAG;
8434 // Build operand list.
8435 SmallVector<SDValue, 8> Ops;
8436 Ops.push_back(LoMul->getOperand(0));
8437 Ops.push_back(LoMul->getOperand(1));
8438 Ops.push_back(*LowAdd);
8439 Ops.push_back(*HiAdd);
8441 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8442 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8444 // Replace the ADDs' nodes uses by the MLA node's values.
8445 SDValue HiMLALResult(MLALNode.getNode(), 1);
8446 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8448 SDValue LoMLALResult(MLALNode.getNode(), 0);
8449 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8451 // Return original node to notify the driver to stop replacing.
8452 SDValue resNode(AddcNode, 0);
8456 /// PerformADDCCombine - Target-specific dag combine transform from
8457 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8458 static SDValue PerformADDCCombine(SDNode *N,
8459 TargetLowering::DAGCombinerInfo &DCI,
8460 const ARMSubtarget *Subtarget) {
8462 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8466 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8467 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8468 /// called with the default operands, and if that fails, with commuted
8470 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8471 TargetLowering::DAGCombinerInfo &DCI,
8472 const ARMSubtarget *Subtarget){
8474 // Attempt to create vpaddl for this add.
8475 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8476 if (Result.getNode())
8479 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8480 if (N0.getNode()->hasOneUse()) {
8481 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8482 if (Result.getNode()) return Result;
8487 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8489 static SDValue PerformADDCombine(SDNode *N,
8490 TargetLowering::DAGCombinerInfo &DCI,
8491 const ARMSubtarget *Subtarget) {
8492 SDValue N0 = N->getOperand(0);
8493 SDValue N1 = N->getOperand(1);
8495 // First try with the default operand order.
8496 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8497 if (Result.getNode())
8500 // If that didn't work, try again with the operands commuted.
8501 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8504 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8506 static SDValue PerformSUBCombine(SDNode *N,
8507 TargetLowering::DAGCombinerInfo &DCI) {
8508 SDValue N0 = N->getOperand(0);
8509 SDValue N1 = N->getOperand(1);
8511 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8512 if (N1.getNode()->hasOneUse()) {
8513 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8514 if (Result.getNode()) return Result;
8520 /// PerformVMULCombine
8521 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8522 /// special multiplier accumulator forwarding.
8528 // However, for (A + B) * (A + B),
8535 static SDValue PerformVMULCombine(SDNode *N,
8536 TargetLowering::DAGCombinerInfo &DCI,
8537 const ARMSubtarget *Subtarget) {
8538 if (!Subtarget->hasVMLxForwarding())
8541 SelectionDAG &DAG = DCI.DAG;
8542 SDValue N0 = N->getOperand(0);
8543 SDValue N1 = N->getOperand(1);
8544 unsigned Opcode = N0.getOpcode();
8545 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8546 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8547 Opcode = N1.getOpcode();
8548 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8549 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8557 EVT VT = N->getValueType(0);
8559 SDValue N00 = N0->getOperand(0);
8560 SDValue N01 = N0->getOperand(1);
8561 return DAG.getNode(Opcode, DL, VT,
8562 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8563 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8566 static SDValue PerformMULCombine(SDNode *N,
8567 TargetLowering::DAGCombinerInfo &DCI,
8568 const ARMSubtarget *Subtarget) {
8569 SelectionDAG &DAG = DCI.DAG;
8571 if (Subtarget->isThumb1Only())
8574 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8577 EVT VT = N->getValueType(0);
8578 if (VT.is64BitVector() || VT.is128BitVector())
8579 return PerformVMULCombine(N, DCI, Subtarget);
8583 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8587 int64_t MulAmt = C->getSExtValue();
8588 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8590 ShiftAmt = ShiftAmt & (32 - 1);
8591 SDValue V = N->getOperand(0);
8595 MulAmt >>= ShiftAmt;
8598 if (isPowerOf2_32(MulAmt - 1)) {
8599 // (mul x, 2^N + 1) => (add (shl x, N), x)
8600 Res = DAG.getNode(ISD::ADD, DL, VT,
8602 DAG.getNode(ISD::SHL, DL, VT,
8604 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8606 } else if (isPowerOf2_32(MulAmt + 1)) {
8607 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8608 Res = DAG.getNode(ISD::SUB, DL, VT,
8609 DAG.getNode(ISD::SHL, DL, VT,
8611 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8617 uint64_t MulAmtAbs = -MulAmt;
8618 if (isPowerOf2_32(MulAmtAbs + 1)) {
8619 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8620 Res = DAG.getNode(ISD::SUB, DL, VT,
8622 DAG.getNode(ISD::SHL, DL, VT,
8624 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8626 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8627 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8628 Res = DAG.getNode(ISD::ADD, DL, VT,
8630 DAG.getNode(ISD::SHL, DL, VT,
8632 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8634 Res = DAG.getNode(ISD::SUB, DL, VT,
8635 DAG.getConstant(0, DL, MVT::i32), Res);
8642 Res = DAG.getNode(ISD::SHL, DL, VT,
8643 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8645 // Do not add new nodes to DAG combiner worklist.
8646 DCI.CombineTo(N, Res, false);
8650 static SDValue PerformANDCombine(SDNode *N,
8651 TargetLowering::DAGCombinerInfo &DCI,
8652 const ARMSubtarget *Subtarget) {
8654 // Attempt to use immediate-form VBIC
8655 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8657 EVT VT = N->getValueType(0);
8658 SelectionDAG &DAG = DCI.DAG;
8660 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8663 APInt SplatBits, SplatUndef;
8664 unsigned SplatBitSize;
8667 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8668 if (SplatBitSize <= 64) {
8670 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8671 SplatUndef.getZExtValue(), SplatBitSize,
8672 DAG, dl, VbicVT, VT.is128BitVector(),
8674 if (Val.getNode()) {
8676 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8677 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8678 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8683 if (!Subtarget->isThumb1Only()) {
8684 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8685 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8686 if (Result.getNode())
8693 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8694 static SDValue PerformORCombine(SDNode *N,
8695 TargetLowering::DAGCombinerInfo &DCI,
8696 const ARMSubtarget *Subtarget) {
8697 // Attempt to use immediate-form VORR
8698 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8700 EVT VT = N->getValueType(0);
8701 SelectionDAG &DAG = DCI.DAG;
8703 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8706 APInt SplatBits, SplatUndef;
8707 unsigned SplatBitSize;
8709 if (BVN && Subtarget->hasNEON() &&
8710 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8711 if (SplatBitSize <= 64) {
8713 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8714 SplatUndef.getZExtValue(), SplatBitSize,
8715 DAG, dl, VorrVT, VT.is128BitVector(),
8717 if (Val.getNode()) {
8719 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8720 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8721 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8726 if (!Subtarget->isThumb1Only()) {
8727 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8728 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8729 if (Result.getNode())
8733 // The code below optimizes (or (and X, Y), Z).
8734 // The AND operand needs to have a single user to make these optimizations
8736 SDValue N0 = N->getOperand(0);
8737 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8739 SDValue N1 = N->getOperand(1);
8741 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8742 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8743 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8745 unsigned SplatBitSize;
8748 APInt SplatBits0, SplatBits1;
8749 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8750 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8751 // Ensure that the second operand of both ands are constants
8752 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8753 HasAnyUndefs) && !HasAnyUndefs) {
8754 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8755 HasAnyUndefs) && !HasAnyUndefs) {
8756 // Ensure that the bit width of the constants are the same and that
8757 // the splat arguments are logical inverses as per the pattern we
8758 // are trying to simplify.
8759 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8760 SplatBits0 == ~SplatBits1) {
8761 // Canonicalize the vector type to make instruction selection
8763 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8764 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8768 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8774 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8777 // BFI is only available on V6T2+
8778 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8782 // 1) or (and A, mask), val => ARMbfi A, val, mask
8783 // iff (val & mask) == val
8785 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8786 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8787 // && mask == ~mask2
8788 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8789 // && ~mask == mask2
8790 // (i.e., copy a bitfield value into another bitfield of the same width)
8795 SDValue N00 = N0.getOperand(0);
8797 // The value and the mask need to be constants so we can verify this is
8798 // actually a bitfield set. If the mask is 0xffff, we can do better
8799 // via a movt instruction, so don't use BFI in that case.
8800 SDValue MaskOp = N0.getOperand(1);
8801 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8804 unsigned Mask = MaskC->getZExtValue();
8808 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8809 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8811 unsigned Val = N1C->getZExtValue();
8812 if ((Val & ~Mask) != Val)
8815 if (ARM::isBitFieldInvertedMask(Mask)) {
8816 Val >>= countTrailingZeros(~Mask);
8818 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8819 DAG.getConstant(Val, DL, MVT::i32),
8820 DAG.getConstant(Mask, DL, MVT::i32));
8822 // Do not add new nodes to DAG combiner worklist.
8823 DCI.CombineTo(N, Res, false);
8826 } else if (N1.getOpcode() == ISD::AND) {
8827 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8828 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8831 unsigned Mask2 = N11C->getZExtValue();
8833 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8835 if (ARM::isBitFieldInvertedMask(Mask) &&
8837 // The pack halfword instruction works better for masks that fit it,
8838 // so use that when it's available.
8839 if (Subtarget->hasT2ExtractPack() &&
8840 (Mask == 0xffff || Mask == 0xffff0000))
8843 unsigned amt = countTrailingZeros(Mask2);
8844 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8845 DAG.getConstant(amt, DL, MVT::i32));
8846 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8847 DAG.getConstant(Mask, DL, MVT::i32));
8848 // Do not add new nodes to DAG combiner worklist.
8849 DCI.CombineTo(N, Res, false);
8851 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8853 // The pack halfword instruction works better for masks that fit it,
8854 // so use that when it's available.
8855 if (Subtarget->hasT2ExtractPack() &&
8856 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8859 unsigned lsb = countTrailingZeros(Mask);
8860 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8861 DAG.getConstant(lsb, DL, MVT::i32));
8862 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8863 DAG.getConstant(Mask2, DL, MVT::i32));
8864 // Do not add new nodes to DAG combiner worklist.
8865 DCI.CombineTo(N, Res, false);
8870 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8871 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8872 ARM::isBitFieldInvertedMask(~Mask)) {
8873 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8874 // where lsb(mask) == #shamt and masked bits of B are known zero.
8875 SDValue ShAmt = N00.getOperand(1);
8876 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8877 unsigned LSB = countTrailingZeros(Mask);
8881 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8882 DAG.getConstant(~Mask, DL, MVT::i32));
8884 // Do not add new nodes to DAG combiner worklist.
8885 DCI.CombineTo(N, Res, false);
8891 static SDValue PerformXORCombine(SDNode *N,
8892 TargetLowering::DAGCombinerInfo &DCI,
8893 const ARMSubtarget *Subtarget) {
8894 EVT VT = N->getValueType(0);
8895 SelectionDAG &DAG = DCI.DAG;
8897 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8900 if (!Subtarget->isThumb1Only()) {
8901 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8902 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8903 if (Result.getNode())
8910 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8911 /// the bits being cleared by the AND are not demanded by the BFI.
8912 static SDValue PerformBFICombine(SDNode *N,
8913 TargetLowering::DAGCombinerInfo &DCI) {
8914 SDValue N1 = N->getOperand(1);
8915 if (N1.getOpcode() == ISD::AND) {
8916 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8919 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8920 unsigned LSB = countTrailingZeros(~InvMask);
8921 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8923 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8924 "undefined behavior");
8925 unsigned Mask = (1u << Width) - 1;
8926 unsigned Mask2 = N11C->getZExtValue();
8927 if ((Mask & (~Mask2)) == 0)
8928 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8929 N->getOperand(0), N1.getOperand(0),
8935 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8936 /// ARMISD::VMOVRRD.
8937 static SDValue PerformVMOVRRDCombine(SDNode *N,
8938 TargetLowering::DAGCombinerInfo &DCI,
8939 const ARMSubtarget *Subtarget) {
8940 // vmovrrd(vmovdrr x, y) -> x,y
8941 SDValue InDouble = N->getOperand(0);
8942 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8943 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8945 // vmovrrd(load f64) -> (load i32), (load i32)
8946 SDNode *InNode = InDouble.getNode();
8947 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8948 InNode->getValueType(0) == MVT::f64 &&
8949 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8950 !cast<LoadSDNode>(InNode)->isVolatile()) {
8951 // TODO: Should this be done for non-FrameIndex operands?
8952 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8954 SelectionDAG &DAG = DCI.DAG;
8956 SDValue BasePtr = LD->getBasePtr();
8957 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8958 LD->getPointerInfo(), LD->isVolatile(),
8959 LD->isNonTemporal(), LD->isInvariant(),
8960 LD->getAlignment());
8962 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8963 DAG.getConstant(4, DL, MVT::i32));
8964 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8965 LD->getPointerInfo(), LD->isVolatile(),
8966 LD->isNonTemporal(), LD->isInvariant(),
8967 std::min(4U, LD->getAlignment() / 2));
8969 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8970 if (DCI.DAG.getDataLayout().isBigEndian())
8971 std::swap (NewLD1, NewLD2);
8972 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8979 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8980 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8981 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8982 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8983 SDValue Op0 = N->getOperand(0);
8984 SDValue Op1 = N->getOperand(1);
8985 if (Op0.getOpcode() == ISD::BITCAST)
8986 Op0 = Op0.getOperand(0);
8987 if (Op1.getOpcode() == ISD::BITCAST)
8988 Op1 = Op1.getOperand(0);
8989 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8990 Op0.getNode() == Op1.getNode() &&
8991 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8992 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8993 N->getValueType(0), Op0.getOperand(0));
8997 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8998 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8999 /// i64 vector to have f64 elements, since the value can then be loaded
9000 /// directly into a VFP register.
9001 static bool hasNormalLoadOperand(SDNode *N) {
9002 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9003 for (unsigned i = 0; i < NumElts; ++i) {
9004 SDNode *Elt = N->getOperand(i).getNode();
9005 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9011 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9012 /// ISD::BUILD_VECTOR.
9013 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9014 TargetLowering::DAGCombinerInfo &DCI,
9015 const ARMSubtarget *Subtarget) {
9016 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9017 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9018 // into a pair of GPRs, which is fine when the value is used as a scalar,
9019 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9020 SelectionDAG &DAG = DCI.DAG;
9021 if (N->getNumOperands() == 2) {
9022 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9027 // Load i64 elements as f64 values so that type legalization does not split
9028 // them up into i32 values.
9029 EVT VT = N->getValueType(0);
9030 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9033 SmallVector<SDValue, 8> Ops;
9034 unsigned NumElts = VT.getVectorNumElements();
9035 for (unsigned i = 0; i < NumElts; ++i) {
9036 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9038 // Make the DAGCombiner fold the bitcast.
9039 DCI.AddToWorklist(V.getNode());
9041 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9042 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9043 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9046 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9048 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9049 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9050 // At that time, we may have inserted bitcasts from integer to float.
9051 // If these bitcasts have survived DAGCombine, change the lowering of this
9052 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9053 // force to use floating point types.
9055 // Make sure we can change the type of the vector.
9056 // This is possible iff:
9057 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9058 // 1.1. Vector is used only once.
9059 // 1.2. Use is a bit convert to an integer type.
9060 // 2. The size of its operands are 32-bits (64-bits are not legal).
9061 EVT VT = N->getValueType(0);
9062 EVT EltVT = VT.getVectorElementType();
9064 // Check 1.1. and 2.
9065 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9068 // By construction, the input type must be float.
9069 assert(EltVT == MVT::f32 && "Unexpected type!");
9072 SDNode *Use = *N->use_begin();
9073 if (Use->getOpcode() != ISD::BITCAST ||
9074 Use->getValueType(0).isFloatingPoint())
9077 // Check profitability.
9078 // Model is, if more than half of the relevant operands are bitcast from
9079 // i32, turn the build_vector into a sequence of insert_vector_elt.
9080 // Relevant operands are everything that is not statically
9081 // (i.e., at compile time) bitcasted.
9082 unsigned NumOfBitCastedElts = 0;
9083 unsigned NumElts = VT.getVectorNumElements();
9084 unsigned NumOfRelevantElts = NumElts;
9085 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9086 SDValue Elt = N->getOperand(Idx);
9087 if (Elt->getOpcode() == ISD::BITCAST) {
9088 // Assume only bit cast to i32 will go away.
9089 if (Elt->getOperand(0).getValueType() == MVT::i32)
9090 ++NumOfBitCastedElts;
9091 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9092 // Constants are statically casted, thus do not count them as
9093 // relevant operands.
9094 --NumOfRelevantElts;
9097 // Check if more than half of the elements require a non-free bitcast.
9098 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9101 SelectionDAG &DAG = DCI.DAG;
9102 // Create the new vector type.
9103 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9104 // Check if the type is legal.
9105 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9106 if (!TLI.isTypeLegal(VecVT))
9110 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9111 // => BITCAST INSERT_VECTOR_ELT
9112 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9114 SDValue Vec = DAG.getUNDEF(VecVT);
9116 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9117 SDValue V = N->getOperand(Idx);
9118 if (V.getOpcode() == ISD::UNDEF)
9120 if (V.getOpcode() == ISD::BITCAST &&
9121 V->getOperand(0).getValueType() == MVT::i32)
9122 // Fold obvious case.
9123 V = V.getOperand(0);
9125 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9126 // Make the DAGCombiner fold the bitcasts.
9127 DCI.AddToWorklist(V.getNode());
9129 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9130 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9132 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9133 // Make the DAGCombiner fold the bitcasts.
9134 DCI.AddToWorklist(Vec.getNode());
9138 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9139 /// ISD::INSERT_VECTOR_ELT.
9140 static SDValue PerformInsertEltCombine(SDNode *N,
9141 TargetLowering::DAGCombinerInfo &DCI) {
9142 // Bitcast an i64 load inserted into a vector to f64.
9143 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9144 EVT VT = N->getValueType(0);
9145 SDNode *Elt = N->getOperand(1).getNode();
9146 if (VT.getVectorElementType() != MVT::i64 ||
9147 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9150 SelectionDAG &DAG = DCI.DAG;
9152 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9153 VT.getVectorNumElements());
9154 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9155 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9156 // Make the DAGCombiner fold the bitcasts.
9157 DCI.AddToWorklist(Vec.getNode());
9158 DCI.AddToWorklist(V.getNode());
9159 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9160 Vec, V, N->getOperand(2));
9161 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9164 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9165 /// ISD::VECTOR_SHUFFLE.
9166 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9167 // The LLVM shufflevector instruction does not require the shuffle mask
9168 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9169 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9170 // operands do not match the mask length, they are extended by concatenating
9171 // them with undef vectors. That is probably the right thing for other
9172 // targets, but for NEON it is better to concatenate two double-register
9173 // size vector operands into a single quad-register size vector. Do that
9174 // transformation here:
9175 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9176 // shuffle(concat(v1, v2), undef)
9177 SDValue Op0 = N->getOperand(0);
9178 SDValue Op1 = N->getOperand(1);
9179 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9180 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9181 Op0.getNumOperands() != 2 ||
9182 Op1.getNumOperands() != 2)
9184 SDValue Concat0Op1 = Op0.getOperand(1);
9185 SDValue Concat1Op1 = Op1.getOperand(1);
9186 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9187 Concat1Op1.getOpcode() != ISD::UNDEF)
9189 // Skip the transformation if any of the types are illegal.
9190 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9191 EVT VT = N->getValueType(0);
9192 if (!TLI.isTypeLegal(VT) ||
9193 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9194 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9197 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9198 Op0.getOperand(0), Op1.getOperand(0));
9199 // Translate the shuffle mask.
9200 SmallVector<int, 16> NewMask;
9201 unsigned NumElts = VT.getVectorNumElements();
9202 unsigned HalfElts = NumElts/2;
9203 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9204 for (unsigned n = 0; n < NumElts; ++n) {
9205 int MaskElt = SVN->getMaskElt(n);
9207 if (MaskElt < (int)HalfElts)
9209 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9210 NewElt = HalfElts + MaskElt - NumElts;
9211 NewMask.push_back(NewElt);
9213 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9214 DAG.getUNDEF(VT), NewMask.data());
9217 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9218 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9219 /// base address updates.
9220 /// For generic load/stores, the memory type is assumed to be a vector.
9221 /// The caller is assumed to have checked legality.
9222 static SDValue CombineBaseUpdate(SDNode *N,
9223 TargetLowering::DAGCombinerInfo &DCI) {
9224 SelectionDAG &DAG = DCI.DAG;
9225 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9226 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9227 const bool isStore = N->getOpcode() == ISD::STORE;
9228 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9229 SDValue Addr = N->getOperand(AddrOpIdx);
9230 MemSDNode *MemN = cast<MemSDNode>(N);
9233 // Search for a use of the address operand that is an increment.
9234 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9235 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9237 if (User->getOpcode() != ISD::ADD ||
9238 UI.getUse().getResNo() != Addr.getResNo())
9241 // Check that the add is independent of the load/store. Otherwise, folding
9242 // it would create a cycle.
9243 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9246 // Find the new opcode for the updating load/store.
9247 bool isLoadOp = true;
9248 bool isLaneOp = false;
9249 unsigned NewOpc = 0;
9250 unsigned NumVecs = 0;
9252 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9254 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9255 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9257 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9259 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9261 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9263 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9264 NumVecs = 2; isLaneOp = true; break;
9265 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9266 NumVecs = 3; isLaneOp = true; break;
9267 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9268 NumVecs = 4; isLaneOp = true; break;
9269 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9270 NumVecs = 1; isLoadOp = false; break;
9271 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9272 NumVecs = 2; isLoadOp = false; break;
9273 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9274 NumVecs = 3; isLoadOp = false; break;
9275 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9276 NumVecs = 4; isLoadOp = false; break;
9277 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9278 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9279 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9280 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9281 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9282 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9286 switch (N->getOpcode()) {
9287 default: llvm_unreachable("unexpected opcode for Neon base update");
9288 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9289 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9290 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9291 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9292 NumVecs = 1; isLaneOp = false; break;
9293 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9294 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9298 // Find the size of memory referenced by the load/store.
9301 VecTy = N->getValueType(0);
9302 } else if (isIntrinsic) {
9303 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9305 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9306 VecTy = N->getOperand(1).getValueType();
9309 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9311 NumBytes /= VecTy.getVectorNumElements();
9313 // If the increment is a constant, it must match the memory ref size.
9314 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9315 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9316 uint64_t IncVal = CInc->getZExtValue();
9317 if (IncVal != NumBytes)
9319 } else if (NumBytes >= 3 * 16) {
9320 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9321 // separate instructions that make it harder to use a non-constant update.
9325 // OK, we found an ADD we can fold into the base update.
9326 // Now, create a _UPD node, taking care of not breaking alignment.
9328 EVT AlignedVecTy = VecTy;
9329 unsigned Alignment = MemN->getAlignment();
9331 // If this is a less-than-standard-aligned load/store, change the type to
9332 // match the standard alignment.
9333 // The alignment is overlooked when selecting _UPD variants; and it's
9334 // easier to introduce bitcasts here than fix that.
9335 // There are 3 ways to get to this base-update combine:
9336 // - intrinsics: they are assumed to be properly aligned (to the standard
9337 // alignment of the memory type), so we don't need to do anything.
9338 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9339 // intrinsics, so, likewise, there's nothing to do.
9340 // - generic load/store instructions: the alignment is specified as an
9341 // explicit operand, rather than implicitly as the standard alignment
9342 // of the memory type (like the intrisics). We need to change the
9343 // memory type to match the explicit alignment. That way, we don't
9344 // generate non-standard-aligned ARMISD::VLDx nodes.
9345 if (isa<LSBaseSDNode>(N)) {
9348 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9349 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9350 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9351 assert(!isLaneOp && "Unexpected generic load/store lane.");
9352 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9353 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9355 // Don't set an explicit alignment on regular load/stores that we want
9356 // to transform to VLD/VST 1_UPD nodes.
9357 // This matches the behavior of regular load/stores, which only get an
9358 // explicit alignment if the MMO alignment is larger than the standard
9359 // alignment of the memory type.
9360 // Intrinsics, however, always get an explicit alignment, set to the
9361 // alignment of the MMO.
9365 // Create the new updating load/store node.
9366 // First, create an SDVTList for the new updating node's results.
9368 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9370 for (n = 0; n < NumResultVecs; ++n)
9371 Tys[n] = AlignedVecTy;
9372 Tys[n++] = MVT::i32;
9373 Tys[n] = MVT::Other;
9374 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9376 // Then, gather the new node's operands.
9377 SmallVector<SDValue, 8> Ops;
9378 Ops.push_back(N->getOperand(0)); // incoming chain
9379 Ops.push_back(N->getOperand(AddrOpIdx));
9382 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9383 // Try to match the intrinsic's signature
9384 Ops.push_back(StN->getValue());
9386 // Loads (and of course intrinsics) match the intrinsics' signature,
9387 // so just add all but the alignment operand.
9388 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9389 Ops.push_back(N->getOperand(i));
9392 // For all node types, the alignment operand is always the last one.
9393 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9395 // If this is a non-standard-aligned STORE, the penultimate operand is the
9396 // stored value. Bitcast it to the aligned type.
9397 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9398 SDValue &StVal = Ops[Ops.size()-2];
9399 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9402 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9404 MemN->getMemOperand());
9407 SmallVector<SDValue, 5> NewResults;
9408 for (unsigned i = 0; i < NumResultVecs; ++i)
9409 NewResults.push_back(SDValue(UpdN.getNode(), i));
9411 // If this is an non-standard-aligned LOAD, the first result is the loaded
9412 // value. Bitcast it to the expected result type.
9413 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9414 SDValue &LdVal = NewResults[0];
9415 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9418 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9419 DCI.CombineTo(N, NewResults);
9420 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9427 static SDValue PerformVLDCombine(SDNode *N,
9428 TargetLowering::DAGCombinerInfo &DCI) {
9429 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9432 return CombineBaseUpdate(N, DCI);
9435 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9436 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9437 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9439 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9440 SelectionDAG &DAG = DCI.DAG;
9441 EVT VT = N->getValueType(0);
9442 // vldN-dup instructions only support 64-bit vectors for N > 1.
9443 if (!VT.is64BitVector())
9446 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9447 SDNode *VLD = N->getOperand(0).getNode();
9448 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9450 unsigned NumVecs = 0;
9451 unsigned NewOpc = 0;
9452 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9453 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9455 NewOpc = ARMISD::VLD2DUP;
9456 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9458 NewOpc = ARMISD::VLD3DUP;
9459 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9461 NewOpc = ARMISD::VLD4DUP;
9466 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9467 // numbers match the load.
9468 unsigned VLDLaneNo =
9469 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9470 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9472 // Ignore uses of the chain result.
9473 if (UI.getUse().getResNo() == NumVecs)
9476 if (User->getOpcode() != ARMISD::VDUPLANE ||
9477 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9481 // Create the vldN-dup node.
9484 for (n = 0; n < NumVecs; ++n)
9486 Tys[n] = MVT::Other;
9487 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9488 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9489 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9490 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9491 Ops, VLDMemInt->getMemoryVT(),
9492 VLDMemInt->getMemOperand());
9495 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9497 unsigned ResNo = UI.getUse().getResNo();
9498 // Ignore uses of the chain result.
9499 if (ResNo == NumVecs)
9502 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9505 // Now the vldN-lane intrinsic is dead except for its chain result.
9506 // Update uses of the chain.
9507 std::vector<SDValue> VLDDupResults;
9508 for (unsigned n = 0; n < NumVecs; ++n)
9509 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9510 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9511 DCI.CombineTo(VLD, VLDDupResults);
9516 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9517 /// ARMISD::VDUPLANE.
9518 static SDValue PerformVDUPLANECombine(SDNode *N,
9519 TargetLowering::DAGCombinerInfo &DCI) {
9520 SDValue Op = N->getOperand(0);
9522 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9523 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9524 if (CombineVLDDUP(N, DCI))
9525 return SDValue(N, 0);
9527 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9528 // redundant. Ignore bit_converts for now; element sizes are checked below.
9529 while (Op.getOpcode() == ISD::BITCAST)
9530 Op = Op.getOperand(0);
9531 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9534 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9535 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9536 // The canonical VMOV for a zero vector uses a 32-bit element size.
9537 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9539 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9541 EVT VT = N->getValueType(0);
9542 if (EltSize > VT.getVectorElementType().getSizeInBits())
9545 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9548 static SDValue PerformLOADCombine(SDNode *N,
9549 TargetLowering::DAGCombinerInfo &DCI) {
9550 EVT VT = N->getValueType(0);
9552 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9553 if (ISD::isNormalLoad(N) && VT.isVector() &&
9554 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9555 return CombineBaseUpdate(N, DCI);
9560 /// PerformSTORECombine - Target-specific dag combine xforms for
9562 static SDValue PerformSTORECombine(SDNode *N,
9563 TargetLowering::DAGCombinerInfo &DCI) {
9564 StoreSDNode *St = cast<StoreSDNode>(N);
9565 if (St->isVolatile())
9568 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9569 // pack all of the elements in one place. Next, store to memory in fewer
9571 SDValue StVal = St->getValue();
9572 EVT VT = StVal.getValueType();
9573 if (St->isTruncatingStore() && VT.isVector()) {
9574 SelectionDAG &DAG = DCI.DAG;
9575 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9576 EVT StVT = St->getMemoryVT();
9577 unsigned NumElems = VT.getVectorNumElements();
9578 assert(StVT != VT && "Cannot truncate to the same type");
9579 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9580 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9582 // From, To sizes and ElemCount must be pow of two
9583 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9585 // We are going to use the original vector elt for storing.
9586 // Accumulated smaller vector elements must be a multiple of the store size.
9587 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9589 unsigned SizeRatio = FromEltSz / ToEltSz;
9590 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9592 // Create a type on which we perform the shuffle.
9593 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9594 NumElems*SizeRatio);
9595 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9598 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9599 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9600 for (unsigned i = 0; i < NumElems; ++i)
9601 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9602 ? (i + 1) * SizeRatio - 1
9605 // Can't shuffle using an illegal type.
9606 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9608 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9609 DAG.getUNDEF(WideVec.getValueType()),
9611 // At this point all of the data is stored at the bottom of the
9612 // register. We now need to save it to mem.
9614 // Find the largest store unit
9615 MVT StoreType = MVT::i8;
9616 for (MVT Tp : MVT::integer_valuetypes()) {
9617 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9620 // Didn't find a legal store type.
9621 if (!TLI.isTypeLegal(StoreType))
9624 // Bitcast the original vector into a vector of store-size units
9625 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9626 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9627 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9628 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9629 SmallVector<SDValue, 8> Chains;
9630 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9631 TLI.getPointerTy(DAG.getDataLayout()));
9632 SDValue BasePtr = St->getBasePtr();
9634 // Perform one or more big stores into memory.
9635 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9636 for (unsigned I = 0; I < E; I++) {
9637 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9638 StoreType, ShuffWide,
9639 DAG.getIntPtrConstant(I, DL));
9640 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9641 St->getPointerInfo(), St->isVolatile(),
9642 St->isNonTemporal(), St->getAlignment());
9643 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9645 Chains.push_back(Ch);
9647 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9650 if (!ISD::isNormalStore(St))
9653 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9654 // ARM stores of arguments in the same cache line.
9655 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9656 StVal.getNode()->hasOneUse()) {
9657 SelectionDAG &DAG = DCI.DAG;
9658 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9660 SDValue BasePtr = St->getBasePtr();
9661 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9662 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9663 BasePtr, St->getPointerInfo(), St->isVolatile(),
9664 St->isNonTemporal(), St->getAlignment());
9666 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9667 DAG.getConstant(4, DL, MVT::i32));
9668 return DAG.getStore(NewST1.getValue(0), DL,
9669 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9670 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9671 St->isNonTemporal(),
9672 std::min(4U, St->getAlignment() / 2));
9675 if (StVal.getValueType() == MVT::i64 &&
9676 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9678 // Bitcast an i64 store extracted from a vector to f64.
9679 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9680 SelectionDAG &DAG = DCI.DAG;
9682 SDValue IntVec = StVal.getOperand(0);
9683 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9684 IntVec.getValueType().getVectorNumElements());
9685 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9686 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9687 Vec, StVal.getOperand(1));
9689 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9690 // Make the DAGCombiner fold the bitcasts.
9691 DCI.AddToWorklist(Vec.getNode());
9692 DCI.AddToWorklist(ExtElt.getNode());
9693 DCI.AddToWorklist(V.getNode());
9694 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9695 St->getPointerInfo(), St->isVolatile(),
9696 St->isNonTemporal(), St->getAlignment(),
9700 // If this is a legal vector store, try to combine it into a VST1_UPD.
9701 if (ISD::isNormalStore(N) && VT.isVector() &&
9702 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9703 return CombineBaseUpdate(N, DCI);
9708 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9709 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9710 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9714 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9716 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9721 APFloat APF = C->getValueAPF();
9722 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9723 != APFloat::opOK || !isExact)
9726 c0 = (I == 0) ? cN : c0;
9727 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9734 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9735 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9736 /// when the VMUL has a constant operand that is a power of 2.
9738 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9739 /// vmul.f32 d16, d17, d16
9740 /// vcvt.s32.f32 d16, d16
9742 /// vcvt.s32.f32 d16, d16, #3
9743 static SDValue PerformVCVTCombine(SDNode *N,
9744 TargetLowering::DAGCombinerInfo &DCI,
9745 const ARMSubtarget *Subtarget) {
9746 SelectionDAG &DAG = DCI.DAG;
9747 SDValue Op = N->getOperand(0);
9749 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9750 Op.getOpcode() != ISD::FMUL)
9754 SDValue N0 = Op->getOperand(0);
9755 SDValue ConstVec = Op->getOperand(1);
9756 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9758 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9759 !isConstVecPow2(ConstVec, isSigned, C))
9762 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9763 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9764 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9765 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9767 // These instructions only exist converting from f32 to i32. We can handle
9768 // smaller integers by generating an extra truncate, but larger ones would
9769 // be lossy. We also can't handle more then 4 lanes, since these intructions
9770 // only support v2i32/v4i32 types.
9775 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9776 Intrinsic::arm_neon_vcvtfp2fxu;
9777 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9778 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9779 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9781 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9783 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9784 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9789 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9790 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9791 /// when the VDIV has a constant operand that is a power of 2.
9793 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9794 /// vcvt.f32.s32 d16, d16
9795 /// vdiv.f32 d16, d17, d16
9797 /// vcvt.f32.s32 d16, d16, #3
9798 static SDValue PerformVDIVCombine(SDNode *N,
9799 TargetLowering::DAGCombinerInfo &DCI,
9800 const ARMSubtarget *Subtarget) {
9801 SelectionDAG &DAG = DCI.DAG;
9802 SDValue Op = N->getOperand(0);
9803 unsigned OpOpcode = Op.getNode()->getOpcode();
9805 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9806 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9810 SDValue ConstVec = N->getOperand(1);
9811 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9813 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9814 !isConstVecPow2(ConstVec, isSigned, C))
9817 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9818 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9819 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9820 // These instructions only exist converting from i32 to f32. We can handle
9821 // smaller integers by generating an extra extend, but larger ones would
9827 SDValue ConvInput = Op.getOperand(0);
9828 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9829 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9830 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9831 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9834 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9835 Intrinsic::arm_neon_vcvtfxu2fp;
9836 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9838 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9839 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9842 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9843 /// operand of a vector shift operation, where all the elements of the
9844 /// build_vector must have the same constant integer value.
9845 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9846 // Ignore bit_converts.
9847 while (Op.getOpcode() == ISD::BITCAST)
9848 Op = Op.getOperand(0);
9849 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9850 APInt SplatBits, SplatUndef;
9851 unsigned SplatBitSize;
9853 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9854 HasAnyUndefs, ElementBits) ||
9855 SplatBitSize > ElementBits)
9857 Cnt = SplatBits.getSExtValue();
9861 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9862 /// operand of a vector shift left operation. That value must be in the range:
9863 /// 0 <= Value < ElementBits for a left shift; or
9864 /// 0 <= Value <= ElementBits for a long left shift.
9865 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9866 assert(VT.isVector() && "vector shift count is not a vector type");
9867 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9868 if (! getVShiftImm(Op, ElementBits, Cnt))
9870 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9873 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9874 /// operand of a vector shift right operation. For a shift opcode, the value
9875 /// is positive, but for an intrinsic the value count must be negative. The
9876 /// absolute value must be in the range:
9877 /// 1 <= |Value| <= ElementBits for a right shift; or
9878 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9879 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9881 assert(VT.isVector() && "vector shift count is not a vector type");
9882 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9883 if (! getVShiftImm(Op, ElementBits, Cnt))
9886 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9887 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9894 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9895 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9896 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9899 // Don't do anything for most intrinsics.
9902 case Intrinsic::arm_neon_vabds:
9903 if (!N->getValueType(0).isInteger())
9905 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9906 N->getOperand(1), N->getOperand(2));
9907 case Intrinsic::arm_neon_vabdu:
9908 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9909 N->getOperand(1), N->getOperand(2));
9911 // Vector shifts: check for immediate versions and lower them.
9912 // Note: This is done during DAG combining instead of DAG legalizing because
9913 // the build_vectors for 64-bit vector element shift counts are generally
9914 // not legal, and it is hard to see their values after they get legalized to
9915 // loads from a constant pool.
9916 case Intrinsic::arm_neon_vshifts:
9917 case Intrinsic::arm_neon_vshiftu:
9918 case Intrinsic::arm_neon_vrshifts:
9919 case Intrinsic::arm_neon_vrshiftu:
9920 case Intrinsic::arm_neon_vrshiftn:
9921 case Intrinsic::arm_neon_vqshifts:
9922 case Intrinsic::arm_neon_vqshiftu:
9923 case Intrinsic::arm_neon_vqshiftsu:
9924 case Intrinsic::arm_neon_vqshiftns:
9925 case Intrinsic::arm_neon_vqshiftnu:
9926 case Intrinsic::arm_neon_vqshiftnsu:
9927 case Intrinsic::arm_neon_vqrshiftns:
9928 case Intrinsic::arm_neon_vqrshiftnu:
9929 case Intrinsic::arm_neon_vqrshiftnsu: {
9930 EVT VT = N->getOperand(1).getValueType();
9932 unsigned VShiftOpc = 0;
9935 case Intrinsic::arm_neon_vshifts:
9936 case Intrinsic::arm_neon_vshiftu:
9937 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9938 VShiftOpc = ARMISD::VSHL;
9941 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9942 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9943 ARMISD::VSHRs : ARMISD::VSHRu);
9948 case Intrinsic::arm_neon_vrshifts:
9949 case Intrinsic::arm_neon_vrshiftu:
9950 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9954 case Intrinsic::arm_neon_vqshifts:
9955 case Intrinsic::arm_neon_vqshiftu:
9956 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9960 case Intrinsic::arm_neon_vqshiftsu:
9961 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9963 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9965 case Intrinsic::arm_neon_vrshiftn:
9966 case Intrinsic::arm_neon_vqshiftns:
9967 case Intrinsic::arm_neon_vqshiftnu:
9968 case Intrinsic::arm_neon_vqshiftnsu:
9969 case Intrinsic::arm_neon_vqrshiftns:
9970 case Intrinsic::arm_neon_vqrshiftnu:
9971 case Intrinsic::arm_neon_vqrshiftnsu:
9972 // Narrowing shifts require an immediate right shift.
9973 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9975 llvm_unreachable("invalid shift count for narrowing vector shift "
9979 llvm_unreachable("unhandled vector shift");
9983 case Intrinsic::arm_neon_vshifts:
9984 case Intrinsic::arm_neon_vshiftu:
9985 // Opcode already set above.
9987 case Intrinsic::arm_neon_vrshifts:
9988 VShiftOpc = ARMISD::VRSHRs; break;
9989 case Intrinsic::arm_neon_vrshiftu:
9990 VShiftOpc = ARMISD::VRSHRu; break;
9991 case Intrinsic::arm_neon_vrshiftn:
9992 VShiftOpc = ARMISD::VRSHRN; break;
9993 case Intrinsic::arm_neon_vqshifts:
9994 VShiftOpc = ARMISD::VQSHLs; break;
9995 case Intrinsic::arm_neon_vqshiftu:
9996 VShiftOpc = ARMISD::VQSHLu; break;
9997 case Intrinsic::arm_neon_vqshiftsu:
9998 VShiftOpc = ARMISD::VQSHLsu; break;
9999 case Intrinsic::arm_neon_vqshiftns:
10000 VShiftOpc = ARMISD::VQSHRNs; break;
10001 case Intrinsic::arm_neon_vqshiftnu:
10002 VShiftOpc = ARMISD::VQSHRNu; break;
10003 case Intrinsic::arm_neon_vqshiftnsu:
10004 VShiftOpc = ARMISD::VQSHRNsu; break;
10005 case Intrinsic::arm_neon_vqrshiftns:
10006 VShiftOpc = ARMISD::VQRSHRNs; break;
10007 case Intrinsic::arm_neon_vqrshiftnu:
10008 VShiftOpc = ARMISD::VQRSHRNu; break;
10009 case Intrinsic::arm_neon_vqrshiftnsu:
10010 VShiftOpc = ARMISD::VQRSHRNsu; break;
10014 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10015 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10018 case Intrinsic::arm_neon_vshiftins: {
10019 EVT VT = N->getOperand(1).getValueType();
10021 unsigned VShiftOpc = 0;
10023 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10024 VShiftOpc = ARMISD::VSLI;
10025 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10026 VShiftOpc = ARMISD::VSRI;
10028 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10032 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10033 N->getOperand(1), N->getOperand(2),
10034 DAG.getConstant(Cnt, dl, MVT::i32));
10037 case Intrinsic::arm_neon_vqrshifts:
10038 case Intrinsic::arm_neon_vqrshiftu:
10039 // No immediate versions of these to check for.
10046 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10047 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10048 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10049 /// vector element shift counts are generally not legal, and it is hard to see
10050 /// their values after they get legalized to loads from a constant pool.
10051 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10052 const ARMSubtarget *ST) {
10053 EVT VT = N->getValueType(0);
10054 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10055 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10056 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10057 SDValue N1 = N->getOperand(1);
10058 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10059 SDValue N0 = N->getOperand(0);
10060 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10061 DAG.MaskedValueIsZero(N0.getOperand(0),
10062 APInt::getHighBitsSet(32, 16)))
10063 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10067 // Nothing to be done for scalar shifts.
10068 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10069 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10072 assert(ST->hasNEON() && "unexpected vector shift");
10075 switch (N->getOpcode()) {
10076 default: llvm_unreachable("unexpected shift opcode");
10079 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10081 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10082 DAG.getConstant(Cnt, dl, MVT::i32));
10088 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10089 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10090 ARMISD::VSHRs : ARMISD::VSHRu);
10092 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10093 DAG.getConstant(Cnt, dl, MVT::i32));
10099 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10100 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10101 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10102 const ARMSubtarget *ST) {
10103 SDValue N0 = N->getOperand(0);
10105 // Check for sign- and zero-extensions of vector extract operations of 8-
10106 // and 16-bit vector elements. NEON supports these directly. They are
10107 // handled during DAG combining because type legalization will promote them
10108 // to 32-bit types and it is messy to recognize the operations after that.
10109 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10110 SDValue Vec = N0.getOperand(0);
10111 SDValue Lane = N0.getOperand(1);
10112 EVT VT = N->getValueType(0);
10113 EVT EltVT = N0.getValueType();
10114 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10116 if (VT == MVT::i32 &&
10117 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10118 TLI.isTypeLegal(Vec.getValueType()) &&
10119 isa<ConstantSDNode>(Lane)) {
10122 switch (N->getOpcode()) {
10123 default: llvm_unreachable("unexpected opcode");
10124 case ISD::SIGN_EXTEND:
10125 Opc = ARMISD::VGETLANEs;
10127 case ISD::ZERO_EXTEND:
10128 case ISD::ANY_EXTEND:
10129 Opc = ARMISD::VGETLANEu;
10132 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10139 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10140 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10141 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10142 const ARMSubtarget *ST) {
10143 // If the target supports NEON, try to use vmax/vmin instructions for f32
10144 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
10145 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
10146 // a NaN; only do the transformation when it matches that behavior.
10148 // For now only do this when using NEON for FP operations; if using VFP, it
10149 // is not obvious that the benefit outweighs the cost of switching to the
10151 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10152 N->getValueType(0) != MVT::f32)
10155 SDValue CondLHS = N->getOperand(0);
10156 SDValue CondRHS = N->getOperand(1);
10157 SDValue LHS = N->getOperand(2);
10158 SDValue RHS = N->getOperand(3);
10159 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10161 unsigned Opcode = 0;
10163 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10164 IsReversed = false; // x CC y ? x : y
10165 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10166 IsReversed = true ; // x CC y ? y : x
10180 // If LHS is NaN, an ordered comparison will be false and the result will
10181 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
10182 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10183 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10184 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10186 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10187 // will return -0, so vmin can only be used for unsafe math or if one of
10188 // the operands is known to be nonzero.
10189 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10190 !DAG.getTarget().Options.UnsafeFPMath &&
10191 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10193 Opcode = IsReversed ? ISD::FMAXNAN : ISD::FMINNAN;
10202 // If LHS is NaN, an ordered comparison will be false and the result will
10203 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
10204 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10205 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10206 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10208 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10209 // will return +0, so vmax can only be used for unsafe math or if one of
10210 // the operands is known to be nonzero.
10211 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10212 !DAG.getTarget().Options.UnsafeFPMath &&
10213 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10215 Opcode = IsReversed ? ISD::FMINNAN : ISD::FMAXNAN;
10221 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10224 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10226 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10227 SDValue Cmp = N->getOperand(4);
10228 if (Cmp.getOpcode() != ARMISD::CMPZ)
10229 // Only looking at EQ and NE cases.
10232 EVT VT = N->getValueType(0);
10234 SDValue LHS = Cmp.getOperand(0);
10235 SDValue RHS = Cmp.getOperand(1);
10236 SDValue FalseVal = N->getOperand(0);
10237 SDValue TrueVal = N->getOperand(1);
10238 SDValue ARMcc = N->getOperand(2);
10239 ARMCC::CondCodes CC =
10240 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10258 /// FIXME: Turn this into a target neutral optimization?
10260 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10261 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10262 N->getOperand(3), Cmp);
10263 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10265 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10266 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10267 N->getOperand(3), NewCmp);
10270 if (Res.getNode()) {
10271 APInt KnownZero, KnownOne;
10272 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10273 // Capture demanded bits information that would be otherwise lost.
10274 if (KnownZero == 0xfffffffe)
10275 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10276 DAG.getValueType(MVT::i1));
10277 else if (KnownZero == 0xffffff00)
10278 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10279 DAG.getValueType(MVT::i8));
10280 else if (KnownZero == 0xffff0000)
10281 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10282 DAG.getValueType(MVT::i16));
10288 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10289 DAGCombinerInfo &DCI) const {
10290 switch (N->getOpcode()) {
10292 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10293 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10294 case ISD::SUB: return PerformSUBCombine(N, DCI);
10295 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10296 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10297 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10298 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10299 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10300 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10301 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10302 case ISD::STORE: return PerformSTORECombine(N, DCI);
10303 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10304 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10305 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10306 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10307 case ISD::FP_TO_SINT:
10308 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10309 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10310 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10313 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10314 case ISD::SIGN_EXTEND:
10315 case ISD::ZERO_EXTEND:
10316 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10317 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10318 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10319 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10320 case ARMISD::VLD2DUP:
10321 case ARMISD::VLD3DUP:
10322 case ARMISD::VLD4DUP:
10323 return PerformVLDCombine(N, DCI);
10324 case ARMISD::BUILD_VECTOR:
10325 return PerformARMBUILD_VECTORCombine(N, DCI);
10326 case ISD::INTRINSIC_VOID:
10327 case ISD::INTRINSIC_W_CHAIN:
10328 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10329 case Intrinsic::arm_neon_vld1:
10330 case Intrinsic::arm_neon_vld2:
10331 case Intrinsic::arm_neon_vld3:
10332 case Intrinsic::arm_neon_vld4:
10333 case Intrinsic::arm_neon_vld2lane:
10334 case Intrinsic::arm_neon_vld3lane:
10335 case Intrinsic::arm_neon_vld4lane:
10336 case Intrinsic::arm_neon_vst1:
10337 case Intrinsic::arm_neon_vst2:
10338 case Intrinsic::arm_neon_vst3:
10339 case Intrinsic::arm_neon_vst4:
10340 case Intrinsic::arm_neon_vst2lane:
10341 case Intrinsic::arm_neon_vst3lane:
10342 case Intrinsic::arm_neon_vst4lane:
10343 return PerformVLDCombine(N, DCI);
10351 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10353 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10356 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10359 bool *Fast) const {
10360 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10361 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10363 switch (VT.getSimpleVT().SimpleTy) {
10369 // Unaligned access can use (for example) LRDB, LRDH, LDR
10370 if (AllowsUnaligned) {
10372 *Fast = Subtarget->hasV7Ops();
10379 // For any little-endian targets with neon, we can support unaligned ld/st
10380 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10381 // A big-endian target may also explicitly support unaligned accesses
10382 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10392 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10393 unsigned AlignCheck) {
10394 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10395 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10398 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10399 unsigned DstAlign, unsigned SrcAlign,
10400 bool IsMemset, bool ZeroMemset,
10402 MachineFunction &MF) const {
10403 const Function *F = MF.getFunction();
10405 // See if we can use NEON instructions for this...
10406 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10407 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10410 (memOpAlign(SrcAlign, DstAlign, 16) ||
10411 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10413 } else if (Size >= 8 &&
10414 (memOpAlign(SrcAlign, DstAlign, 8) ||
10415 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10421 // Lowering to i32/i16 if the size permits.
10424 else if (Size >= 2)
10427 // Let the target-independent logic figure it out.
10431 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10432 if (Val.getOpcode() != ISD::LOAD)
10435 EVT VT1 = Val.getValueType();
10436 if (!VT1.isSimple() || !VT1.isInteger() ||
10437 !VT2.isSimple() || !VT2.isInteger())
10440 switch (VT1.getSimpleVT().SimpleTy) {
10445 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10452 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10453 EVT VT = ExtVal.getValueType();
10455 if (!isTypeLegal(VT))
10458 // Don't create a loadext if we can fold the extension into a wide/long
10460 // If there's more than one user instruction, the loadext is desirable no
10461 // matter what. There can be two uses by the same instruction.
10462 if (ExtVal->use_empty() ||
10463 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10466 SDNode *U = *ExtVal->use_begin();
10467 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10468 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10474 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10475 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10478 if (!isTypeLegal(EVT::getEVT(Ty1)))
10481 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10483 // Assuming the caller doesn't have a zeroext or signext return parameter,
10484 // truncation all the way down to i1 is valid.
10489 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10493 unsigned Scale = 1;
10494 switch (VT.getSimpleVT().SimpleTy) {
10495 default: return false;
10510 if ((V & (Scale - 1)) != 0)
10513 return V == (V & ((1LL << 5) - 1));
10516 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10517 const ARMSubtarget *Subtarget) {
10518 bool isNeg = false;
10524 switch (VT.getSimpleVT().SimpleTy) {
10525 default: return false;
10530 // + imm12 or - imm8
10532 return V == (V & ((1LL << 8) - 1));
10533 return V == (V & ((1LL << 12) - 1));
10536 // Same as ARM mode. FIXME: NEON?
10537 if (!Subtarget->hasVFP2())
10542 return V == (V & ((1LL << 8) - 1));
10546 /// isLegalAddressImmediate - Return true if the integer value can be used
10547 /// as the offset of the target addressing mode for load / store of the
10549 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10550 const ARMSubtarget *Subtarget) {
10554 if (!VT.isSimple())
10557 if (Subtarget->isThumb1Only())
10558 return isLegalT1AddressImmediate(V, VT);
10559 else if (Subtarget->isThumb2())
10560 return isLegalT2AddressImmediate(V, VT, Subtarget);
10565 switch (VT.getSimpleVT().SimpleTy) {
10566 default: return false;
10571 return V == (V & ((1LL << 12) - 1));
10574 return V == (V & ((1LL << 8) - 1));
10577 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10582 return V == (V & ((1LL << 8) - 1));
10586 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10588 int Scale = AM.Scale;
10592 switch (VT.getSimpleVT().SimpleTy) {
10593 default: return false;
10601 Scale = Scale & ~1;
10602 return Scale == 2 || Scale == 4 || Scale == 8;
10605 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10609 // Note, we allow "void" uses (basically, uses that aren't loads or
10610 // stores), because arm allows folding a scale into many arithmetic
10611 // operations. This should be made more precise and revisited later.
10613 // Allow r << imm, but the imm has to be a multiple of two.
10614 if (Scale & 1) return false;
10615 return isPowerOf2_32(Scale);
10619 /// isLegalAddressingMode - Return true if the addressing mode represented
10620 /// by AM is legal for this target, for a load/store of the specified type.
10621 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10622 const AddrMode &AM, Type *Ty,
10623 unsigned AS) const {
10624 EVT VT = getValueType(DL, Ty, true);
10625 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10628 // Can never fold addr of global into load/store.
10632 switch (AM.Scale) {
10633 case 0: // no scale reg, must be "r+i" or "r", or "i".
10636 if (Subtarget->isThumb1Only())
10640 // ARM doesn't support any R+R*scale+imm addr modes.
10644 if (!VT.isSimple())
10647 if (Subtarget->isThumb2())
10648 return isLegalT2ScaledAddressingMode(AM, VT);
10650 int Scale = AM.Scale;
10651 switch (VT.getSimpleVT().SimpleTy) {
10652 default: return false;
10656 if (Scale < 0) Scale = -Scale;
10660 return isPowerOf2_32(Scale & ~1);
10664 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10669 // Note, we allow "void" uses (basically, uses that aren't loads or
10670 // stores), because arm allows folding a scale into many arithmetic
10671 // operations. This should be made more precise and revisited later.
10673 // Allow r << imm, but the imm has to be a multiple of two.
10674 if (Scale & 1) return false;
10675 return isPowerOf2_32(Scale);
10681 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10682 /// icmp immediate, that is the target has icmp instructions which can compare
10683 /// a register against the immediate without having to materialize the
10684 /// immediate into a register.
10685 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10686 // Thumb2 and ARM modes can use cmn for negative immediates.
10687 if (!Subtarget->isThumb())
10688 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10689 if (Subtarget->isThumb2())
10690 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10691 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10692 return Imm >= 0 && Imm <= 255;
10695 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10696 /// *or sub* immediate, that is the target has add or sub instructions which can
10697 /// add a register with the immediate without having to materialize the
10698 /// immediate into a register.
10699 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10700 // Same encoding for add/sub, just flip the sign.
10701 int64_t AbsImm = std::abs(Imm);
10702 if (!Subtarget->isThumb())
10703 return ARM_AM::getSOImmVal(AbsImm) != -1;
10704 if (Subtarget->isThumb2())
10705 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10706 // Thumb1 only has 8-bit unsigned immediate.
10707 return AbsImm >= 0 && AbsImm <= 255;
10710 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10711 bool isSEXTLoad, SDValue &Base,
10712 SDValue &Offset, bool &isInc,
10713 SelectionDAG &DAG) {
10714 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10717 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10718 // AddressingMode 3
10719 Base = Ptr->getOperand(0);
10720 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10721 int RHSC = (int)RHS->getZExtValue();
10722 if (RHSC < 0 && RHSC > -256) {
10723 assert(Ptr->getOpcode() == ISD::ADD);
10725 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10729 isInc = (Ptr->getOpcode() == ISD::ADD);
10730 Offset = Ptr->getOperand(1);
10732 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10733 // AddressingMode 2
10734 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10735 int RHSC = (int)RHS->getZExtValue();
10736 if (RHSC < 0 && RHSC > -0x1000) {
10737 assert(Ptr->getOpcode() == ISD::ADD);
10739 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10740 Base = Ptr->getOperand(0);
10745 if (Ptr->getOpcode() == ISD::ADD) {
10747 ARM_AM::ShiftOpc ShOpcVal=
10748 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10749 if (ShOpcVal != ARM_AM::no_shift) {
10750 Base = Ptr->getOperand(1);
10751 Offset = Ptr->getOperand(0);
10753 Base = Ptr->getOperand(0);
10754 Offset = Ptr->getOperand(1);
10759 isInc = (Ptr->getOpcode() == ISD::ADD);
10760 Base = Ptr->getOperand(0);
10761 Offset = Ptr->getOperand(1);
10765 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10769 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10770 bool isSEXTLoad, SDValue &Base,
10771 SDValue &Offset, bool &isInc,
10772 SelectionDAG &DAG) {
10773 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10776 Base = Ptr->getOperand(0);
10777 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10778 int RHSC = (int)RHS->getZExtValue();
10779 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10780 assert(Ptr->getOpcode() == ISD::ADD);
10782 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10784 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10785 isInc = Ptr->getOpcode() == ISD::ADD;
10786 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10794 /// getPreIndexedAddressParts - returns true by value, base pointer and
10795 /// offset pointer and addressing mode by reference if the node's address
10796 /// can be legally represented as pre-indexed load / store address.
10798 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10800 ISD::MemIndexedMode &AM,
10801 SelectionDAG &DAG) const {
10802 if (Subtarget->isThumb1Only())
10807 bool isSEXTLoad = false;
10808 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10809 Ptr = LD->getBasePtr();
10810 VT = LD->getMemoryVT();
10811 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10812 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10813 Ptr = ST->getBasePtr();
10814 VT = ST->getMemoryVT();
10819 bool isLegal = false;
10820 if (Subtarget->isThumb2())
10821 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10822 Offset, isInc, DAG);
10824 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10825 Offset, isInc, DAG);
10829 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10833 /// getPostIndexedAddressParts - returns true by value, base pointer and
10834 /// offset pointer and addressing mode by reference if this node can be
10835 /// combined with a load / store to form a post-indexed load / store.
10836 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10839 ISD::MemIndexedMode &AM,
10840 SelectionDAG &DAG) const {
10841 if (Subtarget->isThumb1Only())
10846 bool isSEXTLoad = false;
10847 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10848 VT = LD->getMemoryVT();
10849 Ptr = LD->getBasePtr();
10850 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10851 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10852 VT = ST->getMemoryVT();
10853 Ptr = ST->getBasePtr();
10858 bool isLegal = false;
10859 if (Subtarget->isThumb2())
10860 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10863 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10869 // Swap base ptr and offset to catch more post-index load / store when
10870 // it's legal. In Thumb2 mode, offset must be an immediate.
10871 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10872 !Subtarget->isThumb2())
10873 std::swap(Base, Offset);
10875 // Post-indexed load / store update the base pointer.
10880 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10884 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10887 const SelectionDAG &DAG,
10888 unsigned Depth) const {
10889 unsigned BitWidth = KnownOne.getBitWidth();
10890 KnownZero = KnownOne = APInt(BitWidth, 0);
10891 switch (Op.getOpcode()) {
10897 // These nodes' second result is a boolean
10898 if (Op.getResNo() == 0)
10900 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10902 case ARMISD::CMOV: {
10903 // Bits are known zero/one if known on the LHS and RHS.
10904 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10905 if (KnownZero == 0 && KnownOne == 0) return;
10907 APInt KnownZeroRHS, KnownOneRHS;
10908 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10909 KnownZero &= KnownZeroRHS;
10910 KnownOne &= KnownOneRHS;
10913 case ISD::INTRINSIC_W_CHAIN: {
10914 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10915 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10918 case Intrinsic::arm_ldaex:
10919 case Intrinsic::arm_ldrex: {
10920 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10921 unsigned MemBits = VT.getScalarType().getSizeInBits();
10922 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10930 //===----------------------------------------------------------------------===//
10931 // ARM Inline Assembly Support
10932 //===----------------------------------------------------------------------===//
10934 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10935 // Looking for "rev" which is V6+.
10936 if (!Subtarget->hasV6Ops())
10939 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10940 std::string AsmStr = IA->getAsmString();
10941 SmallVector<StringRef, 4> AsmPieces;
10942 SplitString(AsmStr, AsmPieces, ";\n");
10944 switch (AsmPieces.size()) {
10945 default: return false;
10947 AsmStr = AsmPieces[0];
10949 SplitString(AsmStr, AsmPieces, " \t,");
10952 if (AsmPieces.size() == 3 &&
10953 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10954 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10955 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10956 if (Ty && Ty->getBitWidth() == 32)
10957 return IntrinsicLowering::LowerToByteSwap(CI);
10965 /// getConstraintType - Given a constraint letter, return the type of
10966 /// constraint it is for this target.
10967 ARMTargetLowering::ConstraintType
10968 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10969 if (Constraint.size() == 1) {
10970 switch (Constraint[0]) {
10972 case 'l': return C_RegisterClass;
10973 case 'w': return C_RegisterClass;
10974 case 'h': return C_RegisterClass;
10975 case 'x': return C_RegisterClass;
10976 case 't': return C_RegisterClass;
10977 case 'j': return C_Other; // Constant for movw.
10978 // An address with a single base register. Due to the way we
10979 // currently handle addresses it is the same as an 'r' memory constraint.
10980 case 'Q': return C_Memory;
10982 } else if (Constraint.size() == 2) {
10983 switch (Constraint[0]) {
10985 // All 'U+' constraints are addresses.
10986 case 'U': return C_Memory;
10989 return TargetLowering::getConstraintType(Constraint);
10992 /// Examine constraint type and operand type and determine a weight value.
10993 /// This object must already have been set up with the operand type
10994 /// and the current alternative constraint selected.
10995 TargetLowering::ConstraintWeight
10996 ARMTargetLowering::getSingleConstraintMatchWeight(
10997 AsmOperandInfo &info, const char *constraint) const {
10998 ConstraintWeight weight = CW_Invalid;
10999 Value *CallOperandVal = info.CallOperandVal;
11000 // If we don't have a value, we can't do a match,
11001 // but allow it at the lowest weight.
11002 if (!CallOperandVal)
11004 Type *type = CallOperandVal->getType();
11005 // Look at the constraint type.
11006 switch (*constraint) {
11008 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11011 if (type->isIntegerTy()) {
11012 if (Subtarget->isThumb())
11013 weight = CW_SpecificReg;
11015 weight = CW_Register;
11019 if (type->isFloatingPointTy())
11020 weight = CW_Register;
11026 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11027 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11028 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11029 if (Constraint.size() == 1) {
11030 // GCC ARM Constraint Letters
11031 switch (Constraint[0]) {
11032 case 'l': // Low regs or general regs.
11033 if (Subtarget->isThumb())
11034 return RCPair(0U, &ARM::tGPRRegClass);
11035 return RCPair(0U, &ARM::GPRRegClass);
11036 case 'h': // High regs or no regs.
11037 if (Subtarget->isThumb())
11038 return RCPair(0U, &ARM::hGPRRegClass);
11041 if (Subtarget->isThumb1Only())
11042 return RCPair(0U, &ARM::tGPRRegClass);
11043 return RCPair(0U, &ARM::GPRRegClass);
11045 if (VT == MVT::Other)
11047 if (VT == MVT::f32)
11048 return RCPair(0U, &ARM::SPRRegClass);
11049 if (VT.getSizeInBits() == 64)
11050 return RCPair(0U, &ARM::DPRRegClass);
11051 if (VT.getSizeInBits() == 128)
11052 return RCPair(0U, &ARM::QPRRegClass);
11055 if (VT == MVT::Other)
11057 if (VT == MVT::f32)
11058 return RCPair(0U, &ARM::SPR_8RegClass);
11059 if (VT.getSizeInBits() == 64)
11060 return RCPair(0U, &ARM::DPR_8RegClass);
11061 if (VT.getSizeInBits() == 128)
11062 return RCPair(0U, &ARM::QPR_8RegClass);
11065 if (VT == MVT::f32)
11066 return RCPair(0U, &ARM::SPRRegClass);
11070 if (StringRef("{cc}").equals_lower(Constraint))
11071 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11073 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11076 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11077 /// vector. If it is invalid, don't add anything to Ops.
11078 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11079 std::string &Constraint,
11080 std::vector<SDValue>&Ops,
11081 SelectionDAG &DAG) const {
11084 // Currently only support length 1 constraints.
11085 if (Constraint.length() != 1) return;
11087 char ConstraintLetter = Constraint[0];
11088 switch (ConstraintLetter) {
11091 case 'I': case 'J': case 'K': case 'L':
11092 case 'M': case 'N': case 'O':
11093 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11097 int64_t CVal64 = C->getSExtValue();
11098 int CVal = (int) CVal64;
11099 // None of these constraints allow values larger than 32 bits. Check
11100 // that the value fits in an int.
11101 if (CVal != CVal64)
11104 switch (ConstraintLetter) {
11106 // Constant suitable for movw, must be between 0 and
11108 if (Subtarget->hasV6T2Ops())
11109 if (CVal >= 0 && CVal <= 65535)
11113 if (Subtarget->isThumb1Only()) {
11114 // This must be a constant between 0 and 255, for ADD
11116 if (CVal >= 0 && CVal <= 255)
11118 } else if (Subtarget->isThumb2()) {
11119 // A constant that can be used as an immediate value in a
11120 // data-processing instruction.
11121 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11124 // A constant that can be used as an immediate value in a
11125 // data-processing instruction.
11126 if (ARM_AM::getSOImmVal(CVal) != -1)
11132 if (Subtarget->isThumb()) { // FIXME thumb2
11133 // This must be a constant between -255 and -1, for negated ADD
11134 // immediates. This can be used in GCC with an "n" modifier that
11135 // prints the negated value, for use with SUB instructions. It is
11136 // not useful otherwise but is implemented for compatibility.
11137 if (CVal >= -255 && CVal <= -1)
11140 // This must be a constant between -4095 and 4095. It is not clear
11141 // what this constraint is intended for. Implemented for
11142 // compatibility with GCC.
11143 if (CVal >= -4095 && CVal <= 4095)
11149 if (Subtarget->isThumb1Only()) {
11150 // A 32-bit value where only one byte has a nonzero value. Exclude
11151 // zero to match GCC. This constraint is used by GCC internally for
11152 // constants that can be loaded with a move/shift combination.
11153 // It is not useful otherwise but is implemented for compatibility.
11154 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11156 } else if (Subtarget->isThumb2()) {
11157 // A constant whose bitwise inverse can be used as an immediate
11158 // value in a data-processing instruction. This can be used in GCC
11159 // with a "B" modifier that prints the inverted value, for use with
11160 // BIC and MVN instructions. It is not useful otherwise but is
11161 // implemented for compatibility.
11162 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11165 // A constant whose bitwise inverse can be used as an immediate
11166 // value in a data-processing instruction. This can be used in GCC
11167 // with a "B" modifier that prints the inverted value, for use with
11168 // BIC and MVN instructions. It is not useful otherwise but is
11169 // implemented for compatibility.
11170 if (ARM_AM::getSOImmVal(~CVal) != -1)
11176 if (Subtarget->isThumb1Only()) {
11177 // This must be a constant between -7 and 7,
11178 // for 3-operand ADD/SUB immediate instructions.
11179 if (CVal >= -7 && CVal < 7)
11181 } else if (Subtarget->isThumb2()) {
11182 // A constant whose negation can be used as an immediate value in a
11183 // data-processing instruction. This can be used in GCC with an "n"
11184 // modifier that prints the negated value, for use with SUB
11185 // instructions. It is not useful otherwise but is implemented for
11187 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11190 // A constant whose negation can be used as an immediate value in a
11191 // data-processing instruction. This can be used in GCC with an "n"
11192 // modifier that prints the negated value, for use with SUB
11193 // instructions. It is not useful otherwise but is implemented for
11195 if (ARM_AM::getSOImmVal(-CVal) != -1)
11201 if (Subtarget->isThumb()) { // FIXME thumb2
11202 // This must be a multiple of 4 between 0 and 1020, for
11203 // ADD sp + immediate.
11204 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11207 // A power of two or a constant between 0 and 32. This is used in
11208 // GCC for the shift amount on shifted register operands, but it is
11209 // useful in general for any shift amounts.
11210 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11216 if (Subtarget->isThumb()) { // FIXME thumb2
11217 // This must be a constant between 0 and 31, for shift amounts.
11218 if (CVal >= 0 && CVal <= 31)
11224 if (Subtarget->isThumb()) { // FIXME thumb2
11225 // This must be a multiple of 4 between -508 and 508, for
11226 // ADD/SUB sp = sp + immediate.
11227 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11232 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11236 if (Result.getNode()) {
11237 Ops.push_back(Result);
11240 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11243 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11244 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11245 "Register-based DivRem lowering only");
11246 unsigned Opcode = Op->getOpcode();
11247 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11248 "Invalid opcode for Div/Rem lowering");
11249 bool isSigned = (Opcode == ISD::SDIVREM);
11250 EVT VT = Op->getValueType(0);
11251 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11254 switch (VT.getSimpleVT().SimpleTy) {
11255 default: llvm_unreachable("Unexpected request for libcall!");
11256 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11257 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11258 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11259 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11262 SDValue InChain = DAG.getEntryNode();
11264 TargetLowering::ArgListTy Args;
11265 TargetLowering::ArgListEntry Entry;
11266 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11267 EVT ArgVT = Op->getOperand(i).getValueType();
11268 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11269 Entry.Node = Op->getOperand(i);
11271 Entry.isSExt = isSigned;
11272 Entry.isZExt = !isSigned;
11273 Args.push_back(Entry);
11276 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11277 getPointerTy(DAG.getDataLayout()));
11279 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11282 TargetLowering::CallLoweringInfo CLI(DAG);
11283 CLI.setDebugLoc(dl).setChain(InChain)
11284 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11285 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11287 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11288 return CallInfo.first;
11292 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11293 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11297 SDValue Chain = Op.getOperand(0);
11298 SDValue Size = Op.getOperand(1);
11300 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11301 DAG.getConstant(2, DL, MVT::i32));
11304 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11305 Flag = Chain.getValue(1);
11307 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11308 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11310 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11311 Chain = NewSP.getValue(1);
11313 SDValue Ops[2] = { NewSP, Chain };
11314 return DAG.getMergeValues(Ops, DL);
11317 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11318 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11319 "Unexpected type for custom-lowering FP_EXTEND");
11322 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11324 SDValue SrcVal = Op.getOperand(0);
11325 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11326 /*isSigned*/ false, SDLoc(Op)).first;
11329 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11330 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11331 Subtarget->isFPOnlySP() &&
11332 "Unexpected type for custom-lowering FP_ROUND");
11335 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11337 SDValue SrcVal = Op.getOperand(0);
11338 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11339 /*isSigned*/ false, SDLoc(Op)).first;
11343 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11344 // The ARM target isn't yet aware of offsets.
11348 bool ARM::isBitFieldInvertedMask(unsigned v) {
11349 if (v == 0xffffffff)
11352 // there can be 1's on either or both "outsides", all the "inside"
11353 // bits must be 0's
11354 return isShiftedMask_32(~v);
11357 /// isFPImmLegal - Returns true if the target can instruction select the
11358 /// specified FP immediate natively. If false, the legalizer will
11359 /// materialize the FP immediate as a load from a constant pool.
11360 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11361 if (!Subtarget->hasVFP3())
11363 if (VT == MVT::f32)
11364 return ARM_AM::getFP32Imm(Imm) != -1;
11365 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11366 return ARM_AM::getFP64Imm(Imm) != -1;
11370 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11371 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11372 /// specified in the intrinsic calls.
11373 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11375 unsigned Intrinsic) const {
11376 switch (Intrinsic) {
11377 case Intrinsic::arm_neon_vld1:
11378 case Intrinsic::arm_neon_vld2:
11379 case Intrinsic::arm_neon_vld3:
11380 case Intrinsic::arm_neon_vld4:
11381 case Intrinsic::arm_neon_vld2lane:
11382 case Intrinsic::arm_neon_vld3lane:
11383 case Intrinsic::arm_neon_vld4lane: {
11384 Info.opc = ISD::INTRINSIC_W_CHAIN;
11385 // Conservatively set memVT to the entire set of vectors loaded.
11386 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11387 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11388 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11389 Info.ptrVal = I.getArgOperand(0);
11391 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11392 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11393 Info.vol = false; // volatile loads with NEON intrinsics not supported
11394 Info.readMem = true;
11395 Info.writeMem = false;
11398 case Intrinsic::arm_neon_vst1:
11399 case Intrinsic::arm_neon_vst2:
11400 case Intrinsic::arm_neon_vst3:
11401 case Intrinsic::arm_neon_vst4:
11402 case Intrinsic::arm_neon_vst2lane:
11403 case Intrinsic::arm_neon_vst3lane:
11404 case Intrinsic::arm_neon_vst4lane: {
11405 Info.opc = ISD::INTRINSIC_VOID;
11406 // Conservatively set memVT to the entire set of vectors stored.
11407 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11408 unsigned NumElts = 0;
11409 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11410 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11411 if (!ArgTy->isVectorTy())
11413 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11415 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11416 Info.ptrVal = I.getArgOperand(0);
11418 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11419 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11420 Info.vol = false; // volatile stores with NEON intrinsics not supported
11421 Info.readMem = false;
11422 Info.writeMem = true;
11425 case Intrinsic::arm_ldaex:
11426 case Intrinsic::arm_ldrex: {
11427 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11428 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11429 Info.opc = ISD::INTRINSIC_W_CHAIN;
11430 Info.memVT = MVT::getVT(PtrTy->getElementType());
11431 Info.ptrVal = I.getArgOperand(0);
11433 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11435 Info.readMem = true;
11436 Info.writeMem = false;
11439 case Intrinsic::arm_stlex:
11440 case Intrinsic::arm_strex: {
11441 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11442 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11443 Info.opc = ISD::INTRINSIC_W_CHAIN;
11444 Info.memVT = MVT::getVT(PtrTy->getElementType());
11445 Info.ptrVal = I.getArgOperand(1);
11447 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11449 Info.readMem = false;
11450 Info.writeMem = true;
11453 case Intrinsic::arm_stlexd:
11454 case Intrinsic::arm_strexd: {
11455 Info.opc = ISD::INTRINSIC_W_CHAIN;
11456 Info.memVT = MVT::i64;
11457 Info.ptrVal = I.getArgOperand(2);
11461 Info.readMem = false;
11462 Info.writeMem = true;
11465 case Intrinsic::arm_ldaexd:
11466 case Intrinsic::arm_ldrexd: {
11467 Info.opc = ISD::INTRINSIC_W_CHAIN;
11468 Info.memVT = MVT::i64;
11469 Info.ptrVal = I.getArgOperand(0);
11473 Info.readMem = true;
11474 Info.writeMem = false;
11484 /// \brief Returns true if it is beneficial to convert a load of a constant
11485 /// to just the constant itself.
11486 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11488 assert(Ty->isIntegerTy());
11490 unsigned Bits = Ty->getPrimitiveSizeInBits();
11491 if (Bits == 0 || Bits > 32)
11496 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11498 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11499 ARM_MB::MemBOpt Domain) const {
11500 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11502 // First, if the target has no DMB, see what fallback we can use.
11503 if (!Subtarget->hasDataBarrier()) {
11504 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11505 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11507 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11508 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11509 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11510 Builder.getInt32(0), Builder.getInt32(7),
11511 Builder.getInt32(10), Builder.getInt32(5)};
11512 return Builder.CreateCall(MCR, args);
11514 // Instead of using barriers, atomic accesses on these subtargets use
11516 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11519 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11520 // Only a full system barrier exists in the M-class architectures.
11521 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11522 Constant *CDomain = Builder.getInt32(Domain);
11523 return Builder.CreateCall(DMB, CDomain);
11527 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11528 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11529 AtomicOrdering Ord, bool IsStore,
11530 bool IsLoad) const {
11531 if (!getInsertFencesForAtomic())
11537 llvm_unreachable("Invalid fence: unordered/non-atomic");
11540 return nullptr; // Nothing to do
11541 case SequentiallyConsistent:
11543 return nullptr; // Nothing to do
11546 case AcquireRelease:
11547 if (Subtarget->isSwift())
11548 return makeDMB(Builder, ARM_MB::ISHST);
11549 // FIXME: add a comment with a link to documentation justifying this.
11551 return makeDMB(Builder, ARM_MB::ISH);
11553 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11556 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11557 AtomicOrdering Ord, bool IsStore,
11558 bool IsLoad) const {
11559 if (!getInsertFencesForAtomic())
11565 llvm_unreachable("Invalid fence: unordered/not-atomic");
11568 return nullptr; // Nothing to do
11570 case AcquireRelease:
11571 case SequentiallyConsistent:
11572 return makeDMB(Builder, ARM_MB::ISH);
11574 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11577 // Loads and stores less than 64-bits are already atomic; ones above that
11578 // are doomed anyway, so defer to the default libcall and blame the OS when
11579 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11580 // anything for those.
11581 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11582 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11583 return (Size == 64) && !Subtarget->isMClass();
11586 // Loads and stores less than 64-bits are already atomic; ones above that
11587 // are doomed anyway, so defer to the default libcall and blame the OS when
11588 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11589 // anything for those.
11590 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11591 // guarantee, see DDI0406C ARM architecture reference manual,
11592 // sections A8.8.72-74 LDRD)
11593 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11594 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11595 return (Size == 64) && !Subtarget->isMClass();
11598 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11599 // and up to 64 bits on the non-M profiles
11600 TargetLoweringBase::AtomicRMWExpansionKind
11601 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11602 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11603 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11604 ? AtomicRMWExpansionKind::LLSC
11605 : AtomicRMWExpansionKind::None;
11608 // This has so far only been implemented for MachO.
11609 bool ARMTargetLowering::useLoadStackGuardNode() const {
11610 return Subtarget->isTargetMachO();
11613 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11614 unsigned &Cost) const {
11615 // If we do not have NEON, vector types are not natively supported.
11616 if (!Subtarget->hasNEON())
11619 // Floating point values and vector values map to the same register file.
11620 // Therefore, although we could do a store extract of a vector type, this is
11621 // better to leave at float as we have more freedom in the addressing mode for
11623 if (VectorTy->isFPOrFPVectorTy())
11626 // If the index is unknown at compile time, this is very expensive to lower
11627 // and it is not possible to combine the store with the extract.
11628 if (!isa<ConstantInt>(Idx))
11631 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11632 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11633 // We can do a store + vector extract on any vector that fits perfectly in a D
11635 if (BitWidth == 64 || BitWidth == 128) {
11642 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11643 AtomicOrdering Ord) const {
11644 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11645 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11646 bool IsAcquire = isAtLeastAcquire(Ord);
11648 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11649 // intrinsic must return {i32, i32} and we have to recombine them into a
11650 // single i64 here.
11651 if (ValTy->getPrimitiveSizeInBits() == 64) {
11652 Intrinsic::ID Int =
11653 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11654 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11656 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11657 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11659 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11660 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11661 if (!Subtarget->isLittle())
11662 std::swap (Lo, Hi);
11663 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11664 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11665 return Builder.CreateOr(
11666 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11669 Type *Tys[] = { Addr->getType() };
11670 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11671 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11673 return Builder.CreateTruncOrBitCast(
11674 Builder.CreateCall(Ldrex, Addr),
11675 cast<PointerType>(Addr->getType())->getElementType());
11678 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11680 AtomicOrdering Ord) const {
11681 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11682 bool IsRelease = isAtLeastRelease(Ord);
11684 // Since the intrinsics must have legal type, the i64 intrinsics take two
11685 // parameters: "i32, i32". We must marshal Val into the appropriate form
11686 // before the call.
11687 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11688 Intrinsic::ID Int =
11689 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11690 Function *Strex = Intrinsic::getDeclaration(M, Int);
11691 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11693 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11694 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11695 if (!Subtarget->isLittle())
11696 std::swap (Lo, Hi);
11697 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11698 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11701 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11702 Type *Tys[] = { Addr->getType() };
11703 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11705 return Builder.CreateCall(
11706 Strex, {Builder.CreateZExtOrBitCast(
11707 Val, Strex->getFunctionType()->getParamType(0)),
11711 /// \brief Lower an interleaved load into a vldN intrinsic.
11713 /// E.g. Lower an interleaved load (Factor = 2):
11714 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11715 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
11716 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
11719 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11720 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11721 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11722 bool ARMTargetLowering::lowerInterleavedLoad(
11723 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11724 ArrayRef<unsigned> Indices, unsigned Factor) const {
11725 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11726 "Invalid interleave factor");
11727 assert(!Shuffles.empty() && "Empty shufflevector input");
11728 assert(Shuffles.size() == Indices.size() &&
11729 "Unmatched number of shufflevectors and indices");
11731 VectorType *VecTy = Shuffles[0]->getType();
11732 Type *EltTy = VecTy->getVectorElementType();
11734 const DataLayout &DL = LI->getModule()->getDataLayout();
11735 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11736 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11738 // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11739 // support i64/f64 element).
11740 if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11743 // A pointer vector can not be the return type of the ldN intrinsics. Need to
11744 // load integer vectors first and then convert to pointer vectors.
11745 if (EltTy->isPointerTy())
11747 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11749 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11750 Intrinsic::arm_neon_vld3,
11751 Intrinsic::arm_neon_vld4};
11753 Function *VldnFunc =
11754 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11756 IRBuilder<> Builder(LI);
11757 SmallVector<Value *, 2> Ops;
11759 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11760 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11761 Ops.push_back(Builder.getInt32(LI->getAlignment()));
11763 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11765 // Replace uses of each shufflevector with the corresponding vector loaded
11767 for (unsigned i = 0; i < Shuffles.size(); i++) {
11768 ShuffleVectorInst *SV = Shuffles[i];
11769 unsigned Index = Indices[i];
11771 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11773 // Convert the integer vector to pointer vector if the element is pointer.
11774 if (EltTy->isPointerTy())
11775 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11777 SV->replaceAllUsesWith(SubVec);
11783 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11785 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11786 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11787 unsigned NumElts) {
11788 SmallVector<Constant *, 16> Mask;
11789 for (unsigned i = 0; i < NumElts; i++)
11790 Mask.push_back(Builder.getInt32(Start + i));
11792 return ConstantVector::get(Mask);
11795 /// \brief Lower an interleaved store into a vstN intrinsic.
11797 /// E.g. Lower an interleaved store (Factor = 3):
11798 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11799 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11800 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11803 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11804 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11805 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11806 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11808 /// Note that the new shufflevectors will be removed and we'll only generate one
11809 /// vst3 instruction in CodeGen.
11810 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11811 ShuffleVectorInst *SVI,
11812 unsigned Factor) const {
11813 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11814 "Invalid interleave factor");
11816 VectorType *VecTy = SVI->getType();
11817 assert(VecTy->getVectorNumElements() % Factor == 0 &&
11818 "Invalid interleaved store");
11820 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11821 Type *EltTy = VecTy->getVectorElementType();
11822 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11824 const DataLayout &DL = SI->getModule()->getDataLayout();
11825 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11826 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11828 // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11829 // doesn't support i64/f64 element).
11830 if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11833 Value *Op0 = SVI->getOperand(0);
11834 Value *Op1 = SVI->getOperand(1);
11835 IRBuilder<> Builder(SI);
11837 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11838 // vectors to integer vectors.
11839 if (EltTy->isPointerTy()) {
11840 Type *IntTy = DL.getIntPtrType(EltTy);
11842 // Convert to the corresponding integer vector.
11844 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11845 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11846 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11848 SubVecTy = VectorType::get(IntTy, NumSubElts);
11851 static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11852 Intrinsic::arm_neon_vst3,
11853 Intrinsic::arm_neon_vst4};
11854 Function *VstNFunc = Intrinsic::getDeclaration(
11855 SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11857 SmallVector<Value *, 6> Ops;
11859 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11860 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11862 // Split the shufflevector operands into sub vectors for the new vstN call.
11863 for (unsigned i = 0; i < Factor; i++)
11864 Ops.push_back(Builder.CreateShuffleVector(
11865 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11867 Ops.push_back(Builder.getInt32(SI->getAlignment()));
11868 Builder.CreateCall(VstNFunc, Ops);
11880 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11881 uint64_t &Members) {
11882 if (auto *ST = dyn_cast<StructType>(Ty)) {
11883 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11884 uint64_t SubMembers = 0;
11885 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11887 Members += SubMembers;
11889 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11890 uint64_t SubMembers = 0;
11891 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11893 Members += SubMembers * AT->getNumElements();
11894 } else if (Ty->isFloatTy()) {
11895 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11899 } else if (Ty->isDoubleTy()) {
11900 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11904 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11911 return VT->getBitWidth() == 64;
11913 return VT->getBitWidth() == 128;
11915 switch (VT->getBitWidth()) {
11928 return (Members > 0 && Members <= 4);
11931 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11932 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11933 /// passing according to AAPCS rules.
11934 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11935 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11936 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11937 CallingConv::ARM_AAPCS_VFP)
11940 HABaseType Base = HA_UNKNOWN;
11941 uint64_t Members = 0;
11942 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11943 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11945 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11946 return IsHA || IsIntArray;